1
0
mirror of https://github.com/danog/amp.git synced 2024-12-12 09:29:45 +01:00
amp/test/Stream/FilterTest.php

84 lines
1.9 KiB
PHP
Raw Normal View History

<?php
2020-05-13 17:15:21 +02:00
namespace Amp\Test\Stream;
2020-05-13 17:15:21 +02:00
use Amp\AsyncGenerator;
use Amp\PHPUnit\TestException;
2020-05-13 17:15:21 +02:00
use Amp\Stream;
use Amp\StreamSource;
use Amp\Test\BaseTest;
class FilterTest extends BaseTest
2018-06-18 20:00:01 +02:00
{
public function testNoValuesEmitted()
{
2020-05-17 21:41:42 +02:00
$source = new StreamSource;
2020-05-17 21:41:42 +02:00
$stream = Stream\filter($source->stream(), $this->createCallback(0));
2020-05-17 21:41:42 +02:00
$source->complete();
2020-05-17 21:41:42 +02:00
yield Stream\discard($stream);
}
2018-06-18 20:00:01 +02:00
public function testValuesEmitted()
{
2020-05-17 21:41:42 +02:00
$count = 0;
$values = [1, 2, 3];
$expected = [1, 3];
$generator = new AsyncGenerator(static function (callable $yield) use ($values) {
foreach ($values as $value) {
yield $yield($value);
2017-04-27 17:32:53 +02:00
}
});
2020-05-17 21:41:42 +02:00
$iterator = Stream\filter($generator, static function ($value) use (&$count) {
++$count;
return $value & 1;
});
while (list($value) = yield $iterator->continue()) {
$this->assertSame(\array_shift($expected), $value);
}
$this->assertSame(3, $count);
}
/**
* @depends testValuesEmitted
*/
2018-06-18 20:00:01 +02:00
public function testCallbackThrows()
{
2020-05-17 21:41:42 +02:00
$values = [1, 2, 3];
$exception = new TestException;
$generator = new AsyncGenerator(static function (callable $yield) use ($values) {
foreach ($values as $value) {
yield $yield($value);
2017-04-27 17:32:53 +02:00
}
});
2020-05-17 21:41:42 +02:00
$stream = Stream\filter($generator, static function () use ($exception) {
throw $exception;
});
$this->expectExceptionObject($exception);
yield $stream->continue();
}
2020-05-13 17:15:21 +02:00
public function testStreamFails()
2018-06-18 20:00:01 +02:00
{
2020-05-17 21:41:42 +02:00
$exception = new TestException;
$source = new StreamSource;
2020-05-17 21:41:42 +02:00
$stream = Stream\filter($source->stream(), $this->createCallback(0));
$source->fail($exception);
$this->expectExceptionObject($exception);
yield $stream->continue();
}
}