winzik/engine/tests/Cryo/SandboxLoopTest.php

186 lines
6.4 KiB
PHP

<?php
namespace JumPHP\Tests\Cryo;
use JumPHP\Cryo\SandboxLoop;
use PHPUnit\Framework\TestCase;
use React\EventLoop\StreamSelectLoop;
/** A future of the fake host: what Cryo\Sandbox\Future shows without blocking. */
final class FakeFuture
{
public function __construct(public string $status = 'pending', public mixed $value = null, public ?\Throwable $error = null)
{
}
public function status(): string
{
return $this->status;
}
public function value(): mixed
{
return $this->status === 'ready' ? $this->value : null;
}
public function error(): ?\Throwable
{
return $this->error;
}
public function resolve(mixed $value): void
{
$this->status = 'ready';
$this->value = $value;
}
public function fail(\Throwable $e, string $status = 'failed'): void
{
$this->status = $status;
$this->error = $e;
}
}
/** The sandbox wait of the game loop, with a fake host (pump + futures) and a fake clock. */
final class SandboxLoopTest extends TestCase
{
private float $now = 100.0;
private int $pumps = 0;
/** @var list<\Closure> what the fake host does at each pump */
private array $host = [];
private function loop(?\React\EventLoop\LoopInterface $react = null): SandboxLoop
{
return new SandboxLoop(
$react ?? new StreamSelectLoop(),
function (): int {
$this->pumps++;
$step = array_shift($this->host);
return $step ? (int)$step() : 0;
},
fn (): float => $this->now,
);
}
public function testWaitOneFutureIsSettledByTheTimerNeverAtOnce(): void
{
$loop = $this->loop();
$f = new FakeFuture();
$seen = null;
$task = $loop->watch($f)->then(function ($v) use (&$seen) { $seen = $v; });
self::assertTrue($loop->isRunning(), 'wait() starts the pump');
self::assertFalse($task->isDone());
$loop->tick();
self::assertFalse($task->isDone(), 'still pending: nothing blocks');
$this->host[] = function () use ($f) { $f->resolve('ababab'); return 1; };
$loop->tick();
self::assertTrue($task->isOk());
self::assertSame('ababab', $seen);
self::assertSame(2, $this->pumps);
self::assertSame(0, $loop->pendingWaits());
}
public function testWaitArrayKeepsKeysAndFailsOnTheFirstFailure(): void
{
$loop = $this->loop();
$a = new FakeFuture('ready', 1);
$b = new FakeFuture();
$all = $loop->watch(['a' => $a, 'b' => $b]);
$b->resolve([2]);
$loop->tick();
self::assertSame(['a' => 1, 'b' => [2]], $all->result());
$c = new FakeFuture();
$bad = $loop->watch([$a, $c]);
$c->fail(new \LogicException('in the sandbox'));
$loop->tick();
self::assertTrue($bad->isDone());
self::assertFalse($bad->isOk());
self::assertSame('in the sandbox', $bad->error()->getMessage());
$cancelled = new FakeFuture();
$t = $loop->watch($cancelled);
$cancelled->fail(new \RuntimeException('The future was cancelled'), 'cancelled');
$loop->tick();
self::assertSame('The future was cancelled', $t->error()->getMessage());
}
public function testAlreadySettledFuturesSettleAtOnce(): void
{
$loop = $this->loop();
$task = $loop->watch(new FakeFuture('ready', 42));
self::assertTrue($task->isOk());
self::assertSame(42, $task->result());
}
public function testTimeoutFailsTheTaskWithoutWaiting(): void
{
$loop = $this->loop();
$task = $loop->watch([new FakeFuture()], 0.5);
$this->now += 0.4;
$loop->tick();
self::assertFalse($task->isDone());
$this->now += 0.2;
$loop->tick();
self::assertTrue($task->isDone());
self::assertStringContainsString('before the timeout', $task->error()->getMessage());
}
public function testCallbacksMayWaitAgain(): void
{
$loop = $this->loop();
$first = new FakeFuture();
$second = new FakeFuture('ready', 'two');
$got = [];
$loop->watch($first)->then(function ($v) use ($loop, $second, &$got) {
$got[] = $v;
$loop->watch($second)->then(function ($v) use (&$got) { $got[] = $v; });
});
$first->resolve('one');
$loop->tick();
self::assertSame(['one', 'two'], $got);
self::assertSame(0, $loop->pendingWaits());
}
public function testTheReactTimerPumpsEachTurnWithoutBlocking(): void
{
$react = new StreamSelectLoop();
$loop = $this->loop($react);
$f = new FakeFuture();
$task = $loop->watch($f);
$this->host = [fn () => 0, fn () => 0, function () use ($f) { $f->resolve('late'); return 1; }];
$safety = $react->addTimer(0.2, fn () => $react->stop()); // safety net
$task->then(function () use ($react, $safety) { $react->cancelTimer($safety); $react->stop(); });
$t = microtime(true);
$react->run();
self::assertSame('late', $task->result());
self::assertGreaterThanOrEqual(3, $loop->ticks());
self::assertLessThan(0.15, microtime(true) - $t, 'a few timer turns, no sleep');
$loop->stop();
self::assertFalse($loop->isRunning());
}
public function testRealSandboxWhenExtCryoIsThere(): void
{
if (!SandboxLoop::available()) {
self::markTestSkipped('ext-cryo not loaded');
}
$react = new StreamSelectLoop();
$loop = new SandboxLoop($react);
$sb = new \Cryo\Sandbox\Sandbox(['timeout' => 5]);
$f = $sb->callAsync('str_repeat', ['ab', 3]);
self::assertContains($f->status(), ['pending', 'ready']);
$doubled = $sb->evalAsync('return 21;')->then(fn ($v) => $v * 2);
$task = $loop->watch(['s' => $f, 'd' => $doubled], 10.0);
$safety = $react->addTimer(10, fn () => $react->stop());
$done = function () use ($react, $safety) { $react->cancelTimer($safety); $react->stop(); };
$task->then($done, $done);
$t = microtime(true);
if (!$task->isDone()) { // the answers may already be there (a fork answers in a few ms)
$react->run();
}
self::assertLessThan(5, microtime(true) - $t);
self::assertSame(['s' => 'ababab', 'd' => 42], $task->result());
$loop->stop();
}
}