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

75 lines
2.1 KiB
PHP
Raw Normal View History

<?php
namespace Amp\Cancellation;
use Amp\DeferredCancellation;
2020-09-28 05:19:52 +02:00
use Amp\PHPUnit\AsyncTestCase;
2017-05-16 21:56:52 +02:00
use Amp\PHPUnit\TestException;
2021-10-15 00:50:40 +02:00
use Revolt\EventLoop;
use function Amp\delay;
2020-09-28 05:19:52 +02:00
class CancellationTest extends AsyncTestCase
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
public function testUnsubscribeWorks(): void
2018-06-18 20:00:01 +02:00
{
$deferredCancellation = new DeferredCancellation;
$id = $deferredCancellation->getCancellation()->subscribe(function () {
2020-09-28 05:19:52 +02:00
$this->fail("Callback has been called");
});
$deferredCancellation->getCancellation()->subscribe(function () {
2020-09-28 05:19:52 +02:00
$this->assertTrue(true);
});
$deferredCancellation->getCancellation()->unsubscribe($id);
self::assertFalse($deferredCancellation->isCancelled());
$deferredCancellation->cancel();
self::assertTrue($deferredCancellation->isCancelled());
}
2017-05-16 21:56:52 +02:00
2020-09-28 05:19:52 +02:00
public function testThrowingCallbacksEndUpInLoop(): void
2018-06-18 20:00:01 +02:00
{
2021-10-15 00:50:40 +02:00
EventLoop::setErrorHandler(function (\Throwable $exception) use (&$reason): void {
2020-09-28 05:19:52 +02:00
$reason = $exception;
});
2017-05-16 21:56:52 +02:00
$cancellationSource = new DeferredCancellation;
$cancellationSource->getCancellation()->subscribe(function () {
2020-09-28 05:19:52 +02:00
throw new TestException;
2017-05-16 21:56:52 +02:00
});
2020-09-28 05:19:52 +02:00
$cancellationSource->cancel();
2017-05-16 21:56:52 +02:00
delay(0.01); // Tick event loop to invoke callbacks.
2017-05-16 21:56:52 +02:00
2021-03-26 22:34:32 +01:00
self::assertInstanceOf(TestException::class, $reason);
2020-09-28 05:19:52 +02:00
}
2017-05-16 21:56:52 +02:00
2020-09-28 05:19:52 +02:00
public function testDoubleCancelOnlyInvokesOnce(): void
2018-06-18 20:00:01 +02:00
{
$cancellationSource = new DeferredCancellation;
$cancellationSource->getCancellation()->subscribe($this->createCallback(1));
2017-05-16 21:56:52 +02:00
2020-09-28 05:19:52 +02:00
$cancellationSource->cancel();
$cancellationSource->cancel();
2017-05-16 21:56:52 +02:00
}
2020-09-28 05:19:52 +02:00
public function testCalledIfSubscribingAfterCancel(): void
2018-06-18 20:00:01 +02:00
{
$cancellationSource = new DeferredCancellation;
2020-09-28 05:19:52 +02:00
$cancellationSource->cancel();
$cancellationSource->getCancellation()->subscribe($this->createCallback(1));
2017-05-16 21:56:52 +02:00
}
public function testCancelOnDestruct(): void
{
$cancellationSource = new DeferredCancellation;
$cancellationSource->getCancellation()->subscribe($this->createCallback(1));
unset($cancellationSource);
}
}