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

96 lines
2.1 KiB
PHP
Raw Normal View History

<?php
2016-07-12 18:20:06 +02:00
namespace Amp\Test;
2017-03-11 14:43:57 +01:00
use Amp\Failure;
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;
2016-07-12 18:20:06 +02:00
2018-06-18 20:00:01 +02:00
class PromiseMock
{
2020-09-28 05:19:52 +02:00
private Promise $promise;
2016-07-12 18:20:06 +02:00
2018-06-18 20:00:01 +02:00
public function __construct(Promise $promise)
{
2016-11-14 20:59:21 +01:00
$this->promise = $promise;
2016-07-12 18:20:06 +02:00
}
2018-06-18 20:00:01 +02:00
public function then(callable $onFulfilled = null, callable $onRejected = null)
{
2020-09-28 05:19:52 +02:00
$this->promise->onResolve(function ($exception, $value) use ($onFulfilled, $onRejected): void {
2016-07-12 18:20:06 +02:00
if ($exception) {
if ($onRejected) {
$onRejected($exception);
}
return;
}
if ($onFulfilled) {
$onFulfilled($value);
}
});
}
}
2020-09-28 05:19:52 +02:00
class AdaptTest extends AsyncTestCase
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
public function testThenCalled(): void
2018-06-18 20:00:01 +02:00
{
2016-07-12 18:20:06 +02:00
$mock = $this->getMockBuilder(PromiseMock::class)
->disableOriginalConstructor()
->getMock();
2016-07-12 18:20:06 +02:00
$mock->expects($this->once())
->method("then")
->with(
$this->callback(function ($resolve) {
return \is_callable($resolve);
2016-07-12 18:20:06 +02:00
}),
$this->callback(function ($reject) {
return \is_callable($reject);
2016-07-12 18:20:06 +02:00
})
);
$promise = Promise\adapt($mock);
2016-11-14 20:59:21 +01:00
$this->assertInstanceOf(Promise::class, $promise);
2016-07-12 18:20:06 +02:00
}
2016-07-12 18:20:06 +02:00
/**
* @depends testThenCalled
*/
2020-09-28 05:19:52 +02:00
public function testPromiseFulfilled(): void
2018-06-18 20:00:01 +02:00
{
2016-07-12 18:20:06 +02:00
$value = 1;
$promise = new PromiseMock(new Success($value));
$promise = Promise\adapt($promise);
2016-07-12 18:20:06 +02:00
2020-09-28 05:19:52 +02:00
$this->assertSame($value, await($promise));
2016-07-12 18:20:06 +02:00
}
2016-07-12 18:20:06 +02:00
/**
* @depends testThenCalled
*/
2020-09-28 05:19:52 +02:00
public function testPromiseRejected(): void
2018-06-18 20:00:01 +02:00
{
2016-07-12 18:20:06 +02:00
$exception = new \Exception;
$promise = new PromiseMock(new Failure($exception));
$promise = Promise\adapt($promise);
2016-07-12 18:20:06 +02:00
2020-09-28 05:19:52 +02:00
try {
await($promise);
} catch (\Exception $reason) {
$this->assertSame($exception, $reason);
return;
}
2016-07-12 18:20:06 +02:00
2020-09-28 05:19:52 +02:00
$this->fail("Promise was not failed");
2016-07-12 18:20:06 +02:00
}
}