diff --git a/.castor/earl.php b/.castor/earl.php index 35b6be83b..825a6646e 100644 --- a/.castor/earl.php +++ b/.castor/earl.php @@ -38,7 +38,10 @@ * order, so the cache directory constants of qa.php are not defined yet when this * file is parsed. * - * @return array + * The RDF suites are driven by their manifest: their data sets are named after + * the fragment of the test IRI rather than after a fixture file ("byId"). + * + * @return array */ function earlSuites(): array { @@ -63,6 +66,30 @@ function earlSuites(): array 'manifest' => CACHE_DIR_W3C_FRAMING_TEST_SUITE . '/tests/frame-manifest.jsonld', 'iri' => 'https://w3c.github.io/json-ld-framing/tests/frame-manifest', ], + 'ToRdfTest' => [ + 'name' => 'toRdf', + 'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/toRdf-manifest.jsonld', + 'iri' => 'https://w3c.github.io/json-ld-api/tests/toRdf-manifest', + 'byId' => true, + ], + 'FromRdfTest' => [ + 'name' => 'fromRdf', + 'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/fromRdf-manifest.jsonld', + 'iri' => 'https://w3c.github.io/json-ld-api/tests/fromRdf-manifest', + 'byId' => true, + ], + 'RemoteDocTest' => [ + 'name' => 'remote-doc', + 'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/remote-doc-manifest.jsonld', + 'iri' => 'https://w3c.github.io/json-ld-api/tests/remote-doc-manifest', + 'byId' => true, + ], + 'HtmlTest' => [ + 'name' => 'html', + 'manifest' => CACHE_DIR_W3C_TEST_SUITE . '/tests/html-manifest.jsonld', + 'iri' => 'https://w3c.github.io/json-ld-api/tests/html-manifest', + 'byId' => true, + ], ]; } @@ -126,7 +153,7 @@ function earl( $results = $outcomes[$testClass] ?? []; $summary[$suite['name']] = ['passed' => 0, 'failed' => 0, 'inapplicable' => 0, 'untested' => 0]; - foreach (earlManifestEntries($suite['manifest']) as $entry) { + foreach (earlManifestEntries($suite['manifest'], $suite['byId'] ?? false) as $entry) { // A test that was not run is either out of scope (it only applies to // JSON-LD 1.0 processors) or genuinely untested: the distinction matters // in the consolidated report. @@ -201,10 +228,11 @@ function earlOutcomesFromJunit(string $junitFile): array * The data set name follows the convention of AbstractJsonLdTestCase: the expected * output file with "-out" replaced by "-in" (several manifest entries share an * input file but not an expected output), or the input file for a negative test. + * The suites driven by their manifest name it after the test fragment instead. * * @return list */ -function earlManifestEntries(string $manifestFile): array +function earlManifestEntries(string $manifestFile, bool $byId = false): array { $content = file_get_contents($manifestFile); @@ -229,9 +257,11 @@ function earlManifestEntries(string $manifestFile): array $entries[] = [ 'id' => $test['@id'], - 'test' => \is_string($test['expect'] ?? null) - ? str_replace('-out', '-in', basename($test['expect'])) - : basename($test['input']), + 'test' => match (true) { + $byId => $test['@id'], + \is_string($test['expect'] ?? null) => str_replace('-out', '-in', basename($test['expect'])), + default => basename($test['input']), + }, 'jsonLd10Only' => 'json-ld-1.0' === ($option['specVersion'] ?? null), ]; } diff --git a/.castor/json-ld.php b/.castor/json-ld.php index f5c705a6d..0fda7c10a 100644 --- a/.castor/json-ld.php +++ b/.castor/json-ld.php @@ -12,6 +12,7 @@ namespace json_ld; use Castor\Attribute\AsArgument; +use Castor\Attribute\AsOption; use Castor\Attribute\AsTask; use function Castor\io; @@ -20,6 +21,11 @@ use JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander; use JoliCode\StructuredData\JsonLd\Algorithms\Flatten\Flattener; use JoliCode\StructuredData\JsonLd\Algorithms\Frame\Framer; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; +use Symfony\Component\Console\Input\InputOption; #[AsTask(description: 'Applies the expansion algorithm to a JSON-LD document')] function expand( @@ -118,3 +124,50 @@ function frameJsonLd( io()->writeln($result); } + +#[AsTask(name: 'to-rdf', description: 'Deserializes a JSON-LD document to RDF, written as N-Quads')] +function toRdf( + #[AsArgument(name: 'file', description: 'The JSON-LD file to deserialize')] + string $fileName, + #[AsOption(name: 'rdf-direction', mode: InputOption::VALUE_REQUIRED, description: 'How the base direction of a string is written: "i18n-datatype" or "compound-literal" (dropped by default)')] + ?string $rdfDirection = null, + #[AsOption(name: 'generalized', description: 'Keep the triples whose predicate is a blank node')] + bool $generalized = false, +): void { + $file = file_get_contents($fileName); + + if (false === $file) { + io()->error(\sprintf('The file "%s" could not be read.', $fileName)); + + return; + } + + $converter = new ToRdfConverter(); + $dataset = $converter->toRdf($file, new ProcessorOptions(produceGeneralizedRdf: $generalized, rdfDirection: $rdfDirection)); + + io()->write(NQuadsSerializer::serialize($dataset)); +} + +#[AsTask(name: 'from-rdf', description: 'Serializes an RDF dataset, read as N-Quads, as a JSON-LD document')] +function fromRdf( + #[AsArgument(name: 'file', description: 'The N-Quads file to serialize')] + string $fileName, + #[AsOption(name: 'rdf-direction', mode: InputOption::VALUE_REQUIRED, description: 'How the base direction of a string is read back: "i18n-datatype" or "compound-literal"')] + ?string $rdfDirection = null, + #[AsOption(name: 'native-types', description: 'Turn xsd:boolean, xsd:integer and xsd:double literals into JSON booleans and numbers')] + bool $nativeTypes = false, + #[AsOption(name: 'rdf-type', description: 'Keep rdf:type as an ordinary property instead of "@type"')] + bool $rdfType = false, +): void { + $file = file_get_contents($fileName); + + if (false === $file) { + io()->error(\sprintf('The file "%s" could not be read.', $fileName)); + + return; + } + + $converter = new FromRdfConverter(); + + io()->writeln($converter->fromRdf($file, new ProcessorOptions(rdfDirection: $rdfDirection, useNativeTypes: $nativeTypes, useRdfType: $rdfType, ordered: true))); +} diff --git a/.castor/qa.php b/.castor/qa.php index 04a60575d..81c89a8b4 100644 --- a/.castor/qa.php +++ b/.castor/qa.php @@ -80,6 +80,10 @@ function suiteFixturesAreMissing(): bool return !fs()->exists(\sprintf('%s/tests/flatten/output', CACHE_DIR_W3C_TEST_SUITE)) || !fs()->exists(\sprintf('%s/tests/frame/output', CACHE_DIR_W3C_FRAMING_TEST_SUITE)) || !fs()->exists(\sprintf('%s/tests/expand-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) + || !fs()->exists(\sprintf('%s/tests/toRdf-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) + || !fs()->exists(\sprintf('%s/tests/fromRdf-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) + || !fs()->exists(\sprintf('%s/tests/html-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) + || !fs()->exists(\sprintf('%s/tests/remote-doc-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE)) || !fs()->exists(\sprintf('%s/tests/frame-manifest.jsonld', CACHE_DIR_W3C_FRAMING_TEST_SUITE)); } @@ -237,6 +241,20 @@ function phpunitPrepare( } } + // These suites are driven by their manifest, which names every file of a + // test: their fixtures are copied as they are upstream. + foreach (Algorithms::manifestDrivenSuiteNames() as $algorithm) { + fs()->copy( + \sprintf('%s/json-ld-api-%s/tests/%s-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE, $ref, $algorithm), + \sprintf('%s/tests/%s-manifest.jsonld', CACHE_DIR_W3C_TEST_SUITE, $algorithm), + true, + ); + fs()->mirror( + \sprintf('%s/json-ld-api-%s/tests/%s', CACHE_DIR_W3C_TEST_SUITE, $ref, $algorithm), + \sprintf('%s/tests/%s', CACHE_DIR_W3C_TEST_SUITE, $algorithm), + ); + } + // remove the zip archive and all the files fs()->remove($zipFileName); fs()->remove(\sprintf('%s/json-ld-api-%s', CACHE_DIR_W3C_TEST_SUITE, $ref)); diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 052001e52..289b59de1 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -1,7 +1,8 @@ # Benchmarks -The figures below come from `castor qa:bench:all`, run on 2026-11-13 on a developer -laptop, with PHP 8.5 in CLI, opcache and JIT disabled. They are +The figures below come from `castor qa:bench:all`, run on 2026-11-21 on a developer +laptop, with PHP 8.5 in CLI, opcache and JIT disabled, and Composer's optimized +autoloader. They are [PHPBench](https://github.com/phpbench/phpbench) *mode* values: the most frequent measurement over the iterations, with the relative standard deviation next to it. Memory is the peak of the benchmark process. Take them as orders of magnitude: the @@ -24,9 +25,9 @@ content-keyed cache can serve them. | Scenario | Document | Time per document | Peak memory | | --- | --- | --- | --- | -| 25 distinct variants of the Google *Book* fixture | 9 KB JSON-LD, 10 nested types | 12.7 ms | 20.6 MB | +| 25 distinct variants of the Google *Book* fixture | 9 KB JSON-LD, 10 nested types | 13.2 ms | 20.8 MB | -The 25 documents took 318 ms in total (±0.25 %). +The 25 documents took 330 ms in total (±2.36 %). ### The same document, again and again @@ -37,12 +38,12 @@ costs. | Document | Size | Time per audit | Peak memory | | --- | --- | --- | --- | -| schema.org fixture, a single type | 0.4 KB JSON-LD | 1.5 ms | 5.2 MB | -| schema.org fixture, nested types | 6 KB JSON-LD | 3.3 ms | 5.8 MB | -| Google *Book* fixture | 9 KB JSON-LD | 12.6 ms | 8.1 MB | -| jolicode.com homepage | 139 KB HTML | 6.8 ms | 6.6 MB | -| jolicampus.com homepage | 95 KB HTML | 5.5 ms | 6.5 MB | -| Google structured data introduction | 187 KB HTML | 10.5 ms | 6.5 MB | +| schema.org fixture, a single type | 0.4 KB JSON-LD | 1.6 ms | 5.2 MB | +| schema.org fixture, nested types | 6 KB JSON-LD | 4.0 ms | 6.2 MB | +| Google *Book* fixture | 9 KB JSON-LD | 13.1 ms | 8.2 MB | +| jolicode.com homepage | 139 KB HTML | 7.1 ms | 6.6 MB | +| jolicampus.com homepage | 95 KB HTML | 5.9 ms | 6.5 MB | +| Google structured data introduction | 187 KB HTML | 10.9 ms | 6.6 MB | The HTML pages are real pages, downloaded by `castor qa:phpunit:download-fixtures` from hosts JoliCode owns or operates (plus the Google documentation page), and never @@ -56,18 +57,28 @@ processor benchmarks measure the context processing step alone. | Algorithm | Input | Time | Peak memory | | --- | --- | --- | --- | | Context processing | inline context | 11 µs | 3.9 MB | -| Context processing | scoped contexts | 24 µs | 3.9 MB | +| Context processing | scoped contexts | 25 µs | 3.9 MB | | Context processing | nested contexts | 12 µs | 3.9 MB | | Expansion | minimal document (`expand/0002`) | 224 µs | 3.9 MB | -| Expansion | context-heavy document (`expand/0036`) | 409 µs | 3.9 MB | -| Expansion | nested `@graph` (`expand/pr25`) | 829 µs | 3.9 MB | -| Expansion | 8 nodes each repeating the schema.org context | 3.1 ms | 5.1 MB | +| Expansion | context-heavy document (`expand/0036`) | 412 µs | 3.9 MB | +| Expansion | nested `@graph` (`expand/pr25`) | 837 µs | 3.9 MB | +| Expansion | 8 nodes each repeating the schema.org context | 3.2 ms | 5.1 MB | | Compaction | inline context | 215 µs | 3.9 MB | -| Compaction | into the schema.org context | 13.4 ms | 10.2 MB | -| Flattening | minimal document | 266 µs | 3.9 MB | +| Compaction | into the schema.org context | 13.8 ms | 10.2 MB | +| Flattening | minimal document | 264 µs | 3.9 MB | | Flattening | nested lists | 600 µs | 3.9 MB | -| Framing | by type, schema.org context | 16.2 ms | 10.5 MB | -| Framing | embedded node, schema.org context | 16.2 ms | 10.5 MB | +| Framing | by type, schema.org context | 16.3 ms | 10.5 MB | +| Framing | embedded node, schema.org context | 16.3 ms | 10.5 MB | +| Deserialization to RDF | minimal document (`toRdf/0002`) | 126 µs | 3.9 MB | +| Deserialization to RDF | list (`toRdf/0036`) | 182 µs | 3.9 MB | +| Deserialization to RDF | nested `@graph` (`toRdf/pr25`) | 987 µs | 3.9 MB | +| Deserialization to RDF | JSON literal (`toRdf/js12`) | 182 µs | 3.9 MB | +| Deserialization to RDF | 8 schema.org nodes, written as N-Quads | 1.5 ms | 5.2 MB | +| Serialization from RDF | minimal dataset (`fromRdf/0002`) | 87 µs | 3.9 MB | +| Serialization from RDF | lists (`fromRdf/li03`) | 274 µs | 3.9 MB | +| Serialization from RDF | native types (`fromRdf/0027`) | 184 µs | 3.9 MB | +| Serialization from RDF | 1,600 statements, read from N-Quads | 15.7 ms | 6.4 MB | +| Serialization from RDF | the same 1,600 statements, already parsed | 5.6 ms | 5.3 MB | Compaction into the schema.org context and framing with it both cost around 15 ms: that is the price of building the inverse context of the roughly 3,000 schema.org @@ -76,18 +87,29 @@ is cheap in comparison, because the processed context is served from the static vocabulary files the library ships with. The "repeated remote context" subject is the regression guard for that path. +The deserialization to RDF is an expansion followed by the node map generation: on the +nested `@graph` document it costs 18 % more than the expansion alone. The serialization from RDF takes an +`RdfDataset` or N-Quads: on the 1,600 statements dataset, reading the N-Quads is two +thirds of the time (about 6 µs per statement), the algorithm itself the last third +(about 3.5 µs per statement). + ## Reproducing ```bash castor qa:install # phpbench and the other QA tools castor qa:phpunit:prepare # the W3C test suites castor qa:phpunit:download-fixtures # the HTML pages +composer dump-autoload -o # the optimized autoloader the figures are taken with castor qa:bench:all ``` `castor qa:bench:validators -d` additionally breaks the HTML pipeline down step by step (format detection, extraction, parsing, mapping, validation); it is slow. +The autoloader matters: without the optimized class map, the audits of a single document +are 2 to 10 % slower and the peak memory figures are 1.3 to 3 MB lower, the class map of +the 3,000 generated vocabulary classes not being loaded. + For finer time units than the default seconds, call PHPBench directly: ```bash @@ -95,5 +117,5 @@ tools/phpbench/vendor/bin/phpbench run tests/Algorithms/Benchmark --report=reada tools/phpbench/vendor/bin/phpbench run tests/Validation/Benchmark/JsonLdValidatorBench.php tests/Validation/Benchmark/WorkerValidationBench.php --report=readable --time-unit=milliseconds ``` -For the record, the full PHPUnit suite (1,496 tests, 3,317 assertions, W3C suites +For the record, the full PHPUnit suite (2,281 tests, 4,802 assertions, W3C suites included) runs in about 20 seconds on the same machine. diff --git a/CHANGELOG.md b/CHANGELOG.md index 963a805fb..cedcfa604 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,83 @@ # Changelog +## [Unreleased] + +### Added + +- The RDF serialization and deserialization algorithms of JSON-LD 1.1: `ToRdfConverter` + turns a JSON-LD document into an `RdfDataset`, `FromRdfConverter` turns a dataset or + N-Quads into an expanded document, and `NQuadsParser` / `NQuadsSerializer` read and + write N-Quads. Generalized RDF, both `rdfDirection` forms, native types and JSON + literals (canonicalized with RFC 8785) are supported. The official `toRdf` and `fromRdf` + test suites pass, and are part of `castor qa:earl`. From the command line: + `castor json-ld:to-rdf` and `castor json-ld:from-rdf`. See [docs/json-ld.md](docs/json-ld.md#rdf). +- A document given to an algorithm as a URL may be an HTML page: the JSON-LD of its + ` + + + + + +

text

+ + HTML; + + public function testTheFirstScriptIsExtractedByDefault(): void + { + $extracted = (new HtmlScriptExtractor())->extract(self::PAGE); + + $this->assertEquals((object) ['name' => 'first'], $extracted['document']); + $this->assertNull($extracted['base']); + } + + public function testEveryScriptIsExtractedWhenAskedAndArraysAreMerged(): void + { + $extracted = (new HtmlScriptExtractor())->extract(self::PAGE, options: new LoadDocumentOptions(extractAllScripts: true)); + + $this->assertEquals( + [ + (object) ['name' => 'first'], + (object) ['name' => 'second'], + (object) ['name' => 'third'], + (object) ['@context' => (object) ['name' => 'http://example.com/name']], + ], + $extracted['document'], + ); + } + + public function testAFragmentTargetsOneScriptWhateverTheOtherOptions(): void + { + $extracted = (new HtmlScriptExtractor())->extract(self::PAGE, 'second', new LoadDocumentOptions(extractAllScripts: true)); + + $this->assertEquals([(object) ['name' => 'second'], (object) ['name' => 'third']], $extracted['document']); + } + + public function testAFragmentIsPercentDecoded(): void + { + $page = ''; + + $this->assertEquals((object) ['name' => 'accent'], (new HtmlScriptExtractor())->extract($page, '%C3%A9%20a')['document']); + } + + #[DataProvider('provideFragmentsThatAreNotAJsonLdScript')] + public function testAFragmentThatIsNotAJsonLdScriptIsRefused(string $fragment): void + { + $this->expectExceptionObject(new DocumentLoadingException('loading document failed')); + + (new HtmlScriptExtractor())->extract(self::PAGE, $fragment); + } + + /** + * @return iterable + */ + public static function provideFragmentsThatAreNotAJsonLdScript(): iterable + { + yield 'no such element' => ['missing']; + yield 'not a script' => ['paragraph']; + yield 'a script of another type' => ['other']; + } + + public function testAProfileSelectsTheScriptThatDeclaresIt(): void + { + $extracted = (new HtmlScriptExtractor())->extract(self::PAGE, options: LoadDocumentOptions::forContext()); + + $this->assertEquals((object) ['@context' => (object) ['name' => 'http://example.com/name']], $extracted['document']); + } + + public function testAProfileNoScriptDeclaresFallsBackToTheFirstScript(): void + { + $extracted = (new HtmlScriptExtractor())->extract(self::PAGE, options: new LoadDocumentOptions(profile: 'http://example.com/profile')); + + $this->assertEquals((object) ['name' => 'first'], $extracted['document']); + } + + public function testAPageWithoutScriptIsRefusedUnlessEveryScriptIsAskedFor(): void + { + $extractor = new HtmlScriptExtractor(); + + $this->assertSame([], $extractor->extract('', options: new LoadDocumentOptions(extractAllScripts: true))['document']); + + $this->expectExceptionObject(new DocumentLoadingException('loading document failed')); + + $extractor->extract(''); + } + + #[DataProvider('provideInvalidScripts')] + public function testAScriptThatIsNotAJsonDocumentIsRefused(string $content): void + { + $this->expectExceptionObject(new DocumentLoadingException('invalid script element')); + + (new HtmlScriptExtractor())->extract(\sprintf('', $content)); + } + + /** + * @return iterable + */ + public static function provideInvalidScripts(): iterable + { + yield 'not JSON' => ['{"name": }']; + yield 'a comment around the JSON' => ['']; + yield 'a scalar' => ['"just a string"']; + yield 'empty' => ['']; + } + + public function testTheTextOfAScriptIsTakenAsItIsWritten(): void + { + $page = ''; + + $this->assertEquals((object) ['name' => 'café ☕ <&> bold'], (new HtmlScriptExtractor())->extract($page)['document']); + } + + public function testTheBaseElementIsHandedBackAsWritten(): void + { + $page = ''; + + $this->assertSame('../base/', (new HtmlScriptExtractor())->extract($page)['base']); + } +} diff --git a/tests/Algorithms/Http/HttpDocumentLoaderTest.php b/tests/Algorithms/Http/HttpDocumentLoaderTest.php index f560ef998..8c870bc7e 100644 --- a/tests/Algorithms/Http/HttpDocumentLoaderTest.php +++ b/tests/Algorithms/Http/HttpDocumentLoaderTest.php @@ -11,7 +11,7 @@ namespace JoliCode\StructuredData\Tests\Algorithms\Http; -use JoliCode\StructuredData\JsonLd\Algorithms\Exception\ContextProcessingException; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\DocumentLoadingException; use JoliCode\StructuredData\JsonLd\Algorithms\Http\HttpDocumentLoader; use JoliCode\StructuredData\JsonLd\Algorithms\Http\RemoteContextPolicy; use PHPUnit\Framework\Attributes\DataProvider; @@ -23,12 +23,14 @@ #[Group('security')] class HttpDocumentLoaderTest extends TestCase { + private const JSON_LD = ['response_headers' => ['Content-Type' => 'application/ld+json']]; + public function testTheDefaultPolicyRefusesEveryHostWithoutIssuingARequest(): void { $loader = new HttpDocumentLoader(httpClient: $this->clientThatMustNotBeCalled()); - $this->expectException(ContextProcessingException::class); - $this->expectExceptionMessage('loading remote context failed'); + $this->expectException(DocumentLoadingException::class); + $this->expectExceptionMessage('loading document failed'); $loader->load('https://example.com/context.jsonld'); } @@ -37,12 +39,12 @@ public function testAnAllowedHostIsFetched(): void { $loader = new HttpDocumentLoader( RemoteContextPolicy::allowHosts('example.com'), - new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}')), + new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}', self::JSON_LD)), ); $document = $loader->load('https://example.com/context.jsonld'); - $this->assertSame('https://schema.org/name', $document->{'@context'}->name); + $this->assertEquals((object) ['@context' => (object) ['name' => 'https://schema.org/name']], $document->document); } public function testAHostOutsideTheAllowListIsRefused(): void @@ -52,7 +54,7 @@ public function testAHostOutsideTheAllowListIsRefused(): void $this->clientThatMustNotBeCalled(), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('https://other.example/context.jsonld'); } @@ -68,7 +70,7 @@ public function testHostMatchingIsExact(): void $this->clientThatMustNotBeCalled(), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('https://evil.schema.org.example/context.jsonld'); } @@ -85,8 +87,8 @@ public function testNonHttpUrlsAreRefused(string $url): void $this->clientThatMustNotBeCalled(), ); - $this->expectException(ContextProcessingException::class); - $this->expectExceptionMessage('loading remote context failed'); + $this->expectException(DocumentLoadingException::class); + $this->expectExceptionMessage('loading document failed'); $loader->load($url); } @@ -111,7 +113,7 @@ public function testPlainHttpIsRefusedUnlessExplicitlyAllowed(): void $this->clientThatMustNotBeCalled(), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('http://example.com/context.jsonld'); } @@ -130,8 +132,8 @@ public function testAnErrorResponseNeverLeaksItsBody(): void try { $loader->load('https://example.com/internal-service'); $this->fail('The loader should have refused the response.'); - } catch (ContextProcessingException $exception) { - $this->assertSame('loading remote context failed', $exception->getMessage()); + } catch (DocumentLoadingException $exception) { + $this->assertSame('loading document failed', $exception->getMessage()); $this->assertStringNotContainsString('SECRET', $exception->getMessage()); $this->assertStringNotContainsString('404', $exception->getMessage()); $this->assertStringNotContainsString('example.com', $exception->getMessage()); @@ -142,10 +144,10 @@ public function testAnOversizedResponseIsRefused(): void { $loader = new HttpDocumentLoader( RemoteContextPolicy::allowHosts('example.com')->withMaxResponseBytes(1024), - new MockHttpClient(new MockResponse(str_repeat('a', 4096))), + new MockHttpClient(new MockResponse(str_repeat('a', 4096), self::JSON_LD)), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('https://example.com/huge.jsonld'); } @@ -158,12 +160,12 @@ public function testARedirectOutOfTheAllowListIsRefused(): void { $loader = new HttpDocumentLoader( RemoteContextPolicy::allowHosts('example.com'), - new MockHttpClient(new MockResponse('{"@context":{}}', [ + new MockHttpClient(new MockResponse('{"@context":{}}', self::JSON_LD + [ 'url' => 'https://evil.example/context.jsonld', ])), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('https://example.com/context.jsonld'); } @@ -178,11 +180,11 @@ public function testARedirectToADisallowedHostIsRefusedAtTheHop(): void RemoteContextPolicy::allowHosts('example.com'), new MockHttpClient([ new MockResponse('', ['http_code' => 302, 'response_headers' => ['Location' => 'https://evil.example/context.jsonld']]), - new MockResponse('{"@context":{}}'), + new MockResponse('{"@context":{}}', self::JSON_LD), ]), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load('https://example.com/context.jsonld'); } @@ -196,13 +198,13 @@ public function testARedirectInsideTheAllowListIsFollowed(): void RemoteContextPolicy::allowHosts('example.com'), new MockHttpClient([ new MockResponse('', ['http_code' => 302, 'response_headers' => ['Location' => 'https://example.com/real.jsonld']]), - new MockResponse('{"@context":{"name":"https://schema.org/name"}}'), + new MockResponse('{"@context":{"name":"https://schema.org/name"}}', self::JSON_LD), ]), ); $document = $loader->load('https://example.com/context.jsonld'); - $this->assertSame('https://schema.org/name', $document->{'@context'}->name); + $this->assertEquals((object) ['@context' => (object) ['name' => 'https://schema.org/name']], $document->document); } #[DataProvider('provideUrlsRefusedByPolicyRefinements')] @@ -213,7 +215,7 @@ public function testUrlsWithUserinfoOrNonDefaultPortsAreRefused(string $url): vo $this->clientThatMustNotBeCalled(), ); - $this->expectException(ContextProcessingException::class); + $this->expectException(DocumentLoadingException::class); $loader->load($url); } @@ -240,8 +242,8 @@ public function testATransportFailureIsReportedOpaquely(): void try { $loader->load('https://example.com/context.jsonld'); $this->fail('The loader should have refused the response.'); - } catch (ContextProcessingException $exception) { - $this->assertSame('loading remote context failed', $exception->getMessage()); + } catch (DocumentLoadingException $exception) { + $this->assertSame('loading document failed', $exception->getMessage()); } } diff --git a/tests/Algorithms/Http/IriResolverTest.php b/tests/Algorithms/Http/IriResolverTest.php new file mode 100644 index 000000000..d2e007616 --- /dev/null +++ b/tests/Algorithms/Http/IriResolverTest.php @@ -0,0 +1,121 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Http; + +use JoliCode\StructuredData\JsonLd\Algorithms\Http\IriResolver; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * JSON-LD resolves a relative IRI with the algorithm of RFC 3986 section 5.2 + * and nothing more: no normalization, no percent-encoding. + */ +#[Group('algorithms')] +class IriResolverTest extends TestCase +{ + private const BASE = 'http://a/b/c/d;p?q'; + + #[DataProvider('provideRfc3986Examples')] + public function testTheExamplesOfRfc3986(string $reference, string $expected): void + { + $this->assertSame($expected, IriResolver::resolveIri(self::BASE, $reference)); + } + + /** + * RFC 3986 sections 5.4.1 (normal examples) and 5.4.2 (abnormal examples). + * + * @return iterable + */ + public static function provideRfc3986Examples(): iterable + { + $examples = [ + 'g:h' => 'g:h', + 'g' => 'http://a/b/c/g', + './g' => 'http://a/b/c/g', + 'g/' => 'http://a/b/c/g/', + '/g' => 'http://a/g', + '//g' => 'http://g', + '?y' => 'http://a/b/c/d;p?y', + 'g?y' => 'http://a/b/c/g?y', + '#s' => 'http://a/b/c/d;p?q#s', + 'g#s' => 'http://a/b/c/g#s', + 'g?y#s' => 'http://a/b/c/g?y#s', + ';x' => 'http://a/b/c/;x', + 'g;x' => 'http://a/b/c/g;x', + 'g;x?y#s' => 'http://a/b/c/g;x?y#s', + '' => 'http://a/b/c/d;p?q', + '.' => 'http://a/b/c/', + './' => 'http://a/b/c/', + '..' => 'http://a/b/', + '../' => 'http://a/b/', + '../g' => 'http://a/b/g', + '../..' => 'http://a/', + '../../' => 'http://a/', + '../../g' => 'http://a/g', + '../../../g' => 'http://a/g', + '../../../../g' => 'http://a/g', + '/./g' => 'http://a/g', + '/../g' => 'http://a/g', + 'g.' => 'http://a/b/c/g.', + '.g' => 'http://a/b/c/.g', + 'g..' => 'http://a/b/c/g..', + '..g' => 'http://a/b/c/..g', + './../g' => 'http://a/b/g', + './g/.' => 'http://a/b/c/g/', + 'g/./h' => 'http://a/b/c/g/h', + 'g/../h' => 'http://a/b/c/h', + 'g;x=1/./y' => 'http://a/b/c/g;x=1/y', + 'g;x=1/../y' => 'http://a/b/c/y', + 'g?y/./x' => 'http://a/b/c/g?y/./x', + 'g?y/../x' => 'http://a/b/c/g?y/../x', + 'g#s/./x' => 'http://a/b/c/g#s/./x', + 'g#s/../x' => 'http://a/b/c/g#s/../x', + 'http:g' => 'http:g', + ]; + + foreach ($examples as $reference => $expected) { + yield \sprintf('"%s"', $reference) => [(string) $reference, $expected]; + } + } + + #[DataProvider('provideReferences')] + public function testNothingIsNormalized(?string $base, string $reference, string $expected): void + { + $this->assertSame($expected, IriResolver::resolveIri($base, $reference)); + } + + /** + * @return iterable + */ + public static function provideReferences(): iterable + { + yield 'a query keeps the dot segments of the base' => ['http://a/bb/ccc/./d;p?q', '?y', 'http://a/bb/ccc/./d;p?y']; + yield 'a fragment keeps the dot segments of the base' => ['http://a/bb/ccc/../d;p?q', '#s', 'http://a/bb/ccc/../d;p?q#s']; + yield 'an empty reference keeps the dot segments of the base' => ['http://a/bb/ccc/../d;p?q#f', '', 'http://a/bb/ccc/../d;p?q']; + yield 'a fragment replaces the fragment of the base' => ['http://a/b?q#old', '#new', 'http://a/b?q#new']; + yield 'a query replaces the query and the fragment of the base' => ['http://a/b?old#f', '?new', 'http://a/b?new']; + yield 'a path merges with a base holding dot segments' => ['http://a/bb/ccc/../d;p?q', '../../', 'http://a/']; + yield 'the root keeps its slash' => ['http://a/b', '..', 'http://a/']; + yield 'a base without a path' => ['http://a', 'g', 'http://a/g']; + yield 'a file base' => ['file:///a/bb/ccc/d;p?q', 'g?y', 'file:///a/bb/ccc/g?y']; + yield 'characters of an IRI are not percent-encoded' => ['http://example.com/', 'é/ü?ñ#ø', 'http://example.com/é/ü?ñ#ø']; + yield 'the host keeps its case' => ['http://EXAMPLE.com/A/%7euser', 'x', 'http://EXAMPLE.com/A/x']; + yield 'percent-encoded characters are left alone' => ['http://example.com/', '%7Euser/%c3%a9', 'http://example.com/%7Euser/%c3%a9']; + yield 'an absolute IRI is not touched' => ['http://example.com/', 'http://other.example/a/../b', 'http://other.example/a/../b']; + yield 'a blank node identifier is not touched' => ['http://example.com/', '_:b0', '_:b0']; + yield 'no base' => [null, 'relative', 'relative']; + yield 'an empty base' => ['', 'relative', 'relative']; + yield 'a reference that is not an IRI stays as it is' => ['http://example.com/', 'a b', 'a b']; + yield 'characters an IRI may not hold are not percent-encoded either' => ['http://example.com/', 'a/', 'http://example.com/a/']; + } +} diff --git a/tests/Algorithms/Http/LinkHeaderParserTest.php b/tests/Algorithms/Http/LinkHeaderParserTest.php new file mode 100644 index 000000000..4a2083274 --- /dev/null +++ b/tests/Algorithms/Http/LinkHeaderParserTest.php @@ -0,0 +1,65 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Http; + +use JoliCode\StructuredData\JsonLd\Algorithms\Http\LinkHeaderParser; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +#[Group('algorithms')] +class LinkHeaderParserTest extends TestCase +{ + public function testAHeaderListingSeveralLinksIsSplit(): void + { + $this->assertSame( + [ + ['uri' => 'context.jsonld', 'rel' => 'http://www.w3.org/ns/json-ld#context', 'type' => 'application/ld+json'], + ['uri' => 'other.jsonld', 'rel' => 'alternate'], + ], + LinkHeaderParser::parse([ + '; rel="http://www.w3.org/ns/json-ld#context"; type="application/ld+json", ; rel="alternate"', + ]), + ); + } + + public function testACommaInsideAQuotedParameterDoesNotSplitTheLink(): void + { + $this->assertSame( + [['uri' => 'context.jsonld', 'rel' => 'alternate', 'title' => 'one, two']], + LinkHeaderParser::parse(['; rel="alternate"; title="one, two"']), + ); + } + + public function testAParameterValueMayBeABareToken(): void + { + $this->assertSame( + [['uri' => 'document.jsonld', 'rel' => 'alternate', 'type' => 'application/ld+json']], + LinkHeaderParser::parse(['; rel=alternate; type="application/ld+json"']), + ); + } + + public function testAnEqualSignInsideAValueIsKept(): void + { + $this->assertSame( + [['uri' => 'document.jsonld', 'title' => 'a=b', 'anchor' => 'c=d']], + LinkHeaderParser::parse(['; title="a=b"; anchor=c=d']), + ); + } + + public function testAValuelessParameterAndAMalformedLinkAreIgnored(): void + { + $this->assertSame( + [['uri' => 'context.jsonld', 'type' => 'application/ld+json']], + LinkHeaderParser::parse(['; rel; type="application/ld+json"', 'not a link']), + ); + } +} diff --git a/tests/Algorithms/Http/RemoteDocumentLoadingTest.php b/tests/Algorithms/Http/RemoteDocumentLoadingTest.php new file mode 100644 index 000000000..9167c1d9b --- /dev/null +++ b/tests/Algorithms/Http/RemoteDocumentLoadingTest.php @@ -0,0 +1,261 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Http; + +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\ContextProcessingException; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\DocumentLoadingException; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\HttpDocumentLoader; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\LoadDocumentOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\RemoteContextPolicy; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; +use Symfony\Component\HttpClient\MockHttpClient; +use Symfony\Component\HttpClient\Response\MockResponse; + +/** + * What a document loaded from a URL is, beyond what the W3C remote-doc and html + * suites ask: the answers below are the ones a server may give. + */ +#[Group('algorithms')] +class RemoteDocumentLoadingTest extends TestCase +{ + #[DataProvider('provideAcceptedContentTypes')] + public function testJsonContentTypesAreAccepted(string $contentType, string $expectedContentType, ?string $expectedProfile): void + { + $document = $this->loader(['https://example.com/doc' => ['{"name": "doc"}', $contentType]])->load('https://example.com/doc'); + + $this->assertEquals((object) ['name' => 'doc'], $document->document); + $this->assertSame($expectedContentType, $document->contentType); + $this->assertSame($expectedProfile, $document->profile); + $this->assertSame('https://example.com/doc', $document->documentUrl); + } + + /** + * @return iterable + */ + public static function provideAcceptedContentTypes(): iterable + { + yield 'JSON-LD' => ['application/ld+json', 'application/ld+json', null]; + yield 'JSON' => ['application/json', 'application/json', null]; + yield 'a +json type' => ['application/activity+json', 'application/activity+json', null]; + yield 'parameters and case' => ['Application/LD+JSON; charset=utf-8; profile="http://www.w3.org/ns/json-ld#expanded"', 'application/ld+json', 'http://www.w3.org/ns/json-ld#expanded']; + } + + #[DataProvider('provideRefusedContentTypes')] + public function testAnyOtherContentTypeIsRefusedEvenWhenTheBodyIsJson(?string $contentType): void + { + $this->expectExceptionObject(new DocumentLoadingException('loading document failed')); + + $this->loader(['https://example.com/doc' => ['{"name": "doc"}', $contentType]])->load('https://example.com/doc'); + } + + /** + * @return iterable + */ + public static function provideRefusedContentTypes(): iterable + { + yield 'plain text' => ['text/plain']; + yield 'binary' => ['application/octet-stream']; + yield 'javascript' => ['application/javascript']; + yield 'no content type' => [null]; + } + + public function testAJsonDocumentThatIsAnArrayStaysAnArray(): void + { + $document = $this->loader(['https://example.com/doc' => ['[{"name": "a"}, {"name": "b"}]', 'application/ld+json']])->load('https://example.com/doc'); + + $this->assertEquals([(object) ['name' => 'a'], (object) ['name' => 'b']], $document->document); + } + + public function testAJsonBodyThatIsNotADocumentIsRefused(): void + { + $this->expectExceptionObject(new DocumentLoadingException('loading document failed')); + + $this->loader(['https://example.com/doc' => ['"a string"', 'application/ld+json']])->load('https://example.com/doc'); + } + + public function testTheDocumentUrlIsWhereARedirectionLeads(): void + { + $loader = $this->loader([ + 'https://example.com/old' => ['', null, [], 301, 'https://example.com/new/doc'], + 'https://example.com/new/doc' => ['{"@id": ""}', 'application/ld+json'], + ]); + + $this->assertSame('https://example.com/new/doc', $loader->load('https://example.com/old')->documentUrl); + } + + public function testTheContextOfAJsonDocumentIsResolvedAgainstItsLocation(): void + { + $document = $this->loader(['https://example.com/a/doc' => ['{}', 'application/json', ['<../context.jsonld>; rel="http://www.w3.org/ns/json-ld#context"']]])->load('https://example.com/a/doc'); + + $this->assertSame('https://example.com/context.jsonld', $document->contextUrl); + } + + public function testTheContextLinkOfAJsonLdDocumentIsIgnored(): void + { + $document = $this->loader(['https://example.com/doc' => ['{}', 'application/ld+json', ['; rel="http://www.w3.org/ns/json-ld#context"']]])->load('https://example.com/doc'); + + $this->assertNull($document->contextUrl); + } + + public function testSeveralContextLinksAreRefused(): void + { + $this->expectExceptionObject(new DocumentLoadingException('multiple context link headers')); + + $this->loader(['https://example.com/doc' => ['{}', 'application/json', [ + '; rel="http://www.w3.org/ns/json-ld#context"', + '; rel="http://www.w3.org/ns/json-ld#context"', + ]]])->load('https://example.com/doc'); + } + + public function testAnAlternateLinkIsFollowedFromADocumentThatIsNotJson(): void + { + $loader = $this->loader([ + 'https://example.com/page' => ['', 'text/html', ['; rel="alternate"; type="application/ld+json"']], + 'https://example.com/data/doc.jsonld' => ['{"name": "alternate"}', 'application/ld+json'], + ]); + + $document = $loader->load('https://example.com/page'); + + $this->assertEquals((object) ['name' => 'alternate'], $document->document); + $this->assertSame('https://example.com/data/doc.jsonld', $document->documentUrl); + } + + public function testAnAlternateLinkIsNotFollowedFromAJsonDocument(): void + { + $loader = $this->loader([ + 'https://example.com/doc.json' => ['{"name": "json"}', 'application/json', ['; rel="alternate"; type="application/ld+json"']], + 'https://example.com/doc.jsonld' => ['{"name": "alternate"}', 'application/ld+json'], + ]); + + $this->assertEquals((object) ['name' => 'json'], $loader->load('https://example.com/doc.json')->document); + } + + public function testAnHtmlDocumentHandsItsScriptAndItsBase(): void + { + $page = ''; + $loader = $this->loader(['https://example.com/page' => [$page, 'text/html; charset=utf-8']]); + + $first = $loader->load('https://example.com/page'); + $this->assertEquals((object) ['name' => 'first'], $first->document); + $this->assertSame('text/html', $first->contentType); + $this->assertSame('/base/', $first->htmlBase); + $this->assertSame('https://example.com/page', $first->documentUrl); + + $this->assertEquals((object) ['name' => 'second'], $loader->load('https://example.com/page#two')->document); + $this->assertCount(2, (array) $loader->load('https://example.com/page', new LoadDocumentOptions(extractAllScripts: true))->document); + } + + public function testADocumentIsAskedAsJsonLdThenJsonThenHtml(): void + { + $accept = []; + $loader = $this->loader(['https://example.com/doc' => ['{}', 'application/ld+json']], $accept); + + $loader->load('https://example.com/doc'); + $loader->load('https://example.com/doc', LoadDocumentOptions::forContext()); + + $this->assertSame([ + 'application/ld+json,application/json;q=0.9,text/html;q=0.8,application/xhtml+xml;q=0.8,*/*;q=0.1', + 'application/ld+json;profile="http://www.w3.org/ns/json-ld#context",application/json;q=0.9,*/*;q=0.1', + ], $accept); + } + + public function testTheBaseOptionTakesPrecedenceOverTheLocationOfTheDocument(): void + { + $loader = $this->loader(['https://example.com/dir/doc' => ['{"@id": "relative", "http://example.com/p": "v"}', 'application/ld+json']]); + + $expander = new Expander(documentLoader: $loader); + $expected = static fn (string $identifier): array => [(object) ['@id' => $identifier, 'http://example.com/p' => [(object) ['@value' => 'v']]]]; + + $this->assertEquals($expected('https://example.com/dir/relative'), $expander->expand('https://example.com/dir/doc', encodeResult: false)); + $this->assertEquals($expected('https://other.example/relative'), $expander->expand('https://example.com/dir/doc', new ProcessorOptions(base: 'https://other.example/'), false)); + } + + public function testAUrlIsGivenAsItIsOrAsAJsonString(): void + { + $loader = $this->loader(['https://example.com/doc' => ['{"http://example.com/p": "v"}', 'application/ld+json']]); + $expander = new Expander(documentLoader: $loader); + + $this->assertSame($expander->expand('https://example.com/doc'), $expander->expand('"https://example.com/doc"')); + } + + public function testTheLinkedContextComesBeforeTheOneOfTheDocument(): void + { + $loader = $this->loader([ + 'https://example.com/doc' => ['{"@context": {"b": "http://example.com/own-b"}, "a": "1", "b": "2"}', 'application/json', ['; rel="http://www.w3.org/ns/json-ld#context"']], + 'https://example.com/context' => ['{"@context": {"a": "http://example.com/linked-a", "b": "http://example.com/linked-b"}}', 'application/ld+json'], + ]); + + $expanded = (new Expander(documentLoader: $loader))->expand('https://example.com/doc', encodeResult: false); + + $this->assertEquals([(object) [ + 'http://example.com/linked-a' => [(object) ['@value' => '1']], + 'http://example.com/own-b' => [(object) ['@value' => '2']], + ]], $expanded); + } + + public function testADocumentThatCannotBeLoadedAndAContextThatCannotBeLoadedHaveDifferentNames(): void + { + $loader = $this->loader(['https://example.com/doc' => ['{"@context": "https://example.com/missing"}', 'application/ld+json']]); + $expander = new Expander(documentLoader: $loader); + + try { + $expander->expand('https://example.com/nowhere'); + $this->fail('A missing document was loaded.'); + } catch (JsonLdException $exception) { + $this->assertSame('loading document failed', $exception->getMessage()); + } + + $this->expectExceptionObject(new ContextProcessingException('loading remote context failed')); + + $expander->expand('https://example.com/doc'); + } + + /** + * @param array, 3?: int, 4?: string}> $pages body, content type, Link headers, status and Location per URL + * @param list $accept filled with the Accept header of every request + */ + private function loader(array $pages, array &$accept = []): HttpDocumentLoader + { + $client = new MockHttpClient(static function (string $method, string $url, array $options) use ($pages, &$accept): MockResponse { + $accept[] = $options['normalized_headers']['accept'][0] ?? ''; + $accept[array_key_last($accept)] = (string) preg_replace('/^Accept: /i', '', $accept[array_key_last($accept)]); + + if (!\array_key_exists($url, $pages)) { + return new MockResponse('not here', ['http_code' => 404]); + } + + $page = $pages[$url]; + $headers = []; + + if (null !== $page[1]) { + $headers['Content-Type'] = $page[1]; + } + + if ([] !== ($page[2] ?? [])) { + $headers['Link'] = $page[2]; + } + + if (isset($page[4])) { + $headers['Location'] = $page[4]; + } + + return new MockResponse($page[0], ['http_code' => $page[3] ?? 200, 'response_headers' => $headers]); + }); + + return new HttpDocumentLoader(RemoteContextPolicy::allowHosts('example.com', 'other.example'), $client); + } +} diff --git a/tests/Algorithms/Manifest/AbstractRemoteDocumentTestCase.php b/tests/Algorithms/Manifest/AbstractRemoteDocumentTestCase.php new file mode 100644 index 000000000..409f1431a --- /dev/null +++ b/tests/Algorithms/Manifest/AbstractRemoteDocumentTestCase.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Manifest; + +use JoliCode\StructuredData\JsonLd\Algorithms\Compact\Compactor; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander; +use JoliCode\StructuredData\JsonLd\Algorithms\Flatten\Flattener; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsParser; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; +use JoliCode\StructuredData\Tests\Algorithms\Rdf\RdfDatasetIsomorphism; +use PHPUnit\Framework\TestCase; + +/** + * Runs the entries of a W3C manifest whose input is the URL of a document: + * the algorithm the entry names is handed that URL, and W3cFixtureServer + * answers it the way the manifest says. + */ +abstract class AbstractRemoteDocumentTestCase extends TestCase +{ + /** + * @param array $server + */ + protected function runManifestEntry(string $algorithm, string $url, ?string $context, ?string $expect, ?string $errorCode, ProcessorOptions $options, array $server): void + { + if (null !== $errorCode) { + try { + $this->process($algorithm, $url, $context, $options, $server); + } catch (JsonLdException $exception) { + $this->assertSame($errorCode, $exception->getMessage()); + + return; + } + + $this->fail(\sprintf('An exception was expected for this test but none were thrown. Expected error message was : %s', $errorCode)); + } + + $actual = $this->process($algorithm, $url, $context, $options, $server); + + $this->assertNotNull($expect, 'A positive evaluation test names its expected output.'); + + if ('toRdf' === $algorithm) { + $this->assertTrue( + RdfDatasetIsomorphism::areIsomorphic((new NQuadsParser())->parse($expect), (new NQuadsParser())->parse($actual)), + \sprintf("The datasets are not isomorphic.\nExpected:\n%s\nActual:\n%s", $expect, $actual), + ); + + return; + } + + $this->assertEquals(json_decode($expect), json_decode($actual), \sprintf("Expected:\n%s\nActual:\n%s", $expect, $actual)); + } + + /** + * @param array $server + */ + private function process(string $algorithm, string $url, ?string $context, ProcessorOptions $options, array $server): string + { + $documentLoader = W3cFixtureServer::documentLoader($url, $server); + + $result = match ($algorithm) { + 'expand' => (new Expander(documentLoader: $documentLoader))->expand($url, $options), + 'compact' => (new Compactor(documentLoader: $documentLoader))->compact($url, $context, $options), + 'flatten' => (new Flattener(documentLoader: $documentLoader))->flatten($url, $context, $options), + 'toRdf' => NQuadsSerializer::serialize((new ToRdfConverter(documentLoader: $documentLoader))->toRdf($url, $options)), + default => throw new \LogicException(\sprintf('The "%s" algorithm does not take a URL.', $algorithm)), + }; + + $this->assertIsString($result); + + return $result; + } +} diff --git a/tests/Algorithms/Manifest/ManifestTestProvider.php b/tests/Algorithms/Manifest/ManifestTestProvider.php new file mode 100644 index 000000000..0ba7e5454 --- /dev/null +++ b/tests/Algorithms/Manifest/ManifestTestProvider.php @@ -0,0 +1,193 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Manifest; + +use JoliCode\StructuredData\JsonLd\Algorithms\ContextProcessing\Context; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\Tests\Algorithms\AbstractJsonLdTestCase; + +/** + * Turns a W3C manifest into PHPUnit data sets, one per entry and named after + * the fragment of its IRI ("#t0001"), which is what the EARL report maps the + * outcomes back with. + * + * The entries written for a JSON-LD 1.0 processor only are left out: they + * describe a behaviour JSON-LD 1.1 changed. + */ +final class ManifestTestProvider +{ + public const BASE_IRI = 'https://w3c.github.io/json-ld-api/tests/'; + + private const OPTIONS = ['base', 'expandContext', 'extractAllScripts', 'processingMode', 'produceGeneralizedRdf', 'rdfDirection', 'useNativeTypes', 'useRdfType']; + + /** + * What a manifest says of how its input is served, which is the business of + * the simulated server and not of the processor. + */ + private const SERVER_OPTIONS = ['contentType', 'httpLink', 'httpStatus', 'redirectTo']; + + private const ALGORITHMS = [ + 'jld:ExpandTest' => 'expand', + 'jld:CompactTest' => 'compact', + 'jld:FlattenTest' => 'flatten', + 'jld:ToRDFTest' => 'toRdf', + 'jld:FromRDFTest' => 'fromRdf', + ]; + + /** + * What a manifest says of a test without it being an option of the + * processor: the version of the specification it was written for, whether + * it is normative, the canonicalization the JSON literals are compared + * under, which is the only one there is, and the optional feature it needs. + */ + private const IGNORED_OPTIONS = ['specVersion', 'normative', 'useJCS', 'processorFeature']; + + /** + * @return iterable + */ + public static function provide(string $suite): iterable + { + foreach (self::entries($suite) as $id => $entry) { + yield $id => [ + 'input' => self::read($entry['input']), + 'expect' => null === $entry['expect'] ? null : self::read($entry['expect']), + 'errorCode' => $entry['errorCode'], + 'options' => self::options($entry['entryOptions'], self::BASE_IRI . $entry['input']), + ]; + } + } + + /** + * The data sets of a suite whose input is a URL, the document being served + * by W3cFixtureServer: the base IRI is then the location of the document, + * unless the manifest sets one. + * + * @return iterable}> + */ + public static function provideDocuments(string $suite): iterable + { + foreach (self::entries($suite) as $id => $entry) { + yield $id => [ + 'algorithm' => $entry['algorithm'], + 'url' => self::BASE_IRI . $entry['input'], + 'context' => null === $entry['context'] ? null : self::read($entry['context']), + 'expect' => null === $entry['expect'] ? null : self::read($entry['expect']), + 'errorCode' => $entry['errorCode'], + 'options' => self::options($entry['entryOptions'], null), + 'server' => array_intersect_key($entry['entryOptions'], array_flip(self::SERVER_OPTIONS)), + ]; + } + } + + /** + * Where a file of the test suite is, given its path in the manifest. The + * RDF suites keep the upstream layout; the few files they borrow from the + * other suites are filed by kind ("expand/er56-in.jsonld" is in + * "expand/input/"). + */ + public static function fixturePath(string $path): string + { + $path = explode('#', $path, 2)[0]; + $file = \sprintf('%s/%s', AbstractJsonLdTestCase::DATA_PATH, $path); + + if (is_file($file)) { + return $file; + } + + foreach (['-in.jsonld' => 'input', '-out.jsonld' => 'output', '-context.jsonld' => 'context'] as $suffix => $directory) { + if (str_ends_with($path, $suffix)) { + return \sprintf('%s/%s/%s/%s', AbstractJsonLdTestCase::DATA_PATH, \dirname($path), $directory, basename($path)); + } + } + + return $file; + } + + /** + * @return iterable}> + */ + private static function entries(string $suite): iterable + { + $manifestFile = \sprintf('%s/%s-manifest.jsonld', AbstractJsonLdTestCase::DATA_PATH, $suite); + + if (!is_file($manifestFile)) { + throw new \RuntimeException(\sprintf('The manifest "%s" does not exist. Did you forget to install the test suite? Please run the following command : `castor qa:phpunit:prepare`', $manifestFile)); + } + + $manifest = json_decode((string) file_get_contents($manifestFile), true); + + if (!\is_array($manifest) || !\is_array($manifest['sequence'] ?? null)) { + throw new \RuntimeException(\sprintf('The manifest "%s" could not be read.', $manifestFile)); + } + + foreach ($manifest['sequence'] as $entry) { + if (!\is_array($entry) || !\is_string($entry['@id'] ?? null) || !\is_string($entry['input'] ?? null)) { + continue; + } + + $entryOptions = \is_array($entry['option'] ?? null) ? $entry['option'] : []; + + if ('json-ld-1.0' === ($entryOptions['specVersion'] ?? null)) { + continue; + } + + $unknownOptions = array_diff(array_keys($entryOptions), self::OPTIONS, self::SERVER_OPTIONS, self::IGNORED_OPTIONS); + + if ([] !== $unknownOptions) { + throw new \RuntimeException(\sprintf('The test "%s" sets options this provider does not know: %s.', $entry['@id'], implode(', ', $unknownOptions))); + } + + $algorithms = array_values(array_intersect_key(self::ALGORITHMS, array_flip(\is_array($entry['@type'] ?? null) ? array_filter($entry['@type'], \is_string(...)) : []))); + + if (1 !== \count($algorithms)) { + throw new \RuntimeException(\sprintf('The test "%s" does not name the algorithm it runs.', $entry['@id'])); + } + + yield $entry['@id'] => [ + 'algorithm' => $algorithms[0], + 'input' => $entry['input'], + 'context' => \is_string($entry['context'] ?? null) ? $entry['context'] : null, + 'expect' => \is_string($entry['expect'] ?? null) ? $entry['expect'] : null, + 'errorCode' => \is_string($entry['expectErrorCode'] ?? null) ? $entry['expectErrorCode'] : null, + 'entryOptions' => $entryOptions, + ]; + } + } + + /** + * @param array $entryOptions + */ + private static function options(array $entryOptions, ?string $defaultBase): ProcessorOptions + { + return new ProcessorOptions( + base: \is_string($entryOptions['base'] ?? null) ? $entryOptions['base'] : $defaultBase, + expandContext: \is_string($entryOptions['expandContext'] ?? null) ? self::BASE_IRI . $entryOptions['expandContext'] : null, + extractAllScripts: \is_bool($entryOptions['extractAllScripts'] ?? null) ? $entryOptions['extractAllScripts'] : null, + processingMode: 'json-ld-1.0' === ($entryOptions['processingMode'] ?? null) ? Context::PROCESSING_MODE_10 : Context::PROCESSING_MODE_11, + produceGeneralizedRdf: true === ($entryOptions['produceGeneralizedRdf'] ?? false), + rdfDirection: \is_string($entryOptions['rdfDirection'] ?? null) ? $entryOptions['rdfDirection'] : null, + useNativeTypes: true === ($entryOptions['useNativeTypes'] ?? false), + useRdfType: true === ($entryOptions['useRdfType'] ?? false), + ); + } + + private static function read(string $path): string + { + $content = @file_get_contents(self::fixturePath($path)); + + if (false === $content) { + throw new \RuntimeException(\sprintf('The fixture "%s" could not be read.', $path)); + } + + return $content; + } +} diff --git a/tests/Algorithms/Manifest/W3cFixtureServer.php b/tests/Algorithms/Manifest/W3cFixtureServer.php new file mode 100644 index 000000000..18e5e1e93 --- /dev/null +++ b/tests/Algorithms/Manifest/W3cFixtureServer.php @@ -0,0 +1,78 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Manifest; + +use JoliCode\StructuredData\JsonLd\Algorithms\Http\DocumentLoaderInterface; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\HttpDocumentLoader; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\RemoteContextPolicy; +use Symfony\Component\HttpClient\MockHttpClient; +use Symfony\Component\HttpClient\Response\MockResponse; + +/** + * Stands for https://w3c.github.io/json-ld-api/tests/: it serves the copy of + * the test suite downloaded at the pinned commit, with the headers a manifest + * asks for. The tests then run offline, through the real HttpDocumentLoader, + * against the very revision their manifest comes from. + */ +final class W3cFixtureServer +{ + private const CONTENT_TYPES = [ + 'jsonld' => 'application/ld+json', + 'json' => 'application/json', + 'html' => 'text/html', + ]; + + /** + * @param string|null $url the URL the options below apply to: the input of a test + * @param array $server how the manifest wants that URL served: "contentType", "httpLink", "redirectTo" and "httpStatus" + */ + public static function documentLoader(?string $url = null, array $server = []): DocumentLoaderInterface + { + $inputUrl = null === $url ? null : explode('#', $url, 2)[0]; + + $client = new MockHttpClient(static function (string $method, string $requestedUrl) use ($inputUrl, $server): MockResponse { + $requestedUrl = (string) preg_replace('/[?#].*$/', '', $requestedUrl); + $options = $requestedUrl === $inputUrl ? $server : []; + + if (!str_starts_with($requestedUrl, ManifestTestProvider::BASE_IRI) || str_contains($requestedUrl, '..')) { + return new MockResponse('', ['http_code' => 404]); + } + + if (\is_string($options['redirectTo'] ?? null)) { + return new MockResponse('', [ + 'http_code' => \is_int($options['httpStatus'] ?? null) ? $options['httpStatus'] : 302, + 'response_headers' => ['Location' => ManifestTestProvider::BASE_IRI . $options['redirectTo']], + ]); + } + + $file = ManifestTestProvider::fixturePath(substr($requestedUrl, \strlen(ManifestTestProvider::BASE_IRI))); + + if (!is_file($file)) { + return new MockResponse('', ['http_code' => 404]); + } + + $headers = [ + 'Content-Type' => \is_string($options['contentType'] ?? null) + ? $options['contentType'] + : self::CONTENT_TYPES[pathinfo($file, \PATHINFO_EXTENSION)] ?? 'application/octet-stream', + ]; + + if (isset($options['httpLink'])) { + $headers['Link'] = array_values(array_filter((array) $options['httpLink'], \is_string(...))); + } + + return new MockResponse((string) file_get_contents($file), ['response_headers' => $headers]); + }); + + return new HttpDocumentLoader(RemoteContextPolicy::allowHosts('w3c.github.io'), $client); + } +} diff --git a/tests/Algorithms/Rdf/ComparatorTest.php b/tests/Algorithms/Rdf/ComparatorTest.php new file mode 100644 index 000000000..dc38699ec --- /dev/null +++ b/tests/Algorithms/Rdf/ComparatorTest.php @@ -0,0 +1,132 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsParser; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * The two comparators the W3C RDF suites are judged with: a comparator that + * says yes too easily would make every one of those tests pass. + */ +#[Group('rdf')] +class ComparatorTest extends TestCase +{ + #[DataProvider('provideDatasets')] + public function testDatasetIsomorphism(string $first, string $second, bool $isomorphic): void + { + $parser = new NQuadsParser(); + + $this->assertSame($isomorphic, RdfDatasetIsomorphism::areIsomorphic($parser->parse($first), $parser->parse($second))); + $this->assertSame($isomorphic, RdfDatasetIsomorphism::areIsomorphic($parser->parse($second), $parser->parse($first))); + } + + /** + * @return iterable + */ + public static function provideDatasets(): iterable + { + yield 'same ground statements in another order' => [ + " \"a\" .\n \"b\" .", + " \"b\" .\n \"a\" .", + true, + ]; + yield 'renamed blank nodes' => [ + "_:a _:b .\n_:b \"leaf\" .", + "_:x _:y .\n_:y \"leaf\" .", + true, + ]; + yield 'a list, relabelled and shuffled' => [ + " _:l1 .\n_:l1 \"a\" .\n_:l1 _:l2 .\n_:l2 \"b\" .\n_:l2 .", + "_:z .\n_:z \"b\" .\n_:y _:z .\n_:y \"a\" .\n _:y .", + true, + ]; + yield 'a cycle of indistinguishable blank nodes' => [ + "_:a _:b .\n_:b _:c .\n_:c _:a .", + "_:x _:z .\n_:z _:y .\n_:y _:x .", + true, + ]; + yield 'language tags compare without case' => [ + ' "a"@en-US .', + ' "a"@en-us .', + true, + ]; + yield 'a different literal' => [ + ' "a" .', + ' "b" .', + false, + ]; + yield 'a different datatype' => [ + ' "1" .', + ' "1"^^ .', + false, + ]; + yield 'a missing statement' => [ + " \"a\" .\n \"b\" .", + ' "a" .', + false, + ]; + yield 'another graph' => [ + ' "a" .', + ' "a" .', + false, + ]; + yield 'a blank node where an IRI is expected' => [ + ' _:b .', + ' .', + false, + ]; + yield 'two blank nodes merged into one' => [ + "_:a \"x\" .\n_:b \"y\" .", + "_:a \"x\" .\n_:a \"y\" .", + false, + ]; + yield 'the same shapes wired differently' => [ + "_:a _:b .\n_:b _:a .\n_:c _:c .", + "_:a _:b .\n_:b _:c .\n_:c _:a .", + false, + ]; + yield 'a list in another order' => [ + " _:l1 .\n_:l1 \"a\" .\n_:l1 _:l2 .\n_:l2 \"b\" .\n_:l2 .", + " _:l1 .\n_:l1 \"b\" .\n_:l1 _:l2 .\n_:l2 \"a\" .\n_:l2 .", + false, + ]; + } + + #[DataProvider('provideDocuments')] + public function testJsonLdEquivalence(string $first, string $second, bool $equivalent): void + { + $this->assertSame($equivalent, JsonLdComparator::areEquivalent(json_decode($first), json_decode($second))); + $this->assertSame($equivalent, JsonLdComparator::areEquivalent(json_decode($second), json_decode($first))); + } + + /** + * @return iterable + */ + public static function provideDocuments(): iterable + { + yield 'keys in another order' => ['[{"@id": "urn:a", "urn:p": [{"@value": 1}]}]', '[{"urn:p": [{"@value": 1}], "@id": "urn:a"}]', true]; + yield 'values in another order' => ['[{"urn:p": [{"@value": 1}, {"@value": 2}]}]', '[{"urn:p": [{"@value": 2}, {"@value": 1}]}]', true]; + yield 'nodes in another order' => ['[{"@id": "urn:a"}, {"@id": "urn:b"}]', '[{"@id": "urn:b"}, {"@id": "urn:a"}]', true]; + yield 'an integer and the same float' => ['[{"@value": 1}]', '[{"@value": 1.0}]', true]; + yield 'a list in the same order' => ['[{"urn:p": [{"@list": [{"@value": 1}, {"@value": 2}]}]}]', '[{"urn:p": [{"@list": [{"@value": 1}, {"@value": 2}]}]}]', true]; + yield 'a list in another order' => ['[{"urn:p": [{"@list": [{"@value": 1}, {"@value": 2}]}]}]', '[{"urn:p": [{"@list": [{"@value": 2}, {"@value": 1}]}]}]', false]; + yield 'a different value' => ['[{"urn:p": [{"@value": 1}]}]', '[{"urn:p": [{"@value": 2}]}]', false]; + yield 'a string and a number' => ['[{"@value": "1"}]', '[{"@value": 1}]', false]; + yield 'a missing entry' => ['[{"@id": "urn:a", "urn:p": []}]', '[{"@id": "urn:a"}]', false]; + yield 'a duplicated value' => ['[{"urn:p": [{"@value": 1}, {"@value": 1}]}]', '[{"urn:p": [{"@value": 1}, {"@value": 2}]}]', false]; + yield 'an object and an array' => ['[{"@value": {}}]', '[{"@value": []}]', false]; + yield 'a missing value' => ['[{"urn:p": [{"@value": 1}, {"@value": 2}]}]', '[{"urn:p": [{"@value": 1}]}]', false]; + } +} diff --git a/tests/Algorithms/Rdf/ConvertersTest.php b/tests/Algorithms/Rdf/ConvertersTest.php new file mode 100644 index 000000000..5255e1235 --- /dev/null +++ b/tests/Algorithms/Rdf/ConvertersTest.php @@ -0,0 +1,171 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\RdfVocabulary; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * What the W3C suites do not ask of the two converters. + */ +#[Group('rdf')] +class ConvertersTest extends TestCase +{ + private const DOCUMENT = <<<'JSON' + { + "@context": {"@vocab": "http://example.com/", "knows": {"@container": "@list"}}, + "@id": "http://example.com/alice", + "@type": "Person", + "name": {"@value": "Alice", "@language": "fr"}, + "age": 42, + "height": 1.72, + "member": true, + "data": {"@type": "@json", "@value": {"b": [], "a": {}}}, + "knows": [{"@id": "http://example.com/bob"}, {"name": "Carole"}] + } + JSON; + + public function testADocumentSurvivesTheRoundTrip(): void + { + $toRdf = new ToRdfConverter(); + $dataset = $toRdf->toRdf(self::DOCUMENT); + + $this->assertCount(12, $dataset); + + $document = (new FromRdfConverter())->fromRdf($dataset, new ProcessorOptions(useNativeTypes: true)); + + $this->assertStringContainsString('"@value": 1.72', $document); + $this->assertTrue(RdfDatasetIsomorphism::areIsomorphic($dataset, $toRdf->toRdf($document))); + } + + public function testTheCallersDocumentAndOptionsAreLeftAlone(): void + { + $document = json_decode(self::DOCUMENT); + $this->assertInstanceOf(\stdClass::class, $document); + $options = new ProcessorOptions(ordered: true); + + (new ToRdfConverter())->toRdf($document, $options); + + $this->assertEquals(json_decode(self::DOCUMENT), $document); + $this->assertTrue($options->ordered); + } + + public function testABlankNodePredicateIsDroppedUnlessAskedFor(): void + { + $document = '{"@id": "http://example.com/s", "_:p": "o"}'; + $converter = new ToRdfConverter(); + + $this->assertCount(0, $converter->toRdf($document)); + $this->assertSame( + " _:b0 \"o\" .\n", + NQuadsSerializer::serialize($converter->toRdf($document, new ProcessorOptions(produceGeneralizedRdf: true))), + ); + } + + public function testTheBaseDirectionIsDroppedUnlessAskedFor(): void + { + $document = '{"@id": "http://example.com/s", "http://example.com/p": {"@value": "שלום", "@language": "he", "@direction": "rtl"}}'; + $converter = new ToRdfConverter(); + + $this->assertSame( + " \"שלום\"@he .\n", + NQuadsSerializer::serialize($converter->toRdf($document)), + ); + $this->assertSame( + " \"שלום\"^^ .\n", + NQuadsSerializer::serialize($converter->toRdf($document, new ProcessorOptions(rdfDirection: RdfVocabulary::RDF_DIRECTION_I18N_DATATYPE))), + ); + $this->assertCount(4, $converter->toRdf($document, new ProcessorOptions(rdfDirection: RdfVocabulary::RDF_DIRECTION_COMPOUND_LITERAL))); + } + + public function testAnUnknownRdfDirectionIsRefused(): void + { + $options = new ProcessorOptions(rdfDirection: 'sideways'); + + try { + (new ToRdfConverter())->toRdf('{}', $options); + $this->fail('toRdf accepted an unknown rdfDirection.'); + } catch (JsonLdException) { + } + + $this->expectException(JsonLdException::class); + + (new FromRdfConverter())->fromRdf('', $options); + } + + public function testFromRdfHandsBackObjectsWhenAsked(): void + { + $document = (new FromRdfConverter())->fromRdf(' "o" .', encodeResult: false); + + $this->assertEquals([(object) ['@id' => 'http://example.com/s', 'http://example.com/p' => [(object) ['@value' => 'o']]]], $document); + } + + public function testFromRdfOrdersTheNodesWhenAsked(): void + { + $nQuads = " \"1\" .\n \"2\" ."; + $converter = new FromRdfConverter(); + + $this->assertSame(['http://example.com/b', 'http://example.com/a'], array_column($converter->fromRdf($nQuads, encodeResult: false), '@id')); + $this->assertSame(['http://example.com/a', 'http://example.com/b'], array_column($converter->fromRdf($nQuads, new ProcessorOptions(ordered: true), false), '@id')); + } + + public function testAnIntegerPhpCannotHoldKeepsItsLexicalForm(): void + { + $document = (new FromRdfConverter())->fromRdf( + <<<'NQUADS' + "123456789012345678901234567890"^^ . + "+007"^^ . + NQUADS, + new ProcessorOptions(useNativeTypes: true), + false, + ); + + $this->assertEquals( + [ + (object) ['@value' => '123456789012345678901234567890', '@type' => RdfVocabulary::XSD_INTEGER], + (object) ['@value' => 7], + ], + $document[0]->{'http://example.com/p'}, + ); + } + + #[DataProvider('provideCompoundLiterals')] + public function testAnIllFormedCompoundLiteralIsRefused(string $nQuads, string $errorCode): void + { + $this->expectExceptionObject(new JsonLdException($errorCode)); + + (new FromRdfConverter())->fromRdf($nQuads, new ProcessorOptions(rdfDirection: RdfVocabulary::RDF_DIRECTION_COMPOUND_LITERAL)); + } + + /** + * @return iterable + */ + public static function provideCompoundLiterals(): iterable + { + $compoundLiteral = <<<'NQUADS' + _:cl . + _:cl "v" . + _:cl "%s" . + _:cl "%s" . + NQUADS; + + yield 'language' => [\sprintf($compoundLiteral, 'not a language', 'rtl'), 'invalid language-tagged string']; + yield 'direction' => [\sprintf($compoundLiteral, 'en', 'sideways'), 'invalid base direction']; + } +} diff --git a/tests/Algorithms/Rdf/JsonLdComparator.php b/tests/Algorithms/Rdf/JsonLdComparator.php new file mode 100644 index 000000000..a0126d5db --- /dev/null +++ b/tests/Algorithms/Rdf/JsonLdComparator.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +/** + * Compares two decoded JSON-LD documents the way the W3C test suite asks a + * fromRdf result to be compared: the order of an array only matters inside a + * list, since an RDF dataset has no order to give to anything else. + */ +final class JsonLdComparator +{ + public static function areEquivalent(mixed $expected, mixed $actual, bool $ordered = false): bool + { + if ($expected instanceof \stdClass && $actual instanceof \stdClass) { + $expectedEntries = get_object_vars($expected); + $actualEntries = get_object_vars($actual); + + if (\count($expectedEntries) !== \count($actualEntries)) { + return false; + } + + foreach ($expectedEntries as $key => $value) { + if (!\array_key_exists($key, $actualEntries) || !self::areEquivalent($value, $actualEntries[$key], '@list' === (string) $key)) { + return false; + } + } + + return true; + } + + if (\is_array($expected) && \is_array($actual)) { + if (\count($expected) !== \count($actual)) { + return false; + } + + $expected = array_values($expected); + $remaining = array_values($actual); + + if ($ordered) { + foreach ($expected as $index => $value) { + if (!self::areEquivalent($value, $remaining[$index])) { + return false; + } + } + + return true; + } + + foreach ($expected as $value) { + foreach ($remaining as $index => $candidate) { + if (self::areEquivalent($value, $candidate)) { + unset($remaining[$index]); + + continue 2; + } + } + + return false; + } + + return true; + } + + if ((\is_int($expected) || \is_float($expected)) && (\is_int($actual) || \is_float($actual))) { + return (float) $expected === (float) $actual; + } + + return $expected === $actual; + } +} diff --git a/tests/Algorithms/Rdf/LexicalFormTest.php b/tests/Algorithms/Rdf/LexicalFormTest.php new file mode 100644 index 000000000..1a149037b --- /dev/null +++ b/tests/Algorithms/Rdf/LexicalFormTest.php @@ -0,0 +1,131 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\CanonicalLexicalForm; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\JsonCanonicalizer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\WellFormedness; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +#[Group('rdf')] +class LexicalFormTest extends TestCase +{ + #[DataProvider('provideDoubles')] + public function testCanonicalDouble(int|float $value, string $expected): void + { + $this->assertSame($expected, CanonicalLexicalForm::double($value)); + } + + /** + * @return iterable + */ + public static function provideDoubles(): iterable + { + yield 'one' => [1, '1.0E0']; + yield 'a fraction' => [5.3, '5.3E0']; + yield 'negative' => [-0.5, '-5.0E-1']; + yield 'large' => [1.0E21, '1.0E21']; + yield 'small' => [0.00000123, '1.23E-6']; + yield 'fifteen digits' => [1.234567890123456, '1.234567890123456E0']; + yield 'zero' => [0.0, '0.0E0']; + yield 'infinity' => [\INF, 'INF']; + yield 'minus infinity' => [-\INF, '-INF']; + yield 'not a number' => [\NAN, 'NaN']; + } + + #[DataProvider('provideIntegers')] + public function testCanonicalInteger(int|float $value, string $expected): void + { + $this->assertSame($expected, CanonicalLexicalForm::integer($value)); + } + + /** + * @return iterable + */ + public static function provideIntegers(): iterable + { + yield 'an integer' => [42, '42']; + yield 'a negative integer' => [-42, '-42']; + yield 'a float without fraction' => [1.0, '1']; + yield 'a float too large for an int' => [1.0E20, '100000000000000000000']; + yield 'minus zero' => [-0.0, '0']; + } + + public function testWhichNumbersAreDoubles(): void + { + $this->assertFalse(CanonicalLexicalForm::isDouble(1)); + $this->assertFalse(CanonicalLexicalForm::isDouble(1.0)); + $this->assertFalse(CanonicalLexicalForm::isDouble(1.0E20)); + $this->assertTrue(CanonicalLexicalForm::isDouble(1.5)); + $this->assertTrue(CanonicalLexicalForm::isDouble(1.0E21)); + $this->assertTrue(CanonicalLexicalForm::isDouble(-1.0E21)); + } + + public function testBooleans(): void + { + $this->assertSame('true', CanonicalLexicalForm::boolean(true)); + $this->assertSame('false', CanonicalLexicalForm::boolean(false)); + } + + #[DataProvider('provideJson')] + public function testJsonCanonicalization(string $json, string $expected): void + { + $this->assertSame($expected, JsonCanonicalizer::canonicalize(json_decode($json))); + } + + /** + * The numbers are the ones of RFC 8785, appendix B. + * + * @return iterable + */ + public static function provideJson(): iterable + { + yield 'literals' => ['[null, true, false]', '[null,true,false]']; + yield 'empty object and array' => ['{"b": [], "a": {}}', '{"a":{},"b":[]}']; + yield 'keys sorted by UTF-16 code units' => ['{"\u20ac": 1, "\r": 2, "\ud83d\ude00": 3, "\ufb33": 4, "1": 5, "\u0080": 6, "\u00f6": 7}', "{\"\\r\":2,\"1\":5,\"\u{80}\":6,\"ö\":7,\"€\":1,\"😀\":3,\"\u{FB33}\":4}"]; + yield 'string escapes' => ['"\u20ac$\u000f\nA\'B\"\\\\\"/"', '"€$\u000f\nA\'B\"\\\\\"/"']; + yield 'nested' => ['{"numbers": [333333333.33333329, 1E30, 4.50, 2e-3, 0.000000000000000000000000001], "literals": [null, true, false]}', '{"literals":[null,true,false],"numbers":[333333333.3333333,1e+30,4.5,0.002,1e-27]}']; + yield 'zero' => ['[0, 0.0, -0.0]', '[0,0,0]']; + yield 'integer valued float' => ['[1.0, 100.0, 1e2]', '[1,100,100]']; + yield 'largest decimal notation' => ['[1e20, 123456789012345680000, 1e21]', '[100000000000000000000,123456789012345680000,1e+21]']; + yield 'smallest decimal notation' => ['[0.000001, 0.0000001]', '[0.000001,1e-7]']; + yield 'extremes' => ['[5e-324, 1.7976931348623157e308, -1.7976931348623157e308]', '[5e-324,1.7976931348623157e+308,-1.7976931348623157e+308]']; + yield 'shortest round trip' => ['[0.1, 0.30000000000000004, 9007199254740992, 295147905179352830000, 9.999999999999997e22]', '[0.1,0.30000000000000004,9007199254740992,295147905179352830000,9.999999999999997e+22]']; + } + + public function testWellFormedIris(): void + { + $this->assertTrue(WellFormedness::isIri('http://example.com/a?b#c')); + $this->assertTrue(WellFormedness::isIri('urn:ex:s')); + $this->assertFalse(WellFormedness::isIri('relative')); + $this->assertFalse(WellFormedness::isIri('http://example.com/a b')); + $this->assertFalse(WellFormedness::isIri('http://example.com/')); + $this->assertFalse(WellFormedness::isIri('http://example.com/#a#b')); + $this->assertFalse(WellFormedness::isIri('_:b0')); + $this->assertFalse(WellFormedness::isIri(null)); + } + + public function testWellFormedBlankNodesAndLanguageTags(): void + { + $this->assertTrue(WellFormedness::isBlankNode('_:b0')); + $this->assertFalse(WellFormedness::isBlankNode('_:b 0')); + $this->assertFalse(WellFormedness::isBlankNode('http://example.com/')); + + $this->assertTrue(WellFormedness::isLanguageTag('en')); + $this->assertTrue(WellFormedness::isLanguageTag('zh-Hant-TW')); + $this->assertFalse(WellFormedness::isLanguageTag('en us')); + $this->assertFalse(WellFormedness::isLanguageTag('a-very-long-subtag-123456789')); + $this->assertFalse(WellFormedness::isLanguageTag('')); + } +} diff --git a/tests/Algorithms/Rdf/NQuadsTest.php b/tests/Algorithms/Rdf/NQuadsTest.php new file mode 100644 index 000000000..4e534d0da --- /dev/null +++ b/tests/Algorithms/Rdf/NQuadsTest.php @@ -0,0 +1,133 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\BlankNode; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\Iri; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\Literal; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsParser; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\Quad; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\RdfDataset; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\RdfVocabulary; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +#[Group('rdf')] +class NQuadsTest extends TestCase +{ + public function testItReadsEveryKindOfTerm(): void + { + $dataset = (new NQuadsParser())->parse(<<<'NQUADS' + # a comment, then an empty line + + . + _:b0 "plain" . # trailing comment + _:b0 "bonjour"@fr-FR . + "1"^^ _:g . + NQUADS); + + $this->assertEquals([ + new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Iri('http://example.com/o')), + new Quad(new BlankNode('_:b0'), new Iri('http://example.com/p'), new Literal('plain')), + new Quad(new BlankNode('_:b0'), new Iri('http://example.com/p'), new Literal('bonjour', RdfVocabulary::RDF_LANG_STRING, 'fr-FR'), new Iri('http://example.com/g')), + new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Literal('1', RdfVocabulary::XSD_INTEGER), new BlankNode('_:g')), + ], $dataset->quads()); + } + + public function testItUnescapesLiteralsAndIris(): void + { + $dataset = (new NQuadsParser())->parse(' "a\tb\nc \"d\" \\\\ \u00E9 \U0001F600" .'); + $quad = $dataset->quads()[0]; + + $this->assertEquals(new Iri('http://example.com/é'), $quad->subject); + $this->assertEquals(new Literal("a\tb\nc \"d\" \\ é 😀"), $quad->object); + } + + public function testItReadsABlankNodeEndingTheStatement(): void + { + $dataset = (new NQuadsParser())->parse('_:a.b _:c.'); + + $this->assertEquals(new BlankNode('_:a.b'), $dataset->quads()[0]->subject); + $this->assertEquals(new BlankNode('_:c'), $dataset->quads()[0]->object); + } + + public function testItReadsABlankNodePredicate(): void + { + $dataset = (new NQuadsParser())->parse('_:s _:p _:o .'); + + $this->assertEquals(new BlankNode('_:p'), $dataset->quads()[0]->predicate); + } + + #[DataProvider('provideInvalidStatements')] + public function testItRefusesWhatIsNotAStatement(string $statement): void + { + $this->expectException(JsonLdException::class); + + (new NQuadsParser())->parse($statement); + } + + /** + * @return iterable + */ + public static function provideInvalidStatements(): iterable + { + yield 'no final dot' => [' ']; + yield 'literal subject' => ['"s" .']; + yield 'literal predicate' => [' "p" .']; + yield 'two terms' => [' .']; + yield 'unterminated literal' => [' "o .']; + yield 'unknown escape' => [' "\q" .']; + yield 'space in an IRI' => [' "o" .']; + } + + public function testItWritesCanonicalStatements(): void + { + $dataset = new RdfDataset([ + new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Literal("line\nbreak \"quoted\" \\ é")), + new Quad(new BlankNode('_:b0'), new Iri('http://example.com/p'), new Literal('bonjour', RdfVocabulary::RDF_LANG_STRING, 'fr'), new Iri('http://example.com/g')), + new Quad(new BlankNode('_:b0'), new Iri('http://example.com/p'), new Literal('1.0E0', RdfVocabulary::XSD_DOUBLE)), + ]); + + $this->assertSame( + <<<'NQUADS' + "line\nbreak \"quoted\" \\ é" . + _:b0 "bonjour"@fr . + _:b0 "1.0E0"^^ . + + NQUADS, + NQuadsSerializer::serialize($dataset), + ); + } + + public function testADatasetIsASet(): void + { + $dataset = new RdfDataset(); + $dataset->add(new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Literal('o'))); + $dataset->add(new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Literal('o'))); + $dataset->add(new Quad(new Iri('http://example.com/s'), new Iri('http://example.com/p'), new Literal('o'), new Iri('http://example.com/g'))); + + $this->assertCount(2, $dataset); + $this->assertCount(2, iterator_to_array($dataset)); + } + + public function testWhatIsWrittenReadsBackTheSame(): void + { + $dataset = new RdfDataset([ + new Quad(new BlankNode('_:b0'), new BlankNode('_:b1'), new Literal("tab\t, feed\f, return\r, quote\", backslash\\"), new BlankNode('_:b2')), + ]); + + $this->assertEquals($dataset->quads(), (new NQuadsParser())->parse(NQuadsSerializer::serialize($dataset))->quads()); + } +} diff --git a/tests/Algorithms/Rdf/RdfDatasetIsomorphism.php b/tests/Algorithms/Rdf/RdfDatasetIsomorphism.php new file mode 100644 index 000000000..151d4bbd8 --- /dev/null +++ b/tests/Algorithms/Rdf/RdfDatasetIsomorphism.php @@ -0,0 +1,235 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms\Rdf; + +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\BlankNode; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\Iri; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\Literal; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\RdfDataset; + +/** + * Tells whether two RDF datasets are the same up to the labels of their blank + * nodes, which is how the W3C test suite asks a toRdf result to be compared. + * + * The blank nodes are first told apart by what surrounds them, then a + * backtracking search looks for a one to one mapping that turns one dataset + * into the other. + * + * @phpstan-type Term array{bool, string} + * @phpstan-type Statement array{Term, Term, Term, Term} + */ +final class RdfDatasetIsomorphism +{ + public static function areIsomorphic(RdfDataset $first, RdfDataset $second): bool + { + $firstStatements = self::statements($first); + $secondStatements = self::statements($second); + + if (\count($firstStatements) !== \count($secondStatements)) { + return false; + } + + $firstColors = self::colors($firstStatements); + $secondColors = self::colors($secondStatements); + + $firstClasses = array_count_values($firstColors); + $secondClasses = array_count_values($secondColors); + ksort($firstClasses); + ksort($secondClasses); + + if ($firstClasses !== $secondClasses) { + return false; + } + + // The rarest colors first: they leave the fewest candidates to try. + $blankNodes = array_keys($firstColors); + usort($blankNodes, static fn (string $a, string $b): int => [$firstClasses[$firstColors[$a]], $a] <=> [$firstClasses[$firstColors[$b]], $b]); + + $target = []; + + foreach ($secondStatements as $statement) { + $target[self::writtenKey($statement)] = true; + } + + return self::search($blankNodes, 0, [], [], $firstColors, $secondColors, $firstStatements, $target); + } + + /** + * @param list $blankNodes + * @param array $mapping + * @param array $used + * @param array $firstColors + * @param array $secondColors + * @param list $statements + * @param array $target + */ + private static function search(array $blankNodes, int $index, array $mapping, array $used, array $firstColors, array $secondColors, array $statements, array $target): bool + { + foreach ($statements as $statement) { + $key = self::key($statement, $mapping); + + if (null !== $key && !\array_key_exists($key, $target)) { + return false; + } + } + + if (!\array_key_exists($index, $blankNodes)) { + return true; + } + + $blankNode = $blankNodes[$index]; + + foreach ($secondColors as $candidate => $color) { + if ($color !== $firstColors[$blankNode] || \array_key_exists($candidate, $used)) { + continue; + } + + if (self::search($blankNodes, $index + 1, $mapping + [$blankNode => $candidate], $used + [$candidate => true], $firstColors, $secondColors, $statements, $target)) { + return true; + } + } + + return false; + } + + /** + * A color per blank node, refined until the blank nodes that can be told + * apart are: it only depends on the shape of the dataset, never on a label. + * + * @param list $statements + * + * @return array + */ + private static function colors(array $statements): array + { + $colors = []; + + foreach ($statements as $statement) { + foreach ($statement as [$isBlankNode, $value]) { + if ($isBlankNode) { + $colors[$value] = ''; + } + } + } + + for ($round = 0; $round <= \count($colors); ++$round) { + $signatures = array_fill_keys(array_keys($colors), []); + + foreach ($statements as $statement) { + foreach ($statement as [$isBlankNode, $value]) { + if (!$isBlankNode) { + continue; + } + + $parts = []; + + foreach ($statement as [$isOtherBlankNode, $other]) { + $parts[] = match (true) { + !$isOtherBlankNode => 'G' . $other, + $other === $value => 'S', + default => 'B' . $colors[$other], + }; + } + + $signatures[$value][] = implode("\x1F", $parts); + } + } + + $refined = []; + + foreach ($signatures as $blankNode => $signature) { + sort($signature); + $refined[(string) $blankNode] = hash('xxh128', implode("\x1E", $signature)); + } + + if (\count(array_unique($refined)) === \count(array_unique($colors))) { + return $refined; + } + + $colors = $refined; + } + + return $colors; + } + + /** + * The identity of a statement once its blank nodes are renamed, or null + * when it holds a blank node the mapping does not cover yet. + * + * @param Statement $statement + * @param array $mapping + */ + private static function key(array $statement, array $mapping): ?string + { + $parts = []; + + foreach ($statement as [$isBlankNode, $value]) { + if (!$isBlankNode) { + $parts[] = 'G' . $value; + + continue; + } + + if (!\array_key_exists($value, $mapping)) { + return null; + } + + $parts[] = 'B' . $mapping[$value]; + } + + return implode("\x1F", $parts); + } + + /** + * The identity of a statement as it is written, blank node labels included. + * + * @param Statement $statement + */ + private static function writtenKey(array $statement): string + { + $parts = []; + + foreach ($statement as [$isBlankNode, $value]) { + $parts[] = ($isBlankNode ? 'B' : 'G') . $value; + } + + return implode("\x1F", $parts); + } + + /** + * @return list + */ + private static function statements(RdfDataset $dataset): array + { + $statements = []; + + foreach ($dataset->quads() as $quad) { + $statements[] = [self::term($quad->subject), self::term($quad->predicate), self::term($quad->object), self::term($quad->graph)]; + } + + return $statements; + } + + /** + * @return Term + */ + private static function term(Iri|BlankNode|Literal|null $term): array + { + return match (true) { + null === $term => [false, ''], + $term instanceof BlankNode => [true, $term->label], + $term instanceof Iri => [false, '<' . $term->value . '>'], + // Language tags are case insensitive. + default => [false, json_encode([$term->value, $term->datatype, null === $term->language ? null : strtolower($term->language)], \JSON_THROW_ON_ERROR)], + }; + } +} diff --git a/tests/Algorithms/RemoteContextPolicyIntegrationTest.php b/tests/Algorithms/RemoteContextPolicyIntegrationTest.php index 45420f8bf..e55148135 100644 --- a/tests/Algorithms/RemoteContextPolicyIntegrationTest.php +++ b/tests/Algorithms/RemoteContextPolicyIntegrationTest.php @@ -86,7 +86,7 @@ public function testExpandAcceptsARemoteContextOnceItsHostIsAllowed(): void { $expander = new Expander(documentLoader: new HttpDocumentLoader( RemoteContextPolicy::allowHosts('evil.example'), - new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}')), + new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}', ['response_headers' => ['Content-Type' => 'application/ld+json']])), )); $expanded = $expander->expand(self::DOCUMENT_WITH_REMOTE_CONTEXT); @@ -115,7 +115,7 @@ public function testTheProcessedContextCacheIsNotSharedAcrossPolicies(): void $permissive = new ContextCache(new HttpDocumentLoader( RemoteContextPolicy::allowHosts('cache-partitioning.example'), - new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}')), + new MockHttpClient(new MockResponse('{"@context":{"name":"https://schema.org/name"}}', ['response_headers' => ['Content-Type' => 'application/ld+json']])), )); $remoteContexts = [$url]; diff --git a/tests/Algorithms/RemoteDocTest.php b/tests/Algorithms/RemoteDocTest.php new file mode 100644 index 000000000..279af6232 --- /dev/null +++ b/tests/Algorithms/RemoteDocTest.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms; + +use JoliCode\StructuredData\JsonLd\Algorithms; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\Tests\Algorithms\Manifest\AbstractRemoteDocumentTestCase; +use JoliCode\StructuredData\Tests\Algorithms\Manifest\ManifestTestProvider; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; + +/** + * @see https://w3c.github.io/json-ld-api/tests/remote-doc-manifest.html + */ +#[Group('remote-doc')] +class RemoteDocTest extends AbstractRemoteDocumentTestCase +{ + /** + * @param array $server + */ + #[DataProvider('provideManifestEntries')] + public function testRemoteDoc(string $algorithm, string $url, ?string $context, ?string $expect, ?string $errorCode, ProcessorOptions $options, array $server): void + { + $this->runManifestEntry($algorithm, $url, $context, $expect, $errorCode, $options, $server); + } + + /** + * @return iterable}> + */ + public static function provideManifestEntries(): iterable + { + return ManifestTestProvider::provideDocuments(Algorithms::REMOTE_DOC_SUITE); + } +} diff --git a/tests/Algorithms/ToRdfTest.php b/tests/Algorithms/ToRdfTest.php new file mode 100644 index 000000000..aecaca9e1 --- /dev/null +++ b/tests/Algorithms/ToRdfTest.php @@ -0,0 +1,73 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Algorithms; + +use JoliCode\StructuredData\JsonLd\Algorithms; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsParser; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; +use JoliCode\StructuredData\Tests\Algorithms\Manifest\ManifestTestProvider; +use JoliCode\StructuredData\Tests\Algorithms\Manifest\W3cFixtureServer; +use JoliCode\StructuredData\Tests\Algorithms\Rdf\RdfDatasetIsomorphism; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * @see https://w3c.github.io/json-ld-api/tests/toRdf-manifest.html + */ +#[Group('toRdf')] +class ToRdfTest extends TestCase +{ + #[DataProvider('provideManifestEntries')] + public function testToRdf(string $input, ?string $expect, ?string $errorCode, ProcessorOptions $options): void + { + $converter = new ToRdfConverter(documentLoader: W3cFixtureServer::documentLoader()); + + if (null !== $errorCode) { + try { + $converter->toRdf($input, $options); + } catch (JsonLdException $exception) { + $this->assertSame($errorCode, $exception->getMessage()); + + return; + } + + $this->fail(\sprintf('An exception was expected for this test but none were thrown. Expected error message was : %s', $errorCode)); + } + + $dataset = $converter->toRdf($input, $options); + $parser = new NQuadsParser(); + $serialized = NQuadsSerializer::serialize($dataset); + + // What is written must read back as the same dataset, and this is all a + // syntax test asks for. + $this->assertTrue(RdfDatasetIsomorphism::areIsomorphic($dataset, $parser->parse($serialized)), 'The dataset does not survive its own serialization.'); + + if (null !== $expect) { + $this->assertTrue( + RdfDatasetIsomorphism::areIsomorphic($parser->parse($expect), $dataset), + \sprintf("The datasets are not isomorphic.\nExpected:\n%s\nActual:\n%s", $expect, $serialized), + ); + } + } + + /** + * @return iterable + */ + public static function provideManifestEntries(): iterable + { + return ManifestTestProvider::provide(Algorithms::TO_RDF->value); + } +} diff --git a/tests/Validation/AuditTest.php b/tests/Validation/AuditTest.php new file mode 100644 index 000000000..99f6c36b4 --- /dev/null +++ b/tests/Validation/AuditTest.php @@ -0,0 +1,217 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Validation; + +use JoliCode\StructuredData\Audit\Audit; +use JoliCode\StructuredData\Audit\AuditOptions; +use JoliCode\StructuredData\Mapper\MappedError; +use JoliCode\StructuredData\Mapper\MappedProperty; +use JoliCode\StructuredData\Mapper\MappedType; +use JoliCode\StructuredData\Mapper\MappedTypeMerger; +use JoliCode\StructuredData\Vocabularies\Validators\Google\GoogleValidator; +use JoliCode\StructuredData\Vocabularies\Validators\SchemaOrg\SchemaOrgValidator; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +#[Group('validation')] +class AuditTest extends TestCase +{ + public function testWithoutOptionsTheDiagnosticIsTheListOfEveryFormattedMessage(): void + { + $this->assertSame( + [ + '[Google error] Recipe: google error', + '[Google warning] Recipe: google warning', + '[SchemaOrg warning] Recipe: schema.org warning', + '[Merge warning] Recipe: merge warning', + '[Document error] document error', + ], + $this->createAudit()->getDiagnostic(), + ); + } + + /** + * @param list $expectedMessages + */ + #[DataProvider('provideFilters')] + public function testTheDiagnosticIsFilteredBySeverityOrValidator(AuditOptions $options, array $expectedMessages): void + { + $errors = $this->createAudit()->getDiagnostic($options); + + $this->assertIsArray($errors); + $this->assertSame($expectedMessages, array_map( + static fn (mixed $error): string => $error instanceof MappedError ? $error->getMessage() : '', + $errors, + )); + } + + /** + * @return iterable}> + */ + public static function provideFilters(): iterable + { + yield 'errors' => [ + new AuditOptions(severity: AuditOptions::SEVERITY_ERROR, asObject: true), + ['google error', 'document error'], + ]; + yield 'warnings' => [ + new AuditOptions(severity: AuditOptions::SEVERITY_WARNING, asObject: true), + ['google warning', 'schema.org warning', 'merge warning'], + ]; + yield 'document severity' => [ + new AuditOptions(severity: AuditOptions::SEVERITY_DOCUMENT, asObject: true), + ['document error'], + ]; + yield 'google' => [ + new AuditOptions(validator: AuditOptions::VALIDATOR_GOOGLE, asObject: true), + ['google error', 'google warning'], + ]; + yield 'schema.org' => [ + new AuditOptions(validator: AuditOptions::VALIDATOR_SCHEMA_ORG, asObject: true), + ['schema.org warning'], + ]; + yield 'document validator' => [ + new AuditOptions(validator: AuditOptions::VALIDATOR_DOCUMENT, asObject: true), + ['document error'], + ]; + yield 'merge' => [ + new AuditOptions(validator: AuditOptions::VALIDATOR_MERGE, asObject: true), + ['merge warning'], + ]; + } + + public function testTheMessagesAreGroupedByValidator(): void + { + $this->assertSame( + [ + 'Google' => ['[Google error] Recipe: google error', '[Google warning] Recipe: google warning'], + 'SchemaOrg' => ['[SchemaOrg warning] Recipe: schema.org warning'], + 'Merge' => ['[Merge warning] Recipe: merge warning'], + 'Document' => ['[Document error] document error'], + ], + $this->createAudit()->getDiagnostic(new AuditOptions(groupBy: AuditOptions::GROUP_BY_VALIDATOR)), + ); + } + + public function testTheErrorObjectsAreGroupedBySeverity(): void + { + $groups = $this->createAudit()->getDiagnostic(new AuditOptions(groupBy: AuditOptions::GROUP_BY_SEVERITY, asObject: true)); + + $this->assertIsArray($groups); + $this->assertSame(['error', 'warning'], array_keys($groups)); + $this->assertIsArray($groups['error']); + $this->assertIsArray($groups['warning']); + $this->assertContainsOnlyInstancesOf(MappedError::class, $groups['error']); + $this->assertCount(2, $groups['error']); + $this->assertCount(3, $groups['warning']); + } + + public function testTheDiagnosticCanBeEncodedAsJson(): void + { + $json = $this->createAudit()->getDiagnostic(new AuditOptions( + validator: AuditOptions::VALIDATOR_SCHEMA_ORG, + asObject: true, + jsonEncode: true, + )); + + $this->assertIsString($json); + $this->assertSame( + [ + [ + 'message' => 'schema.org warning', + 'property' => 'name', + 'type' => 'Recipe', + 'severity' => 'warning', + 'validatorName' => 'SchemaOrg', + 'ranges' => '1:2 to 1:8', + 'path' => 'Recipe', + 'documentationLink' => 'https://schema.org/Recipe', + ], + ], + json_decode($json, true, flags: \JSON_THROW_ON_ERROR), + ); + } + + public function testAnUnknownSeverityIsRefused(): void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid severity query option provided: fatal'); + + $this->createAudit()->getDiagnostic(new AuditOptions(severity: 'fatal')); + } + + public function testAnUnknownValidatorIsRefused(): void + { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid validator query option provided: bing'); + + $this->createAudit()->getDiagnostic(new AuditOptions(validator: 'bing')); + } + + public function testAWarningKeepsTheAuditValidButNotFullyValid(): void + { + $type = new MappedType(sourceFormat: 'json-ld', type: 'Recipe'); + $audit = new Audit([$type]); + + $this->assertTrue($audit->isValid()); + $this->assertTrue($audit->isFullyValid()); + + $type->addError($this->error('only a warning', MappedError::SEVERITY_WARNING, GoogleValidator::VALIDATOR_NAME, $type)); + $audit = new Audit([$type]); + + $this->assertTrue($audit->isValid()); + $this->assertFalse($audit->isFullyValid()); + + $this->assertFalse($this->createAudit()->isValid()); + $this->assertFalse($this->createAudit()->isFullyValid()); + } + + public function testThePathOfAnErrorFallsBackFromItsParentToItsPropertyThenItsType(): void + { + $type = new MappedType(sourceFormat: 'json-ld', type: 'Recipe'); + $property = new MappedProperty('name', $type); + + $onProperty = new MappedError('message', 'name', 'Recipe', MappedError::SEVERITY_ERROR, 'Google', '', $property); + + $this->assertSame($property, $onProperty->getParent()); + $this->assertSame($property->getPath(), $onProperty->getPath()); + $this->assertSame('name', (new MappedError('message', 'name', 'Recipe', MappedError::SEVERITY_ERROR, 'Google', ''))->getPath()); + $this->assertSame('Recipe', (new MappedError('message', null, 'Recipe', MappedError::SEVERITY_ERROR, 'Google', ''))->getPath()); + $this->assertSame('', (new MappedError('message', null, null, MappedError::SEVERITY_ERROR, 'Google', ''))->getPath()); + } + + private function createAudit(): Audit + { + $type = new MappedType(sourceFormat: 'json-ld', type: 'Recipe'); + $type->addError($this->error('google error', MappedError::SEVERITY_ERROR, GoogleValidator::VALIDATOR_NAME, $type)); + $type->addError($this->error('google warning', MappedError::SEVERITY_WARNING, GoogleValidator::VALIDATOR_NAME, $type)); + $type->addError($this->error('schema.org warning', MappedError::SEVERITY_WARNING, SchemaOrgValidator::VALIDATOR_NAME, $type)); + $type->addError($this->error('merge warning', MappedError::SEVERITY_WARNING, MappedTypeMerger::VALIDATOR_NAME, $type)); + + return new Audit([$type], [$this->error('document error', MappedError::SEVERITY_ERROR, 'Document')]); + } + + private function error(string $message, string $severity, string $validatorName, ?MappedType $parent = null): MappedError + { + return new MappedError( + message: $message, + property: $parent ? 'name' : null, + type: $parent ? 'Recipe' : null, + severity: $severity, + validatorName: $validatorName, + ranges: '1:2 to 1:8', + parent: $parent, + documentationLink: 'https://schema.org/Recipe', + ); + } +} diff --git a/tests/Validation/ExtractorTest.php b/tests/Validation/ExtractorTest.php index 41b65d2d2..d93e7cba1 100644 --- a/tests/Validation/ExtractorTest.php +++ b/tests/Validation/ExtractorTest.php @@ -11,6 +11,7 @@ namespace JoliCode\StructuredData\Tests\Validation; +use JoliCode\StructuredData\Extraction\ExtractionException; use JoliCode\StructuredData\Extraction\Extractor; use JoliCode\StructuredData\Extraction\ExtractorsContainer; use PHPUnit\Framework\Attributes\DataProvider; @@ -313,4 +314,101 @@ public function testItSurfacesAGenericExceptionWhenNoSupportedFormatIsDetected() $extractor->extract('

Hello world

'); } + + public function testItReadsMicrodataAsUtf8WhenThePageDeclaresNoEncoding(): void + { + $document = <<<'HTML' + + +
+ Zoé Müller 日本 +
+ + +HTML; + + $elements = (new Extractor())->extract($document); + + $this->assertCount(1, $elements); + $this->assertStringContainsString('"name":' . json_encode('Zoé Müller 日本'), $elements[0]->content); + } + + public function testItReadsRdfaAsUtf8WhenThePageDeclaresNoEncoding(): void + { + $document = <<<'HTML' + + +
+ Zoé Müller 日本 +
+ + +HTML; + + $elements = (new Extractor())->extract($document); + + $this->assertCount(1, $elements); + $this->assertStringContainsString('"name":' . json_encode('Zoé Müller 日本'), $elements[0]->content); + } + + public function testItHonoursTheEncodingThePageDeclares(): void + { + $document = mb_convert_encoding(<<<'HTML' + + + +
+ Zoé Müller +
+ + +HTML, 'ISO-8859-1', 'UTF-8'); + + $elements = (new Extractor())->extract($document); + + $this->assertCount(1, $elements); + $this->assertStringContainsString('"name":' . json_encode('Zoé Müller'), $elements[0]->content); + } + + public function testAnElementIsLocatedOnTheLineItsStartTagOpensOn(): void + { + $document = <<<'HTML' + + + +
+ Jane Doe +
+ + +HTML; + + $elements = (new Extractor())->extract($document); + + $this->assertCount(1, $elements); + // Lines of a JsonLdElement are counted from 0: the tag opens on the fourth line. + $this->assertSame(3, $elements[0]->startLine); + } + + public function testAMicrodataErrorPointsAtTheLineTheStartTagOpensOn(): void + { + $document = <<<'HTML' + + + + Jane Doe + + +HTML; + + $this->expectException(ExtractionException::class); + $this->expectExceptionMessage('no itemscope attribute at line 4.'); + + (new Extractor())->setExtractors(ExtractorsContainer::MICRODATA)->extract($document); + } } diff --git a/tests/Validation/Google/GoogleValidatorInfrastructureTest.php b/tests/Validation/Google/GoogleValidatorInfrastructureTest.php index c356383b1..26e5ec3ee 100644 --- a/tests/Validation/Google/GoogleValidatorInfrastructureTest.php +++ b/tests/Validation/Google/GoogleValidatorInfrastructureTest.php @@ -17,13 +17,10 @@ use JoliCode\StructuredData\Vocabularies\Validators\Google\GoogleValidator; use JoliCode\StructuredData\Vocabularies\Validators\Google\SpecialRules\SpecialRulesRegistry; use JoliCode\StructuredData\Vocabularies\Validators\Google\Stack; -use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\TestCase; -#[CoversClass(Stack::class)] -#[CoversClass(SpecialRulesRegistry::class)] #[Group('validation')] #[Group('google')] class GoogleValidatorInfrastructureTest extends TestCase diff --git a/tests/Validation/Google/GoogleValidatorTest.php b/tests/Validation/Google/GoogleValidatorTest.php index 26566ff21..575d73288 100644 --- a/tests/Validation/Google/GoogleValidatorTest.php +++ b/tests/Validation/Google/GoogleValidatorTest.php @@ -13,16 +13,12 @@ use JoliCode\StructuredData\Audit\AuditOptions; use JoliCode\StructuredData\Mapper\MappedError; -use JoliCode\StructuredData\Validator; use JoliCode\StructuredData\Vocabularies\Generated\Google\BookWork; use JoliCode\StructuredData\Vocabularies\Generated\Google\NewsArticle; use JoliCode\StructuredData\Vocabularies\Validators\Google\GoogleValidator; -use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; -#[CoversClass(Validator::class)] -#[CoversClass(GoogleValidator::class)] #[Group('validation')] #[Group('google')] class GoogleValidatorTest extends AbstractValidatorTestCase diff --git a/tests/Validation/JsonLdParserTest.php b/tests/Validation/JsonLdParserTest.php new file mode 100644 index 000000000..eb699668a --- /dev/null +++ b/tests/Validation/JsonLdParserTest.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace JoliCode\StructuredData\Tests\Validation; + +use JoliCode\StructuredData\Extraction\ExtractorFormat; +use JoliCode\StructuredData\Extraction\JsonLdElement; +use JoliCode\StructuredData\JsonLd\Parser\DataStructures\AbstractStructure; +use JoliCode\StructuredData\JsonLd\Parser\DataStructures\ArrayStructure; +use JoliCode\StructuredData\JsonLd\Parser\DataStructures\ObjectStructure; +use JoliCode\StructuredData\JsonLd\Parser\JsonLdParser; +use JsonStreamingParser\Exception\ParsingException; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\TestCase; + +/** + * Documents json_decode() refuses go through the streaming parser, which either + * reports where the document breaks or builds what it could read of it. + */ +#[Group('validation')] +class JsonLdParserTest extends TestCase +{ + public function testAMalformedDocumentReportsWhereItBreaks(): void + { + $this->expectException(ParsingException::class); + $this->expectExceptionMessage('Parsing error in [4:3]. Start of string expected for object key. Instead got: o'); + + $this->parse("{\n \"a\": {\"b\": 1},\n \"c\": [1, [2]],\n oops\n}"); + } + + public function testADocumentWithATrailingCommaIsStillRead(): void + { + $structure = $this->parse("{\n \"a\": {\"b\": 1},\n \"c\": [1, [2]],\n}"); + + $this->assertInstanceOf(ObjectStructure::class, $structure); + $this->assertTrue($structure->hasProperty('a')); + $this->assertTrue($structure->hasProperty('c')); + + $nested = $structure->getProperty('a')->value?->content; + $this->assertInstanceOf(ObjectStructure::class, $nested); + $this->assertTrue($nested->hasProperty('b')); + + $list = $structure->getProperty('c')->value?->content; + $this->assertInstanceOf(ArrayStructure::class, $list); + $this->assertCount(2, $list->getValues()); + $this->assertInstanceOf(ArrayStructure::class, $list->getValue(1)->content); + + // The positions are the ones the well-formed document gets from the fast parser. + $wellFormed = $this->parse("{\n \"a\": {\"b\": 1},\n \"c\": [1, [2]]\n}"); + $this->assertInstanceOf(ObjectStructure::class, $wellFormed); + + $this->assertSame('11:5 to 14:2', $this->range($structure)); + $this->assertSame('12:8 to 12:16', $this->range($nested)); + $this->assertSame('13:8 to 13:16', $this->range($list)); + $this->assertSame($this->range($wellFormed), $this->range($structure)); + $this->assertSame($this->range($wellFormed->getProperty('a')->value?->content), $this->range($nested)); + $this->assertSame($this->range($wellFormed->getProperty('c')->value?->content), $this->range($list)); + } + + private function range(mixed $structure): string + { + $this->assertInstanceOf(AbstractStructure::class, $structure); + + return $structure->range?->start . ' to ' . $structure->range?->end; + } + + private function parse(string $content): mixed + { + return (new JsonLdParser())->parse(new JsonLdElement(10, 4, $content, ExtractorFormat::JSONLD)); + } +} diff --git a/tests/Validation/SchemaOrg/SchemaOrgValidatorInfrastructureTest.php b/tests/Validation/SchemaOrg/SchemaOrgValidatorInfrastructureTest.php index a735eb920..a5b85c9d0 100644 --- a/tests/Validation/SchemaOrg/SchemaOrgValidatorInfrastructureTest.php +++ b/tests/Validation/SchemaOrg/SchemaOrgValidatorInfrastructureTest.php @@ -15,11 +15,9 @@ use JoliCode\StructuredData\Validator; use JoliCode\StructuredData\Vocabularies\Validators\SchemaOrg\SchemaOrgValidator; use JoliCode\StructuredData\Vocabularies\Validators\SchemaOrg\TypeGuesser; -use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\TestCase; -#[CoversClass(SchemaOrgValidator::class)] #[Group('validation')] #[Group('schemaorg')] #[Group('schema-org')] diff --git a/tests/Validation/SchemaOrg/SchemaOrgValidatorTest.php b/tests/Validation/SchemaOrg/SchemaOrgValidatorTest.php index 41e1a5c6c..9a73d512f 100644 --- a/tests/Validation/SchemaOrg/SchemaOrgValidatorTest.php +++ b/tests/Validation/SchemaOrg/SchemaOrgValidatorTest.php @@ -12,14 +12,10 @@ namespace JoliCode\StructuredData\Tests\Validation; use JoliCode\StructuredData\Audit\AuditOptions; -use JoliCode\StructuredData\Validator; use JoliCode\StructuredData\Vocabularies\Validators\SchemaOrg\SchemaOrgValidator; -use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\Attributes\Group; -#[CoversClass(Validator::class)] -#[CoversClass(SchemaOrgValidator::class)] #[Group('validation')] #[Group('schemaorg')] #[Group('schema-org')] diff --git a/tests/Validation/SnapshotDocumentLoader.php b/tests/Validation/SnapshotDocumentLoader.php index 4d6774c0b..8edafa372 100644 --- a/tests/Validation/SnapshotDocumentLoader.php +++ b/tests/Validation/SnapshotDocumentLoader.php @@ -12,6 +12,8 @@ namespace JoliCode\StructuredData\Tests\Validation; use JoliCode\StructuredData\JsonLd\Algorithms\Http\DocumentLoaderInterface; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\LoadDocumentOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Http\RemoteDocument; /** * Serves the remote contexts the validation fixtures reference from snapshots @@ -64,7 +66,7 @@ final class SnapshotDocumentLoader implements DocumentLoaderInterface */ private array $documents = []; - public function load(string $url): \stdClass + public function load(string $url, LoadDocumentOptions $options = new LoadDocumentOptions()): RemoteDocument { if (!\array_key_exists($url, self::SNAPSHOTS)) { // Not a ContextProcessingException, and not a RuntimeException either: @@ -74,7 +76,7 @@ public function load(string $url): \stdClass throw new \LogicException(\sprintf('The validation suite runs offline, and no snapshot is registered for the remote context "%s". Download it into "%s" and register it in %s::SNAPSHOTS.', $url, self::SNAPSHOTS_DIRECTORY, self::class)); } - return $this->documents[$url] ??= $this->decode(self::SNAPSHOTS[$url]); + return new RemoteDocument($this->documents[$url] ??= $this->decode(self::SNAPSHOTS[$url]), $url); } public function getCacheNamespace(): string