packages/sql-parser/tests/Unit/Resource/SourceFetcherTest.php

1<?php
2
3declare(strict_types=1);
4
5namespace Tests\Unit\Resource;
6
7use PHPUnit\Framework\Attributes\CoversClass;
8use PHPUnit\Framework\Attributes\Small;
9use PHPUnit\Framework\TestCase;
10use RuntimeException;
11use SqlParser\Resource\SourceFetcher;
12
13#[CoversClass(SourceFetcher::class)]
14#[Small]
15final class SourceFetcherTest extends TestCase
16{
17    public function testFetchReadsTheCachedCopy(): void
18    {
19        $directory = sys_get_temp_dir() . '/sql-parser-cache-' . uniqid();
20        $fetcher = new SourceFetcher($directory);
21        $url = 'https://example.invalid/grammar/parse.y';
22        $path = $fetcher->cachePath($url);
23        self::assertIsString($path);
24        mkdir(dirname($path), 0777, true);
25        file_put_contents($path, 'cmd ::= SELECT.');
26
27        self::assertSame('cmd ::= SELECT.', $fetcher->fetch($url));
28        unlink($path);
29        rmdir($directory);
30    }
31
32    public function testFetchRejectsAnUnreachableSource(): void
33    {
34        $this->expectException(RuntimeException::class);
35
36        (new SourceFetcher())->fetch('http://127.0.0.1:9/unreachable');
37    }
38
39    public function testDownload(): void
40    {
41        self::assertNull((new SourceFetcher())->download('http://127.0.0.1:9/unreachable'));
42    }
43
44    public function testCachePath(): void
45    {
46        $fetcher = new SourceFetcher('/cache');
47
48        self::assertSame('/cache/raw.githubusercontent.com_x_y_parse.y', $fetcher->cachePath('https://raw.githubusercontent.com/x/y/parse.y'));
49        self::assertNull((new SourceFetcher())->cachePath('https://example.invalid/a'));
50    }
51}
52