1
0
mirror of https://github.com/danog/amp.git synced 2024-12-13 01:47:33 +01:00
amp/test/Future/SettleTest.php

78 lines
2.3 KiB
PHP
Raw Normal View History

2021-09-17 03:49:55 +02:00
<?php
namespace Amp\Future;
use Amp\CancelledException;
use Amp\Deferred;
use Amp\Future;
use Amp\TimeoutCancellationToken;
use PHPUnit\Framework\TestCase;
2021-10-15 00:50:40 +02:00
use Revolt\EventLoop;
2021-09-17 03:49:55 +02:00
class SettleTest extends TestCase
{
public function testSingleComplete(): void
{
self::assertSame([[], [42]], settle([Future::complete(42)]));
}
public function testTwoComplete(): void
{
self::assertSame([[], [1, 2]], settle([Future::complete(1), Future::complete(2)]));
}
public function testTwoFirstThrowing(): void
{
$exception = new \Exception('foo');
self::assertSame(
[['one' => $exception], ['two' => 2]],
settle(['one' => Future::error($exception), 'two' => Future::complete(2)])
);
}
public function testTwoBothThrowing(): void
{
$one = new \Exception('foo');
$two = new \RuntimeException('bar');
self::assertSame([[$one, $two], []], Future\settle([Future::error($one), Future::error($two)]));
}
public function testTwoGeneratorThrows(): void
{
$exception = new \Exception('foo');
self::assertSame([[0 => $exception], [1 => 2]], settle((static function () use ($exception) {
yield Future::error($exception);
yield Future::complete(2);
})()));
}
public function testCancellation(): void
{
$this->expectException(CancelledException::class);
$deferreds = \array_map(function (int $value) {
$deferred = new Deferred;
2021-11-14 18:35:07 +01:00
EventLoop::delay($value / 10, fn () => $deferred->complete($value));
2021-09-17 03:49:55 +02:00
return $deferred;
}, \range(1, 3));
settle(\array_map(
2021-11-14 18:35:07 +01:00
fn (Deferred $deferred) => $deferred->getFuture(),
2021-09-17 03:49:55 +02:00
$deferreds
), new TimeoutCancellationToken(0.05));
}
public function testCompleteBeforeCancellation(): void
{
$deferreds = \array_map(function (int $value) {
$deferred = new Deferred;
2021-11-14 18:35:07 +01:00
EventLoop::delay($value / 10, fn () => $deferred->complete($value));
2021-09-17 03:49:55 +02:00
return $deferred;
}, \range(1, 3));
self::assertSame([[], \range(1, 3)], settle(\array_map(
2021-11-14 18:35:07 +01:00
fn (Deferred $deferred) => $deferred->getFuture(),
2021-09-17 03:49:55 +02:00
$deferreds
), new TimeoutCancellationToken(0.5)));
}
}