1
0
mirror of https://github.com/danog/amp.git synced 2024-11-26 20:15:00 +01:00
amp/test/AdaptTest.php

112 lines
2.4 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;
use Amp\Promise;
2017-04-23 14:39:19 +02:00
use Amp\Success;
2016-07-12 18:20:06 +02:00
2018-06-18 20:00:01 +02:00
class PromiseMock
{
/** @var \Amp\Promise */
2016-11-14 20:59:21 +01:00
private $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)
{
$this->promise->onResolve(function ($exception, $value) use ($onFulfilled, $onRejected) {
2016-07-12 18:20:06 +02:00
if ($exception) {
if ($onRejected) {
$onRejected($exception);
}
return;
}
if ($onFulfilled) {
$onFulfilled($value);
}
});
}
}
2018-06-18 20:00:01 +02:00
class AdaptTest extends \PHPUnit\Framework\TestCase
{
public function testThenCalled()
{
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
*/
2018-06-18 20:00:01 +02:00
public function testPromiseFulfilled()
{
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
$promise->onResolve(function ($exception, $value) use (&$result) {
2016-07-12 18:20:06 +02:00
$result = $value;
});
$this->assertSame($value, $result);
}
2016-07-12 18:20:06 +02:00
/**
* @depends testThenCalled
*/
2018-06-18 20:00:01 +02:00
public function testPromiseRejected()
{
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
$promise->onResolve(function ($exception, $value) use (&$reason) {
2016-07-12 18:20:06 +02:00
$reason = $exception;
});
$this->assertSame($exception, $reason);
}
/**
2016-08-11 21:35:58 +02:00
* @expectedException \Error
2016-07-12 18:20:06 +02:00
*/
2018-06-18 20:00:01 +02:00
public function testScalarValue()
{
Promise\adapt(1);
2016-07-12 18:20:06 +02:00
}
/**
2016-08-11 21:35:58 +02:00
* @expectedException \Error
2016-07-12 18:20:06 +02:00
*/
2018-06-18 20:00:01 +02:00
public function testNonThenableObject()
{
Promise\adapt(new \stdClass);
2016-07-12 18:20:06 +02:00
}
}