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

90 lines
2.2 KiB
PHP
Raw Normal View History

<?php
2016-07-12 18:20:06 +02:00
namespace Amp\Test;
use Amp\Loop;
2020-09-28 05:19:52 +02:00
use Amp\PHPUnit\AsyncTestCase;
use Amp\Promise;
2017-04-23 14:39:19 +02:00
use Amp\Success;
2020-09-28 05:19:52 +02:00
use function Amp\await;
use function Amp\sleep;
use function React\Promise\reject;
2016-07-12 18:20:06 +02:00
2020-09-28 05:19:52 +02:00
class SuccessTest extends AsyncTestCase
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
public function testConstructWithPromise(): void
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
$this->expectException(\Error::class);
$success = new Success($this->getMockBuilder(Promise::class)->getMock());
2016-07-12 18:20:06 +02:00
}
2020-09-28 05:19:52 +02:00
public function testOnResolve(): void
2018-06-18 20:00:01 +02:00
{
2016-07-12 18:20:06 +02:00
$value = "Resolution value";
$success = new Success($value);
2020-09-28 05:19:52 +02:00
$this->assertSame($value, await($success));
2016-07-12 18:20:06 +02:00
}
/**
* @depends testOnResolve
2016-07-12 18:20:06 +02:00
*/
2020-09-28 05:19:52 +02:00
public function testOnResolveThrowingForwardsToLoopHandlerOnSuccess(): void
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
$invoked = 0;
$expected = new \Exception;
2016-07-12 18:20:06 +02:00
2020-09-28 05:19:52 +02:00
Loop::setErrorHandler(function ($exception) use (&$invoked, $expected) {
++$invoked;
$this->assertSame($expected, $exception);
});
2016-07-12 18:20:06 +02:00
2020-09-28 05:19:52 +02:00
$callback = function () use ($expected) {
throw $expected;
};
2016-07-12 18:20:06 +02:00
2020-09-28 05:19:52 +02:00
$success = new Success;
2016-07-12 18:20:06 +02:00
2020-09-28 05:19:52 +02:00
$success->onResolve($callback);
sleep(0); // Tick event loop to execute onResolve callback.
2016-07-12 18:20:06 +02:00
$this->assertSame(1, $invoked);
}
2020-09-28 05:19:52 +02:00
public function testOnResolveWithReactPromise(): void
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
$invoked = 0;
$success = new Success;
Loop::setErrorHandler(function (\Throwable $exception) use (&$invoked, &$reason): void {
++$invoked;
$reason = $exception;
});
2020-09-28 05:19:52 +02:00
$success->onResolve(fn () => reject(new \Exception("Success")));
sleep(0); // Tick event loop to execute onResolve callback.
$this->assertSame(1, $invoked);
}
2020-09-28 05:19:52 +02:00
public function testOnResolveWithGenerator(): void
2018-06-18 20:00:01 +02:00
{
$value = 1;
$success = new Success($value);
$invoked = false;
$success->onResolve(function ($exception, $value) use (&$invoked) {
$invoked = true;
return $value;
yield; // Unreachable, but makes function a generator.
});
2020-09-28 05:19:52 +02:00
$this->assertSame($value, await($success));
sleep(0); // Tick event loop to execute coroutine
$this->assertTrue($invoked);
}
2016-07-12 18:20:06 +02:00
}