|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace React\Tests\Async; |
| 4 | + |
| 5 | +use React; |
| 6 | +use React\EventLoop\Loop; |
| 7 | +use React\Promise\Promise; |
| 8 | +use function React\Async\async; |
| 9 | +use function React\Async\await; |
| 10 | +use function React\Promise\all; |
| 11 | + |
| 12 | +class AsyncTest extends TestCase |
| 13 | +{ |
| 14 | + public function testAsyncReturnsPendingPromise() |
| 15 | + { |
| 16 | + $promise = async(function () { |
| 17 | + return 42; |
| 18 | + }); |
| 19 | + |
| 20 | + $promise->then($this->expectCallableNever(), $this->expectCallableNever()); |
| 21 | + } |
| 22 | + |
| 23 | + public function testAsyncReturnsPromiseThatFulfillsWithValueWhenCallbackReturns() |
| 24 | + { |
| 25 | + $promise = async(function () { |
| 26 | + return 42; |
| 27 | + }); |
| 28 | + |
| 29 | + $value = await($promise); |
| 30 | + |
| 31 | + $this->assertEquals(42, $value); |
| 32 | + } |
| 33 | + |
| 34 | + public function testAsyncReturnsPromiseThatRejectsWithExceptionWhenCallbackThrows() |
| 35 | + { |
| 36 | + $promise = async(function () { |
| 37 | + throw new \RuntimeException('Foo', 42); |
| 38 | + }); |
| 39 | + |
| 40 | + $this->expectException(\RuntimeException::class); |
| 41 | + $this->expectExceptionMessage('Foo'); |
| 42 | + $this->expectExceptionCode(42); |
| 43 | + await($promise); |
| 44 | + } |
| 45 | + |
| 46 | + public function testAsyncReturnsPromiseThatFulfillsWithValueWhenCallbackReturnsAfterAwaitingPromise() |
| 47 | + { |
| 48 | + $promise = async(function () { |
| 49 | + $promise = new Promise(function ($resolve) { |
| 50 | + Loop::addTimer(0.001, fn () => $resolve(42)); |
| 51 | + }); |
| 52 | + |
| 53 | + return await($promise); |
| 54 | + }); |
| 55 | + |
| 56 | + $value = await($promise); |
| 57 | + |
| 58 | + $this->assertEquals(42, $value); |
| 59 | + } |
| 60 | + |
| 61 | + public function testAsyncReturnsPromiseThatFulfillsWithValueWhenCallbackReturnsAfterAwaitingTwoConcurrentPromises() |
| 62 | + { |
| 63 | + $promise1 = async(function () { |
| 64 | + $promise = new Promise(function ($resolve) { |
| 65 | + Loop::addTimer(0.11, fn () => $resolve(21)); |
| 66 | + }); |
| 67 | + |
| 68 | + return await($promise); |
| 69 | + }); |
| 70 | + |
| 71 | + $promise2 = async(function () { |
| 72 | + $promise = new Promise(function ($resolve) { |
| 73 | + Loop::addTimer(0.11, fn () => $resolve(42)); |
| 74 | + }); |
| 75 | + |
| 76 | + return await($promise); |
| 77 | + }); |
| 78 | + |
| 79 | + $time = microtime(true); |
| 80 | + $values = await(all([$promise1, $promise2])); |
| 81 | + $time = microtime(true) - $time; |
| 82 | + |
| 83 | + $this->assertEquals([21, 42], $values); |
| 84 | + $this->assertGreaterThan(0.1, $time); |
| 85 | + $this->assertLessThan(0.12, $time); |
| 86 | + } |
| 87 | +} |
0 commit comments