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

88 lines
2.5 KiB
PHP
Raw Normal View History

<?php
2021-09-06 06:47:06 +02:00
namespace Amp\Future;
2021-08-30 06:28:25 +02:00
use Amp\CancelledException;
use Amp\CompositeException;
use Amp\Deferred;
use Amp\Future;
2021-08-30 06:28:25 +02:00
use Amp\TimeoutCancellationToken;
use PHPUnit\Framework\TestCase;
2021-10-15 00:50:40 +02:00
use Revolt\EventLoop;
use function Amp\Future\any;
class AnyTest extends TestCase
{
public function testSingleComplete(): void
{
self::assertSame(42, any([Future::complete(42)]));
}
public function testTwoComplete(): void
{
self::assertSame(1, any([Future::complete(1), Future::complete(2)]));
}
public function testTwoFirstPending(): void
{
$deferred = new Deferred();
self::assertSame(2, any([$deferred->getFuture(), Future::complete(2)]));
}
public function testTwoFirstThrowing(): void
{
self::assertSame(2, any([Future::error(new \Exception('foo')), Future::complete(2)]));
}
public function testTwoBothThrowing(): void
{
$this->expectException(CompositeException::class);
$this->expectExceptionMessage('Multiple errors encountered (2); use "Amp\CompositeException::getReasons()" to retrieve the array of exceptions thrown:');
Future\any([Future::error(new \Exception('foo')), Future::error(new \RuntimeException('bar'))]);
}
public function testTwoGeneratorThrows(): void
{
self::assertSame(2, any((static function () {
yield Future::error(new \Exception('foo'));
yield Future::complete(2);
})()));
}
2021-08-30 06:28:25 +02:00
public function testCancellation(): void
{
$this->expectException(CancelledException::class);
$deferreds = \array_map(function (int $value) {
$deferred = new Deferred;
2021-10-15 00:50:40 +02:00
EventLoop::delay($value / 10, fn() => $deferred->complete($value));
2021-08-30 06:28:25 +02:00
return $deferred;
}, \range(1, 3));
any(\array_map(
fn(Deferred $deferred) => $deferred->getFuture(),
$deferreds
), new TimeoutCancellationToken(0.05));
}
public function testCompleteBeforeCancellation(): void
{
$deferreds = \array_map(function (int $value) {
$deferred = new Deferred;
2021-10-15 00:50:40 +02:00
EventLoop::delay($value / 10, fn() => $deferred->complete($value));
2021-08-30 06:28:25 +02:00
return $deferred;
}, \range(1, 3));
$deferred = new Deferred;
$deferred->error(new \Exception('foo'));
\array_unshift($deferreds, $deferred);
self::assertSame(1, any(\array_map(
fn(Deferred $deferred) => $deferred->getFuture(),
$deferreds
), new TimeoutCancellationToken(0.2)));
}
}