313 lines
20 KiB
PHP
313 lines
20 KiB
PHP
<?php
|
|
|
|
namespace JumPHP\Ide\Tests;
|
|
|
|
use JumPHP\Ide\Async\Deferred;
|
|
use JumPHP\Ide\Board\BoardCommands;
|
|
use JumPHP\Ide\Board\Sync\FallbackProvider;
|
|
use JumPHP\Ide\Board\Sync\ForgejoProvider;
|
|
use JumPHP\Ide\Board\Sync\GenericProvider;
|
|
use JumPHP\Ide\Board\Sync\GitHubProvider;
|
|
use JumPHP\Ide\Board\Sync\GitLabProvider;
|
|
use JumPHP\Ide\Board\Sync\IssueTokens;
|
|
use JumPHP\Ide\Board\Sync\IssueTracker;
|
|
use JumPHP\Ide\Board\Sync\RemoteUrl;
|
|
use JumPHP\Ide\Board\Sync\TokenNeeded;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
/** The Board's issue trackers: GitHub, GitLab, Forgejo, generic; detection from the remote; tokens; close / reopen; with a fake HTTP. */
|
|
final class IssueSyncTest extends TestCase
|
|
{
|
|
private string $root;
|
|
/** @var list<array{method: string, url: string, headers: array<string, string>, body: ?string}> */
|
|
private array $sent = [];
|
|
/** @var array<string, array{0: int, 1: mixed}> "METHOD url" (or a prefix) => [status, JSON body] */
|
|
private array $answers = [];
|
|
|
|
protected function setUp(): void
|
|
{
|
|
$this->root = sys_get_temp_dir() . '/jumphp-issues-' . bin2hex(random_bytes(4));
|
|
mkdir("$this->root/.git/info", 0777, true);
|
|
}
|
|
|
|
protected function tearDown(): void
|
|
{
|
|
exec('rm -rf ' . escapeshellarg($this->root));
|
|
}
|
|
|
|
private function http(): \Closure
|
|
{
|
|
return function (string $method, string $url, array $headers, ?string $body): Deferred {
|
|
$this->sent[] = ['method' => $method, 'url' => $url, 'headers' => $headers, 'body' => $body];
|
|
foreach ($this->answers as $key => [$status, $json]) {
|
|
if (str_starts_with("$method $url", $key)) {
|
|
return Deferred::resolved(['status' => $status, 'body' => is_string($json) ? $json : (string)json_encode($json)]);
|
|
}
|
|
}
|
|
return Deferred::rejected(new \RuntimeException('Could not resolve host'));
|
|
};
|
|
}
|
|
|
|
private static function done(Deferred $d): mixed
|
|
{
|
|
self::assertTrue($d->isDone());
|
|
return $d->result();
|
|
}
|
|
|
|
private function remote(string $url): void
|
|
{
|
|
file_put_contents("$this->root/.git/config", "[core]\n\tbare = false\n[remote \"origin\"]\n\turl = $url\n");
|
|
}
|
|
|
|
public function testRemoteUrlsInHttpsAndSsh(): void
|
|
{
|
|
$r = RemoteUrl::parse('[email protected]:group/sub/game.git');
|
|
self::assertSame(['gitlab.example.com', 'https://gitlab.example.com', 'group/sub/game'], [$r?->host, $r?->base, $r?->path]);
|
|
$r = RemoteUrl::parse('https://user:[email protected]:8443/team/app.git');
|
|
self::assertSame(['git.company.org', 'https://git.company.org:8443', 'team/app', 'git.company.org:8443'], [$r?->host, $r?->base, $r?->path, $r?->authority()]);
|
|
$r = RemoteUrl::parse('ssh://[email protected]:2222/me/game.git');
|
|
self::assertSame(['https://git.jumphp.net', 'me/game'], [$r?->base, $r?->path]);
|
|
self::assertNull(RemoteUrl::parse('/home/me/repo.git'));
|
|
}
|
|
|
|
public function testKnownHostsAreRecognizedByTheirName(): void
|
|
{
|
|
self::assertSame('github', IssueTracker::guess('github.com'));
|
|
self::assertSame('github', IssueTracker::guess('github.mycompany.com'));
|
|
self::assertSame('gitlab', IssueTracker::guess('gitlab.com'));
|
|
self::assertSame('gitlab', IssueTracker::guess('gitlab.example.org'));
|
|
self::assertSame('forgejo', IssueTracker::guess('git.jumphp.net'));
|
|
self::assertSame('forgejo', IssueTracker::guess('codeberg.org'));
|
|
self::assertNull(IssueTracker::guess('git.example.com'));
|
|
}
|
|
|
|
public function testASelfHostedForgeIsAskedWhatItIs(): void
|
|
{
|
|
$this->remote('[email protected]:team/app.git');
|
|
$this->answers = ['GET https://code.example.com/api/v4/version' => [401, ['message' => '401 Unauthorized']]];
|
|
$tracker = new IssueTracker($this->root, $this->http());
|
|
self::assertSame('gitlab', self::done($tracker->detect($tracker->remote())));
|
|
self::assertInstanceOf(GitLabProvider::class, self::done($tracker->provider()));
|
|
// kept: not asked again
|
|
$this->sent = [];
|
|
self::assertSame('gitlab', self::done($tracker->detect($tracker->remote())));
|
|
self::assertSame([], $this->sent);
|
|
|
|
$this->remote('https://forge.example.net/me/game.git');
|
|
$this->answers = ['GET https://forge.example.net/api/v4/version' => [404, 'not found'], 'GET https://forge.example.net/api/v1/version' => [200, ['version' => '9.0.0']]];
|
|
$tracker = new IssueTracker($this->root, $this->http());
|
|
self::assertSame('forgejo', self::done($tracker->detect($tracker->remote())));
|
|
|
|
// nothing answers: the generic tracker when set, else a message
|
|
$this->remote('https://plain.example.org/me/game.git');
|
|
$this->answers = [];
|
|
$tracker = new IssueTracker($this->root, $this->http());
|
|
self::assertStringContainsString('No issue tracker was recognized on plain.example.org', $tracker->provider()->error()?->getMessage() ?? '');
|
|
$tracker->configure(['generic' => ['issueUrl' => 'https://bugs.example.org/show/{number}']]);
|
|
self::assertInstanceOf(GenericProvider::class, self::done($tracker->provider()));
|
|
}
|
|
|
|
public function testASubversionProjectHasOnlyTheGenericTracker(): void
|
|
{
|
|
rmdir("$this->root/.git/info");
|
|
rmdir("$this->root/.git");
|
|
mkdir("$this->root/.svn");
|
|
$tracker = new IssueTracker($this->root, $this->http());
|
|
self::assertTrue($tracker->isSvn());
|
|
self::assertStringContainsString('Issue tracker', $tracker->provider()->error()?->getMessage() ?? '');
|
|
$tracker->configure(['generic' => ['issueUrl' => 'https://trac.example.org/ticket/{number}']]);
|
|
$p = self::done($tracker->provider());
|
|
self::assertInstanceOf(GenericProvider::class, $p);
|
|
self::assertSame('https://trac.example.org/ticket/12', $p->issueUrl(12));
|
|
self::assertSame([], self::done($p->list()));
|
|
}
|
|
|
|
public function testGitHubIssuesAndPullRequests(): void
|
|
{
|
|
$this->answers = ['GET https://api.github.com/repos/o/r/issues' => [200, [
|
|
['number' => 1, 'title' => 'Crash', 'body' => 'boom', 'state' => 'open', 'html_url' => 'https://github.com/o/r/issues/1', 'updated_at' => '2026-11-01T10:00:00Z',
|
|
'labels' => [['name' => 'bug', 'color' => 'd73a4a']], 'assignee' => ['login' => 'ada']],
|
|
['number' => 2, 'title' => 'Faster', 'state' => 'closed', 'html_url' => 'https://github.com/o/r/pull/2', 'updated_at' => '2026-11-03T10:00:00Z',
|
|
'pull_request' => ['merged_at' => '2026-11-03T10:00:00Z']],
|
|
['number' => 3, 'title' => 'Draft', 'state' => 'open', 'html_url' => 'https://github.com/o/r/pull/3', 'updated_at' => '2026-11-02T10:00:00Z', 'pull_request' => ['merged_at' => null]],
|
|
]]];
|
|
$p = new GitHubProvider('https://github.com', 'o/r', $this->http(), 'ghp_secret');
|
|
$list = self::done($p->list());
|
|
self::assertSame([2, 3, 1], array_column($list, 'number'));
|
|
self::assertSame(['merged', 'open', 'open'], array_column($list, 'state'));
|
|
self::assertSame(['pr', 'pr', 'issue'], array_column($list, 'kind'));
|
|
self::assertSame(['number' => 1, 'title' => 'Crash', 'body' => 'boom', 'state' => 'open', 'kind' => 'issue', 'url' => 'https://github.com/o/r/issues/1',
|
|
'labels' => [['name' => 'bug', 'color' => 'd73a4a']], 'assignee' => 'ada', 'updatedAt' => '2026-11-01T10:00:00Z'], $list[2]);
|
|
self::assertSame('Bearer ghp_secret', $this->sent[0]['headers']['Authorization']);
|
|
self::assertSame('application/vnd.github+json', $this->sent[0]['headers']['Accept']);
|
|
self::assertSame('jumphp-ide', $this->sent[0]['headers']['User-Agent']);
|
|
|
|
$this->answers = ['PATCH https://api.github.com/repos/o/r/issues/1' => [200, ['number' => 1, 'title' => 'Crash', 'state' => 'closed', 'html_url' => 'https://github.com/o/r/issues/1']]];
|
|
self::assertSame('closed', self::done($p->closeIssue(1))['state']);
|
|
self::assertSame(['state' => 'closed'], json_decode((string)end($this->sent)['body'], true));
|
|
$p->reopenIssue(1);
|
|
self::assertSame(['PATCH', 'https://api.github.com/repos/o/r/issues/1', ['state' => 'open']], [end($this->sent)['method'], end($this->sent)['url'], json_decode((string)end($this->sent)['body'], true)]);
|
|
// GitHub Enterprise
|
|
self::assertSame('https://ghe.example.com/api/v3', (new GitHubProvider('https://ghe.example.com', 'o/r', $this->http()))->api());
|
|
}
|
|
|
|
public function testGitLabIssuesAndMergeRequests(): void
|
|
{
|
|
$issues = [['iid' => 4, 'id' => 9001, 'title' => 'Bug', 'description' => 'it breaks', 'state' => 'opened', 'web_url' => 'https://gitlab.com/g/s/p/-/issues/4',
|
|
'labels' => [['name' => 'bug', 'color' => '#d9534f']], 'assignee' => ['username' => 'ada'], 'updated_at' => '2026-11-02T00:00:00Z'],
|
|
['iid' => 5, 'title' => 'Old', 'state' => 'closed', 'web_url' => 'https://gitlab.com/g/s/p/-/issues/5', 'labels' => ['wontfix'], 'updated_at' => '2026-10-01T00:00:00Z']];
|
|
$mrs = [['iid' => 4, 'title' => 'Fix bug', 'state' => 'merged', 'web_url' => 'https://gitlab.com/g/s/p/-/merge_requests/4', 'updated_at' => '2026-11-05T00:00:00Z'],
|
|
['iid' => 6, 'title' => 'WIP', 'state' => 'opened', 'web_url' => 'https://gitlab.com/g/s/p/-/merge_requests/6', 'updated_at' => '2026-11-01T00:00:00Z']];
|
|
$this->answers = ['GET https://gitlab.com/api/v4/projects/g%2Fs%2Fp/issues?' => [200, $issues], 'GET https://gitlab.com/api/v4/projects/g%2Fs%2Fp/merge_requests?' => [200, $mrs]];
|
|
$p = new GitLabProvider('https://gitlab.com', 'g/s/p', $this->http(), 'glpat-x');
|
|
$list = self::done($p->list());
|
|
self::assertSame([['pr', 4, 'merged'], ['issue', 4, 'open'], ['pr', 6, 'open'], ['issue', 5, 'closed']],
|
|
array_map(fn ($i) => [$i['kind'], $i['number'], $i['state']], $list));
|
|
self::assertSame('it breaks', $list[1]['body']);
|
|
self::assertSame([['name' => 'bug', 'color' => '#d9534f']], $list[1]['labels']);
|
|
self::assertSame([['name' => 'wontfix', 'color' => '']], $list[3]['labels']);
|
|
self::assertSame('ada', $list[1]['assignee']);
|
|
self::assertSame('glpat-x', $this->sent[0]['headers']['PRIVATE-TOKEN']);
|
|
self::assertArrayNotHasKey('Authorization', $this->sent[0]['headers']);
|
|
|
|
$this->answers = ['PUT https://gitlab.com/api/v4/projects/g%2Fs%2Fp/issues/4' => [200, ['iid' => 4, 'state' => 'closed', 'web_url' => 'u']]];
|
|
self::assertSame('closed', self::done($p->closeIssue(4))['state']);
|
|
self::assertSame(['state_event' => 'close'], json_decode((string)end($this->sent)['body'], true));
|
|
$p->reopenIssue(4);
|
|
self::assertSame(['state_event' => 'reopen'], json_decode((string)end($this->sent)['body'], true));
|
|
$this->answers = ['POST https://gitlab.com/api/v4/projects/g%2Fs%2Fp/issues' => [201, ['iid' => 7, 'state' => 'opened', 'web_url' => 'https://gitlab.com/g/s/p/-/issues/7']]];
|
|
self::assertSame(7, self::done($p->createIssue('T', 'B'))['number']);
|
|
self::assertSame(['title' => 'T', 'description' => 'B'], json_decode((string)end($this->sent)['body'], true));
|
|
self::assertStringContainsString('/-/user_settings/personal_access_tokens', $p->tokenUrl());
|
|
}
|
|
|
|
public function testForgejoIssuesAndPulls(): void
|
|
{
|
|
$this->answers = [
|
|
'GET https://git.jumphp.net/api/v1/repos/me/game/issues?state=all&type=issues' => [200, [['number' => 1, 'title' => 'Bug', 'state' => 'open', 'html_url' => 'https://git.jumphp.net/me/game/issues/1', 'updated_at' => '2026-11-01T00:00:00Z']]],
|
|
'GET https://git.jumphp.net/api/v1/repos/me/game/issues?state=all&type=pulls' => [200, [['number' => 2, 'title' => 'PR', 'state' => 'closed', 'html_url' => 'https://git.jumphp.net/me/game/pulls/2',
|
|
'pull_request' => ['merged' => true, 'merged_at' => '2026-11-02T00:00:00Z'], 'updated_at' => '2026-11-02T00:00:00Z']]],
|
|
];
|
|
$p = new ForgejoProvider('https://git.jumphp.net', 'me/game', $this->http(), 'fj');
|
|
$list = self::done($p->list());
|
|
self::assertSame([['pr', 2, 'merged'], ['issue', 1, 'open']], array_map(fn ($i) => [$i['kind'], $i['number'], $i['state']], $list));
|
|
self::assertSame('token fj', $this->sent[0]['headers']['Authorization']);
|
|
$this->answers = ['PATCH https://git.jumphp.net/api/v1/repos/me/game/issues/1' => [201, ['number' => 1, 'state' => 'closed']]];
|
|
self::assertSame('closed', self::done($p->closeIssue(1))['state']);
|
|
self::assertSame(['state' => 'closed'], json_decode((string)end($this->sent)['body'], true));
|
|
}
|
|
|
|
public function testTheGenericMapping(): void
|
|
{
|
|
$this->answers = ['GET https://bugs.example.org/api' => [200, ['data' => ['tickets' => [
|
|
['key' => 'GAME-12', 'fields' => ['summary' => 'Sound cuts', 'status' => 'In Progress'], 'text' => 'details'],
|
|
['key' => 'GAME-13', 'fields' => ['summary' => 'Typo', 'status' => 'Resolved']],
|
|
['key' => 'nothing', 'fields' => []],
|
|
]]]]];
|
|
$p = new GenericProvider(['issueUrl' => 'https://bugs.example.org/browse/GAME-{number}', 'listUrl' => 'https://bugs.example.org/api', 'items' => 'data.tickets',
|
|
'tokenHeader' => 'X-Api-Key', 'tokenPrefix' => '', 'fields' => ['number' => 'key', 'title' => 'fields.summary', 'state' => 'fields.status', 'body' => 'text']], $this->http(), 'k');
|
|
$list = self::done($p->list());
|
|
self::assertSame([12, 13], array_column($list, 'number'));
|
|
self::assertSame(['open', 'closed'], array_column($list, 'state'));
|
|
self::assertSame('https://bugs.example.org/browse/GAME-12', $list[0]['url']);
|
|
self::assertSame('details', $list[0]['body']);
|
|
self::assertSame('k', $this->sent[0]['headers']['X-Api-Key']);
|
|
self::assertNotNull($p->closeIssue(12)->error());
|
|
$this->expectException(\InvalidArgumentException::class);
|
|
new GenericProvider(['issueUrl' => 'ftp://x']);
|
|
}
|
|
|
|
public function testAMissingOrRefusedTokenIsAskedFor(): void
|
|
{
|
|
$this->answers = ['GET https://gitlab.example.com/api/v4/' => [404, ['message' => '404 Project Not Found']]];
|
|
$error = (new GitLabProvider('https://gitlab.example.com', 'team/app', $this->http()))->list()->error();
|
|
self::assertInstanceOf(TokenNeeded::class, $error);
|
|
self::assertSame('gitlab.example.com', $error->host);
|
|
self::assertFalse($error->refused);
|
|
$this->answers = ['GET https://gitlab.example.com/api/v4/' => [401, ['message' => '401 Unauthorized']]];
|
|
$error = (new GitLabProvider('https://gitlab.example.com', 'team/app', $this->http(), 'old'))->list()->error();
|
|
self::assertInstanceOf(TokenNeeded::class, $error);
|
|
self::assertTrue($error->refused);
|
|
self::assertStringNotContainsString('old', $error->getMessage());
|
|
// with a token, a 404 is said as such
|
|
$this->answers = ['GET https://gitlab.example.com/api/v4/' => [404, []]];
|
|
self::assertStringContainsString('was not found', (new GitLabProvider('https://gitlab.example.com', 'team/app', $this->http(), 't'))->list()->error()?->getMessage() ?? '');
|
|
}
|
|
|
|
public function testTokensAreKeptPerHostOutsideTheProject(): void
|
|
{
|
|
$file = "$this->root-settings/issue-tokens.json";
|
|
$tokens = new IssueTokens($file, fn (string $host) => $host === 'git.example.com' ? 'from-git' : null);
|
|
$tokens->set('GitLab.example.com', 'glpat-1');
|
|
self::assertSame('glpat-1', $tokens->get('gitlab.example.com'));
|
|
self::assertSame('from-git', $tokens->get('git.example.com'));
|
|
self::assertFalse($tokens->has('git.example.com'));
|
|
self::assertSame('600', substr(sprintf('%o', fileperms($file)), -3));
|
|
self::assertTrue($tokens->forget('gitlab.example.com'));
|
|
self::assertNull($tokens->get('gitlab.example.com'));
|
|
exec('rm -rf ' . escapeshellarg("$this->root-settings"));
|
|
}
|
|
|
|
public function testTheBoardSyncsGitLabAsksForATokenAndClosesIssuesWhenDone(): void
|
|
{
|
|
$this->remote('[email protected]:team/app.git');
|
|
$commands = new BoardCommands($this->root);
|
|
$tokens = new IssueTokens("$this->root-settings/t.json");
|
|
$commands->connectIssues($this->http(), $tokens);
|
|
// private project, no token: the window is asked for one
|
|
$this->answers = ['GET https://gitlab.com/api/v4/' => [404, ['message' => '404 Project Not Found']]];
|
|
$r = self::done($commands->tokenNeeded($commands->local()->sync()));
|
|
self::assertSame('gitlab.com', $r['tokenNeeded']['host']);
|
|
self::assertSame('gitlab', $r['tokenNeeded']['provider']);
|
|
self::assertStringStartsWith('https://gitlab.com/-/user_settings/personal_access_tokens', $r['tokenNeeded']['tokenUrl']);
|
|
$commands->setToken('gitlab.com', 'glpat-ok');
|
|
$this->answers = [
|
|
'GET https://gitlab.com/api/v4/projects/team%2Fapp/issues?' => [200, [['iid' => 3, 'title' => 'Bug', 'state' => 'opened', 'web_url' => 'https://gitlab.com/team/app/-/issues/3']]],
|
|
'GET https://gitlab.com/api/v4/projects/team%2Fapp/merge_requests?' => [200, []],
|
|
'PUT https://gitlab.com/api/v4/projects/team%2Fapp/issues/3' => [200, ['iid' => 3, 'state' => 'closed', 'web_url' => 'https://gitlab.com/team/app/-/issues/3']],
|
|
];
|
|
self::assertSame(1, self::done($commands->local()->sync())['imported']);
|
|
$board = self::done($commands->local()->board());
|
|
$card = $board['cards'][0];
|
|
// moved to the last column: closed on GitLab
|
|
self::done($commands->local()->updateCard($card['id'], ['columnId' => end($board['columns'])['id']]));
|
|
$closed = self::done($commands->local()->setIssueState($card['id'], false));
|
|
self::assertSame('closed', $closed['issue']['state']);
|
|
self::assertSame(['PUT', ['state_event' => 'close'], 'glpat-ok'], [end($this->sent)['method'], json_decode((string)end($this->sent)['body'], true), end($this->sent)['headers']['PRIVATE-TOKEN']]);
|
|
// and back: reopened
|
|
$count = count($this->sent);
|
|
self::assertSame('open', self::done($commands->local()->setIssueState($card['id'], true))['issue']['state']);
|
|
self::assertSame(['state_event' => 'reopen'], json_decode((string)end($this->sent)['body'], true));
|
|
// already open: nothing sent
|
|
self::done($commands->local()->setIssueState($card['id'], true));
|
|
self::assertCount($count + 1, $this->sent);
|
|
// the setting
|
|
self::assertSame('ask', $commands->state()['closeWhenDone']);
|
|
$commands->tracker()->configure(['closeWhenDone' => 'always']);
|
|
self::assertSame('always', $commands->state()['closeWhenDone']);
|
|
$state = self::done($commands->trackerState());
|
|
self::assertSame(['gitlab', 'gitlab.com', true], [$state['detected'], $state['host'], $state['hasToken']]);
|
|
self::assertStringNotContainsString('glpat', (string)file_get_contents("$this->root/.jumphp/ide.json"));
|
|
exec('rm -rf ' . escapeshellarg("$this->root-settings"));
|
|
}
|
|
|
|
public function testWithoutATokenGhComesFirstThenTheApiWithoutToken(): void
|
|
{
|
|
$this->remote('https://github.com/o/r.git');
|
|
$commands = new BoardCommands($this->root);
|
|
$commands->connectIssues($this->http(), new IssueTokens("$this->root-settings/t.json"));
|
|
$commands->ghRunner = fn () => Deferred::rejected(new \RuntimeException('cannot start gh'));
|
|
$this->answers = ['GET https://api.github.com/repos/o/r/issues' => [200, [['number' => 5, 'title' => 'Public', 'state' => 'open', 'html_url' => 'h']]]];
|
|
$p = self::done($commands->tracker()->provider());
|
|
self::assertInstanceOf(FallbackProvider::class, $p);
|
|
self::assertSame(1, self::done($commands->local()->sync())['imported']);
|
|
self::assertArrayNotHasKey('Authorization', end($this->sent)['headers']);
|
|
// a private repository: the API asks for a token
|
|
$this->answers = ['GET https://api.github.com/repos/o/r/issues' => [404, ['message' => 'Not Found']]];
|
|
self::assertSame('github.com', self::done($commands->tokenNeeded($commands->local()->sync()))['tokenNeeded']['host']);
|
|
// with a token: the API alone
|
|
$commands->setToken('github.com', 'ghp_x');
|
|
self::assertInstanceOf(GitHubProvider::class, self::done($commands->tracker()->provider()));
|
|
exec('rm -rf ' . escapeshellarg("$this->root-settings"));
|
|
}
|
|
}
|