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

83 lines
2.1 KiB
PHP
Raw Normal View History

<?php
2015-07-21 04:24:51 +02:00
namespace Amp\Test;
use Amp\Delayed;
use Amp\Loop;
use function Amp\Promise\wait;
2015-07-21 04:24:51 +02:00
class DelayedTest extends BaseTest
2018-06-18 20:00:01 +02:00
{
public function testDelayed()
{
2016-07-19 07:05:40 +02:00
$time = 100;
$value = "test";
$start = \microtime(true);
2016-07-19 07:05:40 +02:00
Loop::run(static function () use (&$result, $time, $value) {
$promise = new Delayed($time, $value);
2016-07-19 07:05:40 +02:00
$callback = static function ($exception, $value) use (&$result) {
2016-07-19 07:05:40 +02:00
$result = $value;
};
$promise->onResolve($callback);
2015-07-21 04:28:51 +02:00
});
2016-07-19 07:05:40 +02:00
$this->assertGreaterThanOrEqual($time - 1 /* 1ms grace period */, (\microtime(true) - $start) * 1000);
2016-07-19 07:05:40 +02:00
$this->assertSame($value, $result);
2015-07-21 04:28:51 +02:00
}
2018-06-18 20:00:01 +02:00
public function testUnreference()
{
$time = 100;
$value = "test";
$start = \microtime(true);
$invoked = false;
Loop::run(static function () use (&$invoked, $time, $value, &$promise) {
$promise = new Delayed($time, $value);
$promise->unreference();
$callback = static function () use (&$invoked) {
$invoked = true;
};
$promise->onResolve($callback);
});
$this->assertLessThanOrEqual($time - 1 /* 1ms grace period */, (\microtime(true) - $start) * 1000);
$this->assertFalse($invoked);
// clear watcher
$promise->reference();
wait($promise);
}
/**
* @depends testUnreference
*/
2018-06-18 20:00:01 +02:00
public function testReference()
{
$time = 100;
$value = "test";
$start = \microtime(true);
$invoked = false;
Loop::run(static function () use (&$invoked, $time, $value) {
$promise = new Delayed($time, $value);
$promise->unreference();
$promise->reference();
$callback = static function ($exception, $value) use (&$invoked) {
$invoked = true;
};
$promise->onResolve($callback);
});
$this->assertGreaterThanOrEqual($time - 1 /* 1ms grace period */, (\microtime(true) - $start) * 1000);
$this->assertTrue($invoked);
}
2015-07-21 04:24:51 +02:00
}