1
0
mirror of https://github.com/danog/amp.git synced 2024-12-04 10:28:01 +01:00
amp/test/Cancellation/CancellationTest.php
2022-01-16 16:21:21 +01:00

75 lines
2.1 KiB
PHP

<?php
namespace Amp\Cancellation;
use Amp\DeferredCancellation;
use Amp\PHPUnit\AsyncTestCase;
use Amp\PHPUnit\TestException;
use Revolt\EventLoop;
use function Amp\delay;
class CancellationTest extends AsyncTestCase
{
public function testUnsubscribeWorks(): void
{
$deferredCancellation = new DeferredCancellation;
$id = $deferredCancellation->getCancellation()->subscribe(function () {
$this->fail("Callback has been called");
});
$deferredCancellation->getCancellation()->subscribe(function () {
$this->assertTrue(true);
});
$deferredCancellation->getCancellation()->unsubscribe($id);
self::assertFalse($deferredCancellation->isCancelled());
$deferredCancellation->cancel();
self::assertTrue($deferredCancellation->isCancelled());
}
public function testThrowingCallbacksEndUpInLoop(): void
{
EventLoop::setErrorHandler(function (\Throwable $exception) use (&$reason): void {
$reason = $exception;
});
$cancellationSource = new DeferredCancellation;
$cancellationSource->getCancellation()->subscribe(function () {
throw new TestException;
});
$cancellationSource->cancel();
delay(0.01); // Tick event loop to invoke callbacks.
self::assertInstanceOf(TestException::class, $reason);
}
public function testDoubleCancelOnlyInvokesOnce(): void
{
$cancellationSource = new DeferredCancellation;
$cancellationSource->getCancellation()->subscribe($this->createCallback(1));
$cancellationSource->cancel();
$cancellationSource->cancel();
}
public function testCalledIfSubscribingAfterCancel(): void
{
$cancellationSource = new DeferredCancellation;
$cancellationSource->cancel();
$cancellationSource->getCancellation()->subscribe($this->createCallback(1));
}
public function testCancelOnDestruct(): void
{
$cancellationSource = new DeferredCancellation;
$cancellationSource->getCancellation()->subscribe($this->createCallback(1));
unset($cancellationSource);
}
}