1
0
mirror of https://github.com/danog/amp.git synced 2025-01-23 05:41:25 +01:00
amp/test/DeferredTest.php

78 lines
1.8 KiB
PHP
Raw Normal View History

<?php
2016-07-12 11:20:06 -05:00
namespace Amp\Test;
use Amp\Deferred;
2020-09-27 22:19:52 -05:00
use Amp\PHPUnit\AsyncTestCase;
use Amp\Promise;
use function Amp\delay;
2016-07-12 11:20:06 -05:00
2020-09-27 22:19:52 -05:00
class DeferredTest extends AsyncTestCase
2018-06-18 20:00:01 +02:00
{
2020-09-27 22:19:52 -05:00
private Deferred $deferred;
2016-07-12 11:20:06 -05:00
2020-09-27 22:19:52 -05:00
public function setUp(): void
2018-06-18 20:00:01 +02:00
{
2020-09-27 22:19:52 -05:00
parent::setUp();
2016-07-12 11:20:06 -05:00
$this->deferred = new Deferred;
}
2020-09-27 22:19:52 -05:00
public function testGetPromise(): void
2018-06-18 20:00:01 +02:00
{
2016-11-14 13:59:21 -06:00
$promise = $this->deferred->promise();
$this->assertInstanceOf(Promise::class, $promise);
2016-07-12 11:20:06 -05:00
}
2016-07-12 11:20:06 -05:00
/**
2016-11-14 13:59:21 -06:00
* @depends testGetPromise
2016-07-12 11:20:06 -05:00
*/
2020-09-27 22:19:52 -05:00
public function testResolve(): void
2018-06-18 20:00:01 +02:00
{
2016-07-12 11:20:06 -05:00
$value = "Resolution value";
2016-11-14 13:59:21 -06:00
$promise = $this->deferred->promise();
2016-07-12 11:20:06 -05:00
$this->assertFalse($this->deferred->isResolved());
2016-07-12 11:20:06 -05:00
$invoked = false;
$promise->onResolve(function ($exception, $value) use (&$invoked, &$result) {
2016-07-12 11:20:06 -05:00
$invoked = true;
$result = $value;
});
2016-07-12 11:20:06 -05:00
$this->deferred->resolve($value);
2020-09-27 22:19:52 -05:00
$this->assertFalse($invoked); // Resolution should be async.
delay(0); // Force loop to tick once.
2020-09-27 22:19:52 -05:00
$this->assertTrue($this->deferred->isResolved());
2016-07-12 11:20:06 -05:00
$this->assertTrue($invoked);
$this->assertSame($value, $result);
}
/**
2016-11-14 13:59:21 -06:00
* @depends testGetPromise
2016-07-12 11:20:06 -05:00
*/
2020-09-27 22:19:52 -05:00
public function testFail(): void
2018-06-18 20:00:01 +02:00
{
2016-07-12 11:20:06 -05:00
$exception = new \Exception;
2016-11-14 13:59:21 -06:00
$promise = $this->deferred->promise();
2016-07-12 11:20:06 -05:00
$invoked = false;
$promise->onResolve(function ($exception, $value) use (&$invoked, &$result) {
2016-07-12 11:20:06 -05:00
$invoked = true;
$result = $exception;
});
$this->deferred->fail($exception);
2020-09-27 22:19:52 -05:00
$this->assertFalse($invoked); // Resolution should be async.
delay(0); // Force loop to tick once.
2020-09-27 22:19:52 -05:00
2016-07-12 11:20:06 -05:00
$this->assertTrue($invoked);
$this->assertSame($exception, $result);
}
}