rob-revisited/ide/tests/BoardTest.php

359 lines
22 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\Async\Deferred;
use JumPHP\Ide\Board\BoardCommands;
use JumPHP\Ide\Board\BoardData;
use JumPHP\Ide\Board\GhIssues;
use JumPHP\Ide\Board\LocalBoard;
use JumPHP\Ide\Board\RemoteBoard;
use PHPUnit\Framework\TestCase;
/** The Board window: the local .jumphp/board.json, jumphp.net's board through a fake client, gh's issues, the backend chosen. */
final class BoardTest extends TestCase
{
private string $root;
protected function setUp(): void
{
$this->root = sys_get_temp_dir() . '/jumphp-board-' . bin2hex(random_bytes(4));
mkdir("$this->root/.git/info", 0777, true);
file_put_contents("$this->root/.git/info/exclude", "# git ls-files --others --exclude-from=.git/info/exclude\n\n/.jumphp/\n");
}
protected function tearDown(): void
{
exec('rm -rf ' . escapeshellarg($this->root));
}
private static function done(Deferred $d): mixed
{
self::assertTrue($d->isDone());
return $d->result();
}
public function testANewBoardHasThreeColumnsAndIsKeptInGit(): void
{
$board = self::done((new LocalBoard($this->root))->board());
self::assertCount(3, $board['columns']);
self::assertSame(['To do', 'In progress', 'Done'], array_column($board['columns'], 'name'));
self::assertSame([], $board['cards']);
self::assertFileExists("$this->root/.jumphp/board.json");
$exclude = (string)file_get_contents("$this->root/.git/info/exclude");
self::assertStringContainsString("/.jumphp/*\n!/.jumphp/board.json", $exclude);
self::assertDoesNotMatchRegularExpression('#^/\.jumphp/$#m', $exclude);
// the same columns the next time (ids kept)
self::assertSame($board['columns'], self::done((new LocalBoard($this->root))->board())['columns']);
}
public function testCardsAreAddedEditedAndDeleted(): void
{
$local = new LocalBoard($this->root);
$todo = self::done($local->board())['columns'][0]['id'];
$card = self::done($local->addCard(['columnId' => $todo, 'title' => ' Jump higher ', 'labels' => [['name' => 'bug', 'color' => 'd73a4a'], 'ui', 'BUG'],
'priority' => 'HIGH', 'due' => '2026-12-01T10:00', 'checklist' => [['text' => 'test it'], 'ship', ['text' => '']]]));
self::assertSame('Jump higher', $card['title']);
self::assertSame([['name' => 'bug', 'color' => '#d73a4a'], ['name' => 'ui', 'color' => BoardData::color(null, 'ui')]], $card['labels']);
self::assertSame('high', $card['priority']);
self::assertSame('2026-12-01', $card['due']);
self::assertSame([['text' => 'test it', 'done' => false], ['text' => 'ship', 'done' => false]], $card['checklist']);
self::assertNull($card['issue']);
$edited = self::done($local->updateCard($card['id'], ['body' => "# Why\n\nbecause", 'checklist' => [['text' => 'test it', 'done' => true]], 'priority' => 'nonsense']));
self::assertSame("# Why\n\nbecause", $edited['body']);
self::assertSame('', $edited['priority']);
self::assertSame('Jump higher', $edited['title'], 'what is not given stays');
$failed = $local->addCard(['columnId' => $todo, 'title' => ' ']);
self::assertInstanceOf(\InvalidArgumentException::class, $failed->error());
self::assertSame(['deleted' => true], self::done($local->deleteCard($card['id'])));
self::assertSame([], self::done($local->board())['cards']);
$actions = array_column(self::done($local->board())['activity'], 'action');
self::assertSame(['card.add', 'card.edit', 'card.delete'], $actions);
}
public function testMovingACardRenumbersBothColumns(): void
{
$local = new LocalBoard($this->root);
[$todo, $doing, $done] = array_column(self::done($local->board())['columns'], 'id');
$ids = [];
foreach (['A', 'B', 'C'] as $t) {
$ids[$t] = self::done($local->addCard(['columnId' => $todo, 'title' => $t]))['id'];
}
$d = self::done($local->addCard(['columnId' => $doing, 'title' => 'D']))['id'];
// C to the top of its column
self::done($local->updateCard($ids['C'], ['position' => 0]));
self::assertSame(['C', 'A', 'B'], $this->titles($local, $todo));
// A into "In progress", before D
$moved = self::done($local->updateCard($ids['A'], ['columnId' => $doing, 'position' => 0]));
self::assertSame($doing, $moved['columnId']);
self::assertSame(['C', 'B'], $this->titles($local, $todo));
self::assertSame(['A', 'D'], $this->titles($local, $doing));
// a position past the end: the end
self::done($local->updateCard($d, ['columnId' => $done, 'position' => 99]));
self::assertSame(['D'], $this->titles($local, $done));
foreach (self::done($local->board())['cards'] as $c) {
self::assertSame(array_search($c['title'], $this->titles($local, $c['columnId']), true), $c['position']);
}
self::assertSame('card.done', end(self::done($local->board())['activity'])['action']);
}
public function testColumnsAreAddedRenamedMovedAndDeletedWithoutLosingCards(): void
{
$local = new LocalBoard($this->root);
$columns = self::done($local->board())['columns'];
$review = self::done($local->addColumn('Review'));
self::assertSame(3, $review['position']);
self::done($local->updateColumn($review['id'], ['name' => 'Code review', 'position' => 1]));
self::assertSame(['To do', 'Code review', 'In progress', 'Done'], array_column(self::done($local->board())['columns'], 'name'));
self::done($local->addCard(['columnId' => $columns[0]['id'], 'title' => 'first']));
self::done($local->addCard(['columnId' => $review['id'], 'title' => 'kept']));
$r = self::done($local->deleteColumn($review['id']));
self::assertTrue($r['deleted']);
self::assertSame(['first', 'kept'], $this->titles($local, $columns[0]['id']));
self::assertSame([0, 1, 2], array_column(self::done($local->board())['columns'], 'position'));
// never the last one
foreach (array_slice(self::done($local->board())['columns'], 1) as $c) {
self::done($local->deleteColumn($c['id']));
}
self::assertInstanceOf(\RuntimeException::class, $local->deleteColumn($columns[0]['id'])->error());
}
public function testNotesAreSavedRenamedAndDeleted(): void
{
$local = new LocalBoard($this->root);
$a = self::done($local->saveNote(null, 'Ideas', "- a boss\n- a secret level"));
$b = self::done($local->saveNote(null, '', 'nothing'));
self::assertSame('Untitled note', $b['title']);
$renamed = self::done($local->saveNote($a['id'], 'Level ideas', "- a boss"));
self::assertSame($a['id'], $renamed['id']);
$notes = self::done($local->notes());
self::assertCount(2, $notes);
self::assertContains('Level ideas', array_column($notes, 'title'));
self::assertSame(['deleted' => true], self::done($local->deleteNote($b['id'])));
self::assertSame(['Level ideas'], array_column(self::done($local->notes()), 'title'));
}
public function testTheFileIsWrittenAtomicallyWithABackup(): void
{
$local = new LocalBoard($this->root);
$todo = self::done($local->board())['columns'][0]['id'];
self::done($local->addCard(['columnId' => $todo, 'title' => 'one']));
self::done($local->addCard(['columnId' => $todo, 'title' => 'two']));
self::assertSame([], glob("$this->root/.jumphp/.board.json.*.tmp"), 'no temporary file left');
$saved = json_decode((string)file_get_contents("$this->root/.jumphp/board.json"), true);
self::assertSame(1, $saved['version']);
self::assertCount(2, $saved['cards']);
$backup = json_decode((string)file_get_contents("$this->root/.jumphp/board.json.bak"), true);
self::assertCount(1, $backup['cards'], 'the version before the last write');
}
public function testADamagedFileIsPutAsideAndTheBackupTakesItsPlace(): void
{
$local = new LocalBoard($this->root);
$todo = self::done($local->board())['columns'][0]['id'];
self::done($local->addCard(['columnId' => $todo, 'title' => 'safe']));
self::done($local->addCard(['columnId' => $todo, 'title' => 'lost']));
file_put_contents("$this->root/.jumphp/board.json", '{"columns": [ {"id": "x"'); // a write cut in half, a bad merge...
$board = self::done((new LocalBoard($this->root))->board());
self::assertSame(['safe'], array_column($board['cards'], 'title'));
self::assertStringStartsWith('.jumphp/board.json.corrupt-', $board['recovered']);
self::assertFileExists("$this->root/" . $board['recovered']);
// nothing to recover from: a new board
file_put_contents("$this->root/.jumphp/board.json", 'nonsense');
@unlink("$this->root/.jumphp/board.json.bak");
$fresh = self::done((new LocalBoard($this->root))->board());
self::assertCount(3, $fresh['columns']);
// a hand-edited file: cards of an unknown column land in the first one, missing fields get their defaults
file_put_contents("$this->root/.jumphp/board.json", json_encode(['columns' => [['id' => 'a', 'name' => 'A', 'position' => 5], ['id' => 'b', 'name' => 'B', 'position' => 1]],
'cards' => [['id' => 'k', 'columnId' => 'zzz', 'title' => 'orphan']]]));
$board = self::done((new LocalBoard($this->root))->board());
self::assertSame(['B', 'A'], array_column($board['columns'], 'name'));
self::assertSame('b', $board['cards'][0]['columnId']);
self::assertSame([], $board['cards'][0]['labels']);
}
public function testIssuesAndPullRequestsOfTheForgeBecomeCards(): void
{
$json = json_encode([
['number' => 1, 'title' => 'Crash on start', 'body' => 'boom', 'state' => 'open', 'html_url' => 'https://github.com/o/r/issues/1',
'labels' => [['name' => 'bug', 'color' => 'd73a4a']], 'assignee' => ['login' => 'ada']],
['number' => 2, 'title' => 'Faster jumps', 'body' => '', 'state' => 'open', 'html_url' => 'https://github.com/o/r/pull/2', 'pull_request' => ['merged_at' => null]],
['number' => 3, 'title' => 'Old', 'state' => 'closed', 'html_url' => 'https://github.com/o/r/issues/3'],
]);
$issues = GhIssues::parse((string)$json);
self::assertSame('pr', $issues[1]['kind']);
self::assertSame('ada', $issues[0]['assignee']);
$calls = [];
$run = function (array $args) use (&$calls, &$json): Deferred {
$calls[] = $args;
return Deferred::resolved($args[1] === '-X' ? '{"number": 7, "html_url": "https://github.com/o/r/issues/7", "state": "open"}' : $json);
};
file_put_contents("$this->root/.git/config", "[core]\n\tbare = false\n[remote \"origin\"]\n\turl = [email protected]:o/r.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n");
$commands = new BoardCommands($this->root);
$commands->ghRunner = $run;
self::assertSame('github.com/o/r', $commands->state()['forge']);
$local = $commands->local();
self::assertSame(['imported' => 2, 'updated' => 0, 'errors' => []], self::done($local->sync()));
self::assertSame(['api', 'repos/o/r/issues?state=all&per_page=100&sort=updated'], $calls[0]);
$cards = self::done($local->board())['cards'];
self::assertSame(['Crash on start', 'Faster jumps'], array_column($cards, 'title'));
self::assertSame(['number' => 1, 'url' => 'https://github.com/o/r/issues/1', 'state' => 'open', 'kind' => 'issue'], $cards[0]['issue']);
// again: nothing new; then #1 is closed: its card goes to the last column
self::assertSame(0, self::done($local->sync())['imported']);
$json = (string)json_encode([['number' => 1, 'title' => 'Crash on start', 'state' => 'closed', 'html_url' => 'https://github.com/o/r/issues/1']]);
self::assertSame(1, self::done($local->sync())['updated']);
$board = self::done($local->board());
$crash = array_values(array_filter($board['cards'], fn ($c) => $c['issue']['number'] === 1))[0];
self::assertSame(end($board['columns'])['id'], $crash['columnId']);
self::assertSame('boom', $crash['body']);
// "Create issue" of a card
$card = self::done($local->addCard(['columnId' => $board['columns'][0]['id'], 'title' => 'New idea', 'body' => 'details']));
$linked = self::done($local->createIssue($card['id']));
self::assertSame(7, $linked['issue']['number']);
self::assertSame(['api', '-X', 'POST', 'repos/o/r/issues', '-f', 'title=New idea', '-f', 'body=details'], end($calls));
}
public function testGhFailuresAreSaidPlainly(): void
{
file_put_contents("$this->root/.git/config", "[remote \"origin\"]\n\turl = https://git.jumphp.net/me/game.git\n");
self::assertSame(['git.jumphp.net', 'me/game'], GhIssues::remote($this->root));
$commands = new BoardCommands($this->root);
$commands->ghRunner = fn () => Deferred::rejected(new \RuntimeException('cannot start gh (not found in the PATH: /usr/bin)'));
self::assertStringContainsString('gh auth login', $commands->local()->sync()->error()?->getMessage() ?? '');
$commands->ghRunner = fn () => Deferred::rejected(new \RuntimeException('HTTP 401: Bad credentials'));
self::assertStringContainsString('is not signed in to git.jumphp.net', $commands->local()->sync()->error()?->getMessage() ?? '');
// no remote: no sync
unlink("$this->root/.git/config");
self::assertNotNull((new BoardCommands($this->root))->local()->sync()->error());
}
public function testALinkedProjectUsesJumphpNetsBoardUnlessTheLocalOneIsChosen(): void
{
[$client, $log] = $this->fakeSite();
$commands = new BoardCommands($this->root);
self::assertSame('local', $commands->mode());
self::assertInstanceOf(LocalBoard::class, $commands->store());
$slug = null;
$commands->connect(function () use (&$slug) { return $slug; }, $client);
self::assertSame('local', $commands->mode(), 'connected, but not a jumphp.net project');
$slug = 'my-game';
self::assertSame('remote', $commands->mode());
self::assertInstanceOf(RemoteBoard::class, $commands->store());
self::assertSame(['mode' => 'local'], $commands->setMode('local'));
self::assertInstanceOf(LocalBoard::class, $commands->store());
self::assertSame('local', json_decode((string)file_get_contents("$this->root/.jumphp/ide.json"), true)['board']);
$commands->setMode('remote');
self::assertSame('remote', $commands->state()['mode']);
$slug = null;
$this->expectException(\RuntimeException::class);
$commands->setMode('remote');
}
public function testTheRemoteBoardSpeaksJumphpNetsApi(): void
{
[$client, $log] = $this->fakeSite();
$remote = new RemoteBoard('my game', $client);
$board = self::done($remote->board());
self::assertSame(['Backlog', 'Done'], array_column($board['columns'], 'name'));
self::assertSame('12', $board['cards'][0]['id']);
self::assertSame(['number' => 4, 'url' => 'https://git.jumphp.net/me/g/pulls/4', 'state' => 'open', 'kind' => 'pr'], $board['cards'][0]['issue']);
self::assertSame('GET', $log[0][0]);
self::assertSame('/api/ide/projects/my%20game/board', $log[0][1]);
$card = self::done($remote->addCard(['columnId' => '1', 'title' => 'Sound', 'labels' => ['audio'], 'ignored' => 1]));
self::assertSame('Sound', $card['title']);
self::assertSame(['POST', '/api/ide/projects/my%20game/board/cards'], [self::last($log)[0], self::last($log)[1]]);
self::assertSame(['columnId' => '1', 'title' => 'Sound', 'labels' => [['name' => 'audio', 'color' => BoardData::color(null, 'audio')]]], self::last($log)[2]);
self::done($remote->updateCard('12', ['columnId' => 2, 'position' => '0', 'title' => 'Moved']));
self::assertSame(['PATCH', '/api/ide/projects/my%20game/board/cards/12', ['title' => 'Moved', 'columnId' => '2', 'position' => 0]], self::last($log));
self::done($remote->deleteCard('12'));
self::assertSame(['DELETE', '/api/ide/projects/my%20game/board/cards/12', null], self::last($log));
self::done($remote->addColumn('Review'));
self::assertSame(['POST', '/api/ide/projects/my%20game/board/columns', ['name' => 'Review']], self::last($log));
self::done($remote->updateColumn('2', ['name' => 'Shipped', 'other' => 1]));
self::assertSame(['PATCH', '/api/ide/projects/my%20game/board/columns/2', ['name' => 'Shipped']], self::last($log));
self::done($remote->deleteColumn('2'));
self::assertSame('DELETE', self::last($log)[0]);
self::assertSame(['imported' => 3, 'updated' => 1, 'errors' => ['#9: no access']], self::done($remote->sync()));
self::assertSame(['POST', '/api/ide/projects/my%20game/board/sync', []], self::last($log));
self::assertSame(5, self::done($remote->createIssue('12'))['issue']['number']);
self::assertSame('/api/ide/projects/my%20game/board/cards/12/issue', self::last($log)[1]);
self::assertSame(['Plan'], array_column(self::done($remote->notes()), 'title'));
self::done($remote->saveNote(null, 'New', 'text'));
self::assertSame(['POST', '/api/ide/projects/my%20game/notes', ['title' => 'New', 'body' => 'text']], self::last($log));
self::done($remote->saveNote('3', 'Plan', 'more'));
self::assertSame(['PATCH', '/api/ide/projects/my%20game/notes/3', ['title' => 'Plan', 'body' => 'more']], self::last($log));
self::done($remote->deleteNote('3'));
self::assertSame(['DELETE', '/api/ide/projects/my%20game/notes/3', null], self::last($log));
}
public function testASiteThatFailsRejects(): void
{
$remote = new RemoteBoard('g', fn () => Deferred::rejected(new \RuntimeException('jumphp.net cannot be reached: timeout')));
self::assertSame('jumphp.net cannot be reached: timeout', $remote->board()->error()?->getMessage());
}
public function testTheLocalBoardIsCopiedToJumphpNet(): void
{
[$client, $log] = $this->fakeSite();
$commands = new BoardCommands($this->root);
$commands->connect(fn () => 'g', $client);
$local = $commands->local();
$columns = self::done($local->board())['columns'];
self::done($local->addCard(['columnId' => $columns[0]['id'], 'title' => 'Sound', 'priority' => 'low']));
self::done($local->addCard(['columnId' => $columns[2]['id'], 'title' => 'Shipped thing']));
self::done($local->saveNote(null, 'Plan', 'same title as there'));
self::done($local->saveNote(null, 'Diary', 'new'));
$r = self::done($commands->copyToRemote());
// "To do" and "In progress" are new there, "Done" exists
self::assertSame(['columns' => 2, 'cards' => 2, 'notes' => 1, 'skipped' => 1, 'errors' => []], $r);
$posted = array_column(array_map(fn ($l) => $l[2], array_filter($log->getArrayCopy(), fn ($l) => $l[0] === 'POST' && str_ends_with($l[1], '/board/cards'))), null, 'title');
self::assertSame('2', $posted['Shipped thing']['columnId'], 'into the column of the same name');
self::assertSame('low', $posted['Sound']['priority']);
}
/** @return array{0: \Closure, 1: \ArrayObject} a fake jumphp.net: the calls are logged, the answers canned */
private function fakeSite(): array
{
$log = new \ArrayObject();
$client = function (string $method, string $path, ?array $body) use ($log): Deferred {
$log[] = [$method, $path, $body];
$rest = (string)preg_replace('#^/api/ide/projects/[^/]+#', '', $path);
$answer = match (true) {
$method === 'GET' && $rest === '/board' => ['columns' => [['id' => 2, 'name' => 'Done', 'position' => 1], ['id' => 1, 'name' => 'Backlog', 'position' => 0]],
'cards' => [['id' => 12, 'columnId' => 1, 'position' => 0, 'title' => 'Netcode', 'labels' => [['name' => 'net', 'color' => '#00ff00']],
'issue' => ['number' => 4, 'url' => 'https://git.jumphp.net/me/g/pulls/4', 'state' => 'open', 'kind' => 'pr'], 'updatedAt' => '2026-11-15T10:00:00Z']]],
$method === 'POST' && $rest === '/board/cards' => ['id' => 99, 'position' => 0] + $body,
$method === 'PATCH' && str_starts_with($rest, '/board/cards/') => ['id' => 12, 'columnId' => $body['columnId'] ?? 1] + $body,
$method === 'POST' && $rest === '/board/columns' => ['id' => 50 + count($log), 'name' => $body['name'], 'position' => 9],
$method === 'PATCH' && str_starts_with($rest, '/board/columns/') => ['id' => 2] + $body,
$rest === '/board/sync' => ['imported' => 3, 'updated' => 1, 'errors' => ['#9: no access']],
str_ends_with($rest, '/issue') => ['id' => 12, 'title' => 'Netcode', 'issue' => ['number' => 5, 'url' => 'u', 'state' => 'open', 'kind' => 'issue']],
$method === 'GET' && $rest === '/notes' => ['notes' => [['id' => 3, 'title' => 'Plan', 'body' => 'x', 'updatedAt' => '2026-11-14T00:00:00Z']]],
in_array($method, ['POST', 'PATCH'], true) && str_starts_with($rest, '/notes') => ['id' => 3] + $body,
default => [],
};
return Deferred::resolved($answer);
};
return [$client, $log];
}
private static function last(\ArrayObject $log): array
{
$all = $log->getArrayCopy();
return (array)end($all);
}
/** @return list<string> */
private function titles(LocalBoard $local, string $column): array
{
$cards = array_values(array_filter(self::done($local->board())['cards'], fn ($c) => $c['columnId'] === $column));
usort($cards, fn ($a, $b) => $a['position'] <=> $b['position']);
return array_column($cards, 'title');
}
}