rob-revisited/ide/tests/SiteAddressTest.php

202 lines
9.6 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\Async\Deferred;
use JumPHP\Ide\HttpClient\HttpClientCommands;
use JumPHP\Ide\HttpClient\History;
use JumPHP\Ide\HttpClient\HttpSender;
use JumPHP\Ide\HttpClient\OpenApiExport;
use JumPHP\Ide\HttpClient\SpecFinder;
use JumPHP\Ide\HttpClient\Vault;
use JumPHP\Ide\Web\SiteAddress;
use PHPUnit\Framework\TestCase;
/** The local site's real address (OpenAPI window) and the schema export command. */
final class SiteAddressTest extends TestCase
{
private string $dir;
protected function setUp(): void
{
$this->dir = sys_get_temp_dir() . '/jumphp-site-' . bin2hex(random_bytes(4));
mkdir($this->dir . '/p/.jumphp', 0777, true);
}
protected function tearDown(): void
{
exec('rm -rf ' . escapeshellarg($this->dir));
}
private function root(): string
{
return $this->dir . '/p';
}
public function testASiteServedByWebServeIsOnItsOwnPortNotOnTheEnvPlaceholder(): void
{
// Symfony's .env placeholder (port 80) must not win over web:serve's port: the bug of "localhost:80 refused"
file_put_contents($this->root() . '/.env', "DEFAULT_URI=http://localhost\n");
file_put_contents($this->root() . '/.jumphp/web.json', '{"kind": "symfony"}');
$port = SpecFinder::webPort($this->root());
self::assertSame("http://localhost:$port", SiteAddress::guess($this->root()));
self::assertSame("http://localhost:$port", (new SpecFinder($this->root()))->siteBase());
$urls = array_column(SiteAddress::candidates($this->root()), 'url');
self::assertSame(['http://localhost'], array_slice($urls, 1));
}
public function testSymfonyDockerFilesGiveTheWebServePortToo(): void
{
$r = $this->root();
file_put_contents("$r/compose.yaml", "services:\n php:\n build: .\n ports:\n - \"\${HTTP_PORT:-80}:80\"\n");
mkdir("$r/frankenphp");
file_put_contents("$r/Dockerfile", "FROM dunglas/frankenphp:1-php8.5 AS base\n");
$port = SpecFinder::webPort($r);
$urls = array_column(SiteAddress::candidates($r), 'url');
self::assertSame("http://localhost:$port", $urls[0]);
self::assertContains('http://localhost:80', $urls);
}
public function testAnOwnComposeFileGivesThePublishedPortOfItsPhpService(): void
{
$r = $this->root();
file_put_contents("$r/.jumphp/web.json", '{"docker": "compose", "compose": "compose.yaml", "service": "web"}');
file_put_contents("$r/.env", "APP_PORT=9090\nDEFAULT_URI=http://localhost\n");
file_put_contents("$r/compose.yaml", "services:\n db:\n image: mariadb\n ports:\n - '3307:3306'\n web:\n build: .\n ports:\n - \"127.0.0.1:\${APP_PORT:-8080}:80/tcp\"\n - 8443:443\n");
self::assertSame('http://localhost:9090', SiteAddress::guess($r));
self::assertSame([9090, 8443], SiteAddress::composePorts($r));
}
public function testComposePortsLongSyntaxAndDefaults(): void
{
$yaml = "services:\n app:\n ports:\n - target: 80\n published: 8888\n protocol: tcp\n - target: 5432\n published: 5433\n cache:\n ports: ['6379:6379']\nvolumes:\n x: {}\n";
self::assertSame(['app' => [8888 => 80, 5433 => 5432], 'cache' => [6379 => 6379]], SiteAddress::publishedPorts($yaml));
self::assertSame(['app' => [8080 => 80]], SiteAddress::publishedPorts("services:\n app:\n ports:\n - \"\${PORT:-8080}:80\"\n"));
self::assertSame(['app' => [7000 => 80]], SiteAddress::publishedPorts("services:\n app:\n ports:\n - \"\${PORT:-8080}:80\"\n", ['PORT' => '7000']));
}
public function testWithoutAnythingTheEnvThenLocalhost8000(): void
{
$r = $this->root();
self::assertSame('http://localhost:8000', SiteAddress::guess($r));
file_put_contents("$r/.env.local", "APP_URL=http://127.0.0.1:8123/\n");
self::assertSame('http://127.0.0.1:8123', SiteAddress::guess($r));
}
public function testTheSiteCommandAsksEachCandidateAndKeepsTheOneThatAnswers(): void
{
$r = $this->root();
file_put_contents("$r/.jumphp/web.json", '{"kind": "symfony"}');
file_put_contents("$r/.env", "DEFAULT_URI=http://localhost\n");
file_put_contents("$r/composer.json", '{"require": {"api-platform/symfony": "^4"}}');
$port = SpecFinder::webPort($r);
$commands = [];
$sender = new class (fn (string $url) => $url === 'http://localhost/' ? 200 : null) implements HttpSender {
public array $asked = [];
public function __construct(private \Closure $up)
{
}
public function send(array $request): Deferred
{
$this->asked[] = $request['url'];
$status = ($this->up)($request['url']);
return $status === null ? Deferred::rejected(new \RuntimeException('connection refused')) : Deferred::resolved(['status' => $status]);
}
public function poll(): void
{
}
public function busy(): bool
{
return false;
}
};
HttpClientCommands::register(function (string $n, callable $h) use (&$commands) {
$commands[$n] = $h;
}, $r, $sender, new Vault($r, $this->dir . '/s.json'), new History($r, $this->dir . '/h'));
$site = $commands['http.openapi.site']([])->result();
self::assertSame(["http://localhost:$port/", 'http://localhost/'], $sender->asked);
self::assertTrue($site['running']);
self::assertSame('http://localhost', $site['url']);
self::assertSame('http://localhost/api/docs.jsonopenapi', $site['urls'][0]);
self::assertSame('api-platform', $site['framework']);
self::assertTrue($site['exportable']);
$down = new class implements HttpSender {
public function send(array $request): Deferred
{
return Deferred::rejected(new \RuntimeException('connection refused'));
}
public function poll(): void
{
}
public function busy(): bool
{
return false;
}
};
HttpClientCommands::register(function (string $n, callable $h) use (&$commands) {
$commands[$n] = $h;
}, $r, $down, new Vault($r, $this->dir . '/s.json'), new History($r, $this->dir . '/h'));
$site = $commands['http.openapi.site']([])->result();
self::assertFalse($site['running']);
self::assertSame("http://localhost:$port", $site['url']);
self::assertSame("http://localhost:$port/api/docs.jsonopenapi", $site['urls'][0]);
}
public function testTheExportCommandsAndTheirOutput(): void
{
self::assertSame(['api:openapi:export', '--output=var/openapi.json'], OpenApiExport::argv('api-platform', 'var/openapi.json'));
self::assertSame(['nelmio:apidoc:dump', '--format=json'], OpenApiExport::argv('nelmio', 'var/openapi.json'));
self::assertNull(OpenApiExport::argv('', 'var/openapi.json'));
self::assertSame('var/openapi.json', OpenApiExport::output(''));
self::assertSame('docs/api.yaml', OpenApiExport::output('/docs/api.yaml'));
foreach (['../x.json', 'a/../../x.json', 'schema.txt', '.git/x.json', 'a;b.json'] as $bad) {
try {
OpenApiExport::output($bad);
self::fail("$bad accepted");
} catch (\InvalidArgumentException) {
self::assertTrue(true);
}
}
$printed = "\e[33mDeprecated: x {y}\e[0m\n{\"openapi\":\"3.1.0\",\"info\":{\"title\":\"T\"},\"paths\":{}}\n";
self::assertSame('{"openapi":"3.1.0","info":{"title":"T"},"paths":{}}', OpenApiExport::extractJson($printed));
self::assertNull(OpenApiExport::extractJson('nothing {here}'));
$r = $this->root();
$done = OpenApiExport::finish($r, 'var/openapi.json', 0, $printed);
self::assertSame('var/openapi.json', $done['file']);
self::assertSame('3.1.0', json_decode((string)file_get_contents("$r/var/openapi.json"), true)['openapi']);
$this->expectException(\RuntimeException::class);
OpenApiExport::finish($r, 'var/other.json', 1, 'Command "api:openapi:export" is not defined.');
}
public function testRegeneratingRunsTheConsoleAndWritesTheFile(): void
{
$r = $this->root();
file_put_contents("$r/composer.json", '{"require": {"nelmio/api-doc-bundle": "^5"}}');
$seen = null;
$commands = [];
HttpClientCommands::register(function (string $n, callable $h) use (&$commands) {
$commands[$n] = $h;
}, $r, null, new Vault($r, $this->dir . '/s.json'), new History($r, $this->dir . '/h'), function (array $p) use (&$seen): Deferred {
$seen = $p;
return Deferred::resolved(['code' => 0, 'output' => "{\"openapi\":\"3.0.0\",\"info\":{\"title\":\"N\"},\"paths\":{}}\n"]);
});
$out = $commands['http.openapi.export'](['output' => 'build/api.json'])->result();
self::assertSame(['argv' => ['nelmio:apidoc:dump', '--format=json']], $seen);
self::assertSame('build/api.json', $out['file']);
self::assertFileExists("$r/build/api.json");
file_put_contents("$r/composer.json", '{"require": {"api-platform/core": "^4"}}');
$commands['http.openapi.export']([])->result();
self::assertSame(['argv' => ['api:openapi:export', '--output=var/openapi.json']], $seen);
file_put_contents("$r/composer.json", '{}');
self::assertNotNull($commands['http.openapi.export']([])->error());
}
}