|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +use ElementaryFramework\Core\Async\CancellationToken; |
| 6 | +use ElementaryFramework\Core\Async\CancellationTokenSource; |
| 7 | +use ElementaryFramework\Core\Async\CombinedCancellationToken; |
| 8 | + |
| 9 | +describe('CombinedCancellationToken', function () { |
| 10 | + it('is cancelled when any source token cancels and invokes callbacks', function () { |
| 11 | + $a = new CancellationTokenSource(); |
| 12 | + $b = new CancellationTokenSource(); |
| 13 | + |
| 14 | + $combined = CombinedCancellationToken::create($a->getToken(), $b->getToken()); |
| 15 | + |
| 16 | + $called = 0; |
| 17 | + $combined->register(function () use (&$called) { $called++; }); |
| 18 | + |
| 19 | + expect($combined->isCancellationRequested())->toBeFalse() |
| 20 | + ->and($combined->canBeCanceled())->toBeTrue(); |
| 21 | + |
| 22 | + $b->cancel('stop'); |
| 23 | + |
| 24 | + expect($combined->isCancellationRequested())->toBeTrue() |
| 25 | + ->and($called)->toBe(1); |
| 26 | + |
| 27 | + // register after cancel should invoke immediately |
| 28 | + $immediate = 0; |
| 29 | + $combined->register(function () use (&$immediate) { $immediate++; }); |
| 30 | + expect($immediate)->toBe(1); |
| 31 | + |
| 32 | + // throwIfCancellationRequested should throw |
| 33 | + expect(fn () => $combined->throwIfCancellationRequested()) |
| 34 | + ->toThrow(\ElementaryFramework\Core\Async\CancellationException::class); |
| 35 | + }); |
| 36 | + |
| 37 | + it('waitForCancellation resolves when cancelled; never resolves when cannot be canceled', function () { |
| 38 | + $src = new CancellationTokenSource(); |
| 39 | + $combined = CombinedCancellationToken::create($src->getToken()); |
| 40 | + |
| 41 | + $p = $combined->waitForCancellation(); |
| 42 | + expect($p->isPending())->toBeTrue(); |
| 43 | + |
| 44 | + $src->cancel('go'); |
| 45 | + $this->runEventLoopBriefly(0.02); |
| 46 | + expect($p->isFulfilled())->toBeTrue(); |
| 47 | + |
| 48 | + $never = CombinedCancellationToken::create(CancellationToken::never()); |
| 49 | + $p2 = $never->waitForCancellation(); |
| 50 | + expect($p2->isPending())->toBeTrue(); |
| 51 | + }); |
| 52 | + |
| 53 | + it('combineWith merges additional tokens', function () { |
| 54 | + $a = new CancellationTokenSource(); |
| 55 | + $b = new CancellationTokenSource(); |
| 56 | + $c = new CancellationTokenSource(); |
| 57 | + |
| 58 | + $combined = CombinedCancellationToken::create($a->getToken()); |
| 59 | + $merged = $combined->combineWith($b->getToken(), $c->getToken()); |
| 60 | + |
| 61 | + // Cancel one of the later tokens and expect merged to be cancelled |
| 62 | + $c->cancel('later'); |
| 63 | + if (method_exists($merged, 'waitForCancellation')) { |
| 64 | + $this->runEventLoopBriefly(0.02); |
| 65 | + expect($merged->isCancellationRequested())->toBeTrue(); |
| 66 | + } |
| 67 | + }); |
| 68 | +}); |
0 commit comments