1
0
mirror of https://github.com/danog/amp.git synced 2024-12-11 17:09:40 +01:00
amp/test/Iterator/MapTest.php

101 lines
2.6 KiB
PHP
Raw Normal View History

<?php
2020-05-13 17:15:21 +02:00
namespace Amp\Test\Iterator;
use Amp\Emitter;
2017-04-27 17:51:06 +02:00
use Amp\Iterator;
2020-09-28 05:19:52 +02:00
use Amp\PHPUnit\AsyncTestCase;
use Amp\PHPUnit\TestException;
2017-04-23 14:39:19 +02:00
use Amp\Producer;
2020-09-28 05:19:52 +02:00
class MapTest extends AsyncTestCase
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
public function testNoValuesEmitted(): \Generator
2018-06-18 20:00:01 +02:00
{
$invoked = false;
2020-09-28 05:19:52 +02:00
$emitter = new Emitter;
2020-09-28 05:19:52 +02:00
$iterator = Iterator\map($emitter->iterate(), function ($value) use (&$invoked) {
$invoked = true;
});
2020-09-28 05:19:52 +02:00
$this->assertInstanceOf(Iterator::class, $iterator);
2020-09-28 05:19:52 +02:00
$emitter->complete();
$this->assertFalse(yield $iterator->advance());
$this->assertFalse($invoked);
}
2020-09-28 05:19:52 +02:00
public function testValuesEmitted(): \Generator
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
$count = 0;
$values = [1, 2, 3];
$producer = new Producer(function (callable $emit) use ($values) {
foreach ($values as $value) {
yield $emit($value);
2017-04-27 17:32:53 +02:00
}
2020-09-28 05:19:52 +02:00
});
2020-09-28 05:19:52 +02:00
$iterator = Iterator\map($producer, function ($value) use (&$count) {
++$count;
return $value + 1;
});
2020-09-28 05:19:52 +02:00
while (yield $iterator->advance()) {
$this->assertSame(\array_shift($values) + 1, $iterator->getCurrent());
}
$this->assertSame(3, $count);
}
/**
* @depends testValuesEmitted
*/
2020-09-28 05:19:52 +02:00
public function testOnNextCallbackThrows(): \Generator
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
$values = [1, 2, 3];
$exception = new TestException;
$producer = new Producer(function (callable $emit) use ($values) {
foreach ($values as $value) {
yield $emit($value);
2017-04-27 17:32:53 +02:00
}
});
2020-09-28 05:19:52 +02:00
$iterator = Iterator\map($producer, function () use ($exception) {
throw $exception;
});
try {
yield $iterator->advance();
$this->fail("The exception thrown from the map callback should be thrown from advance()");
} catch (TestException $reason) {
$this->assertSame($reason, $exception);
}
}
2020-09-28 05:19:52 +02:00
public function testIteratorFails(): \Generator
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
$invoked = false;
$exception = new TestException;
$emitter = new Emitter;
2020-09-28 05:19:52 +02:00
$iterator = Iterator\map($emitter->iterate(), function ($value) use (&$invoked) {
$invoked = true;
});
2020-09-28 05:19:52 +02:00
$emitter->fail($exception);
try {
yield $iterator->advance();
$this->fail("The exception used to fail the iterator should be thrown from advance()");
} catch (TestException $reason) {
$this->assertSame($reason, $exception);
}
$this->assertFalse($invoked);
}
}