1
0
mirror of https://github.com/danog/amp.git synced 2024-12-11 00:49:48 +01:00
amp/test/Future/RaceTest.php

80 lines
2.2 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;
2021-12-02 22:29:45 +01:00
use Amp\DeferredFuture;
use Amp\Future;
use Amp\TimeoutCancellation;
use PHPUnit\Framework\TestCase;
2021-10-15 00:50:40 +02:00
use Revolt\EventLoop;
class RaceTest extends TestCase
{
public function testSingleComplete(): void
{
self::assertSame(42, race([Future::complete(42)]));
}
public function testTwoComplete(): void
{
self::assertSame(1, Future\race([Future::complete(1), Future::complete(2)]));
}
public function testTwoFirstPending(): void
{
2021-12-02 22:29:45 +01:00
$deferred = new DeferredFuture;
self::assertSame(2, Future\race([$deferred->getFuture(), Future::complete(2)]));
}
public function testTwoFirstThrowing(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('foo');
race([Future::error(new \Exception('foo')), Future::complete(2)]);
}
public function testTwoGeneratorThrows(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionMessage('foo');
race((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) {
2021-12-02 22:29:45 +01:00
$deferred = new DeferredFuture;
2021-11-14 18:35:07 +01:00
EventLoop::delay($value / 10, fn () => $deferred->complete($value));
2021-08-30 06:28:25 +02:00
return $deferred;
}, \range(1, 3));
race(\array_map(
2021-12-02 22:29:45 +01:00
fn (DeferredFuture $deferred) => $deferred->getFuture(),
2021-08-30 06:28:25 +02:00
$deferreds
), new TimeoutCancellation(0.05));
2021-08-30 06:28:25 +02:00
}
public function testCompleteBeforeCancellation(): void
{
$deferreds = \array_map(function (int $value) {
2021-12-02 22:29:45 +01:00
$deferred = new DeferredFuture;
2021-11-14 18:35:07 +01:00
EventLoop::delay($value / 10, fn () => $deferred->complete($value));
2021-08-30 06:28:25 +02:00
return $deferred;
}, \range(1, 3));
self::assertSame(1, race(\array_map(
2021-12-02 22:29:45 +01:00
fn (DeferredFuture $deferred) => $deferred->getFuture(),
2021-08-30 06:28:25 +02:00
$deferreds
), new TimeoutCancellation(0.2)));
2021-08-30 06:28:25 +02:00
}
}