1
0
mirror of https://github.com/danog/amp.git synced 2024-11-26 20:15:00 +01:00
amp/test/MapTest.php

107 lines
2.8 KiB
PHP
Raw Normal View History

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