rob-revisited/ide/tests/YamlComposeTest.php

249 lines
13 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\Async\Deferred;
use JumPHP\Ide\Config\ConfigCompletion;
use JumPHP\Ide\Docker\ComposeLint;
use JumPHP\Ide\Docker\ComposeStacks;
use JumPHP\Ide\Docker\ComposeTemplates;
use JumPHP\Ide\Docker\DockerHub;
use JumPHP\Ide\Lang\Messages;
use JumPHP\Ide\Workspace\MemoryWorkspace;
use JumPHP\Ide\Yaml\YamlLines;
use JumPHP\Ide\Yaml\YamlLint;
use PHPUnit\Framework\TestCase;
/** YAML read correctly (its problems, its outline) and Docker Compose in the IDE (checks, stacks, templates, Docker Hub). */
final class YamlComposeTest extends TestCase
{
protected function setUp(): void
{
Messages::setLocale('en');
DockerHub::forget();
}
protected function tearDown(): void
{
Messages::reset();
}
public function testASyntaxErrorHasItsLineAndColumn(): void
{
$list = YamlLint::diagnostics('config/packages/x.yaml', "a: 1\nb:\n c: 2\n d: 3\n");
self::assertCount(1, $list);
self::assertSame(4, $list[0]['startLine']);
self::assertSame('error', $list[0]['severity']);
self::assertStringStartsWith('YAML: ', $list[0]['message']);
$tab = YamlLint::diagnostics('x.yml', "a:\n\tb: 1\n");
self::assertSame(2, $tab[0]['startLine']);
self::assertSame(1, $tab[0]['startColumn']);
$dup = YamlLint::diagnostics('x.yml', "a: 1\na: 2\n");
self::assertSame(2, $dup[0]['startLine']);
}
public function testTagsAnchorsAndSeveralDocumentsAreValid(): void
{
$text = "base: &base\n a: 1\nchild:\n <<: *base\n b: !php/const PHP_EOL\n c: !tagged_iterator app.handler\n d: |\n text: here\n---\nsecond: true\n";
self::assertSame([], YamlLint::diagnostics('config/x.yaml', $text));
$second = YamlLint::diagnostics('k8s.yaml', "a: 1\n---\nb: 2\nc: [\n");
self::assertSame(4, $second[0]['startLine']);
}
public function testTheLinesOfKeysAndItems(): void
{
$lines = new YamlLines("services:\n web:\n image: nginx\n ports:\n - \"80:80\"\n - \"443:443\"\n command: |\n a: b\n db:\n image: x\n");
self::assertSame(6, $lines->line(['services', 'web', 'ports', 1]));
self::assertSame(9, $lines->line(['services', 'db']));
self::assertSame(4, $lines->line(['services', 'web', 'ports', 7])); // the deepest known
self::assertSame(['services', 'web', 'command'], $lines->locate(['services', 'web', 'command', 'a'])['path'] ?? null); // a block scalar's text has no keys
$outline = $lines->outline();
self::assertSame('services', $outline[0]['name']);
self::assertSame(['web', 'db'], array_column($outline[0]['children'], 'name'));
self::assertSame(8, $outline[0]['children'][0]['endLine']);
}
public function testComposeChecks(): void
{
$text = <<<'YAML'
version: "3.8"
servics: {}
services:
web:
imgae: nginx
ports:
- "8080:80"
- "127.0.0.1:${PORT:-8081}:80/tcp"
- "80:80:80:80"
volumes:
- ./src:/app:ro
- data:/data
- cache:/cache
- nope
environment:
- APP_ENV=dev
depends_on: [db, redis]
restart: sometimes
networks: [front]
db:
image: mariadb:11.4
volumes:
data:
YAML;
$list = YamlLint::diagnostics('compose.yaml', $text);
$at = [];
foreach ($list as $d) {
$at[] = $d['startLine'] . ' ' . $d['severity'] . ' ' . $d['message'];
}
$expect = [
'1 warning The "version" key is obsolete: Docker Compose ignores it.',
'2 warning Unknown top-level key "servics" of a Compose file.',
'4 error The service web has neither image nor build.',
'5 warning Unknown key "imgae" in the service web.',
'9 error Not a port: "80:80:80:80" (expected [host:]container[/protocol], e.g. "127.0.0.1:8080:80").',
'13 error The named volume cache is not declared under the top-level volumes.',
'14 error Not a volume: "nope" (expected source:/path/in/container[:ro]).',
'17 error The service web depends on redis, which no Compose file of this folder defines.',
'18 error restart is no, always, on-failure[:N] or unless-stopped.',
'19 error The network front is not declared under the top-level networks.',
];
self::assertSame($expect, $at);
}
public function testAnOverrideMayChangeOnlySomeSettingsAndSeesTheStack(): void
{
$ws = new MemoryWorkspace([
'compose.yaml' => "services:\n php:\n image: app\nvolumes:\n db_data:\n",
'compose.override.yaml' => "services:\n php:\n volumes: [db_data:/x]\n depends_on: [database]\n database:\n ports: [\"5432\"]\n",
]);
$stacks = new ComposeStacks($ws);
$list = YamlLint::diagnostics('compose.override.yaml', $ws->read('compose.override.yaml'), fn (string $p) => $stacks->siblings($p));
self::assertSame([], $list);
self::assertTrue(ComposeLint::isCompose('docker-compose.prod.yml'));
self::assertFalse(ComposeLint::isCompose('config/services.yaml'));
}
public function testPortsAndVolumesSyntax(): void
{
foreach (['80', '8080:80', '127.0.0.1:8080:80', '[::1]:80:80', '9000-9010:9000-9010', '127.0.0.1::80', '53:53/udp', '${HTTP_PORT:-80}:80'] as $ok) {
self::assertTrue(ComposeLint::isPort($ok), $ok);
}
foreach (['http', '80:80:80:80', '80/xyz'] as $bad) {
self::assertFalse(ComposeLint::isPort($bad), $bad);
}
self::assertNull(ComposeLint::namedVolume('./src:/app'));
self::assertNull(ComposeLint::namedVolume('/var/run/docker.sock:/var/run/docker.sock:ro'));
self::assertNull(ComposeLint::namedVolume('/tmp'));
self::assertSame('data', ComposeLint::namedVolume('data:/var/lib/mysql'));
self::assertNull(ComposeLint::namedVolume('C:\\data:/data'));
self::assertFalse(ComposeLint::namedVolume('data:relative'));
self::assertFalse(ComposeLint::namedVolume('./x:/y:bad'));
}
public function testSymfonyServicesObviousChecks(): void
{
$text = "services:\n _defaults:\n autowire: true\n autowyre: true\n App:\n resource: '../src/'\n App\\Mailer: ~\nparamters: {}\n";
$list = YamlLint::diagnostics('config/services.yaml', $text);
self::assertSame([4, 5, 8], array_column($list, 'startLine'));
}
public function testATemplateIsAddedUnderServicesWithItsVolume(): void
{
$text = "services:\n app:\n image: x\n\nvolumes:\n other: {}\n";
$r = ComposeTemplates::add($text, 'postgres');
self::assertSame('postgres', $r['name']);
self::assertSame([], YamlLint::diagnostics('compose.yaml', $r['text']));
self::assertStringContainsString(" postgres:\n image: postgres:16-alpine\n environment:\n POSTGRES_DB: app", $r['text']);
self::assertStringContainsString("volumes:\n other: {}\n postgres-data:\n", $r['text']);
$again = ComposeTemplates::add($r['text'], 'postgres');
self::assertSame('postgres-2', $again['name']);
self::assertStringContainsString('postgres-2-data:/var/lib/postgresql/data', $again['text']);
self::assertSame([], YamlLint::diagnostics('compose.yaml', $again['text']));
$empty = ComposeTemplates::add('', 'redis');
self::assertSame("services:\n redis:\n", substr($empty['text'], 0, 19));
foreach (array_keys(ComposeTemplates::all()) as $name) {
$one = ComposeTemplates::add("services:\n", $name);
self::assertSame([], YamlLint::diagnostics('compose.yaml', $one['text']), $name);
}
}
public function testTheStacksOfTheProject(): void
{
$ws = new MemoryWorkspace([
'bin/console' => '', 'public/index.php' => '', 'composer.json' => '{}',
'docker/compose.yaml' => "services:\n a:\n image: x\n", 'docker/compose.prod.yaml' => "services: {}\n",
'vendor/x/compose.yaml' => "services: {}\n",
]);
$stacks = (new ComposeStacks($ws))->stacks();
self::assertSame(['', 'docker'], array_column($stacks, 'dir'));
self::assertSame('jumphp', $stacks[0]['kind']);
self::assertSame('compose.override.yaml', $stacks[0]['override']);
self::assertSame(['docker/compose.yaml'], $stacks[1]['files']);
self::assertSame(['docker/compose.prod.yaml'], $stacks[1]['others']);
$made = (new ComposeStacks($ws))->createOverride('');
self::assertTrue($made['created']);
$added = (new ComposeStacks($ws))->addService('compose.override.yaml', 'mailpit', null);
self::assertSame('mailpit', $added['name']);
self::assertStringContainsString("services:\n mailpit:\n image: axllent/mailpit", $ws->read('compose.override.yaml'));
self::assertSame(['compose.override.yaml'], (new ComposeStacks($ws))->stacks()[0]['files']);
}
public function testComposeErrorsAreProblemsAtTheirLine(): void
{
$ws = new MemoryWorkspace(['compose.yaml' => "services:\n web:\n image: x\n ports:\n - bad\n"]);
$p = (new ComposeStacks($ws))->problems("validating /home/u/site/compose.yaml: services.web.ports.0 Does not match format 'ports'\n", ['compose.yaml']);
self::assertSame(5, $p['compose.yaml'][0]['startLine']);
$p = (new ComposeStacks($ws))->problems("yaml: line 3: mapping values are not allowed in this context", ['compose.yaml']);
self::assertSame(3, $p['compose.yaml'][0]['startLine']);
$p = (new ComposeStacks($ws))->problems('service "web" depends on undefined service "db": invalid compose project', ['compose.yaml']);
self::assertSame(2, $p['compose.yaml'][0]['startLine']);
}
public function testComposeCompletionKeysValuesTemplatesAndDockerHub(): void
{
$asked = [];
$hub = new DockerHub(function (string $url) use (&$asked): Deferred {
$asked[] = $url;
if (str_contains($url, '/search/')) {
return Deferred::resolved(['status' => 200, 'json' => ['results' => [
['repo_name' => 'bitnami/redis', 'short_description' => 'Bitnami', 'star_count' => 300, 'pull_count' => 1e9],
['repo_name' => 'redis', 'short_description' => 'Redis is…', 'star_count' => 13000, 'pull_count' => 5e9, 'is_official' => true],
]]]);
}
if (str_contains($url, '/tags')) {
return Deferred::resolved(['status' => 200, 'json' => ['results' => [['name' => '7-alpine', 'full_size' => 15e6, 'last_updated' => '2026-10-01T00:00:00Z']]]]);
}
return Deferred::resolved(['status' => 200, 'json' => ['namespace' => 'library', 'name' => 'redis']]);
});
$c = new ConfigCompletion(null, $hub);
$r = $c->complete('compose.yaml', "services:\n cache:\n image: red\n", 3, 15);
self::assertInstanceOf(Deferred::class, $r);
$items = $r->result();
self::assertSame(['redis', 'bitnami/redis'], array_column($items['items'], 'label'));
self::assertSame('red', $items['typed']);
$tags = $c->complete('compose.yaml', "services:\n cache:\n image: redis:7\n", 3, 21)->result();
self::assertSame(['7-alpine'], array_column($tags['items'], 'label'));
self::assertSame('7', $tags['typed']);
// the same search again: from the cache, no request
$count = count($asked);
$c->complete('compose.yaml', "services:\n cache:\n image: red\n", 3, 15);
self::assertCount($count, $asked);
foreach ($asked as $url) {
self::assertStringStartsWith('https://hub.docker.com/v2/', $url);
}
$keys = $c->complete('compose.yaml', "services:\n web:\n image: x\n res\n", 4, 8);
self::assertContains('restart', array_column($keys['items'], 'label'));
self::assertNotContains('image', array_column($keys['items'], 'label'));
$values = $c->complete('compose.yaml', "services:\n web:\n restart: \n", 3, 14);
self::assertSame(['no', 'always', 'on-failure', 'unless-stopped'], array_column($values['items'], 'label'));
$templates = $c->complete('compose.yaml', "services:\n web:\n image: x\n ma\n", 4, 5);
$snippet = array_values(array_filter($templates['items'], fn ($i) => $i['label'] === 'mariadb'))[0];
self::assertTrue($snippet['snippet']);
self::assertStringStartsWith("mariadb:\n image: mariadb:11.4", $snippet['insertText']);
$top = $c->complete('compose.yaml', "services: {}\nvol\n", 2, 4);
self::assertContains('volumes', array_column($top['items'], 'label'));
// another registry: nothing asked
self::assertSame([], $c->complete('compose.yaml', "services:\n a:\n image: ghcr.io/x/y\n", 3, 23)->result()['items']);
}
}