-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonSuiteTest.php
More file actions
83 lines (68 loc) · 2.93 KB
/
Copy pathJsonSuiteTest.php
File metadata and controls
83 lines (68 loc) · 2.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
declare(strict_types=1);
namespace Mbolli\Ron\Tests;
use Mbolli\Ron\Ron;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
/**
* Round-trips every accepted document from the external JSON conformance corpus
* (nst/JSONTestSuite) to prove RON conversion and encode/decode are lossless over
* a broad, independent set of valid JSON.
*/
final class JsonSuiteTest extends TestCase {
use ComparesJson;
private const DIR = __DIR__ . '/corpus/json';
#[DataProvider('provideValidJsonRoundTripsCases')]
public function testValidJsonRoundTrips(string $path): void {
$raw = (string) file_get_contents($path);
$expected = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
// JSON -> RON -> JSON preserves the value exactly (number text is preserved).
$roundTripped = json_decode(Ron::toJson(Ron::fromJson($raw)), true, 512, JSON_THROW_ON_ERROR);
self::assertSameJsonValue($expected, $roundTripped);
// PHP value -> RON -> PHP value. Numbers are compared numerically (RON, like
// JSON, has a single number type, so whole-valued floats may come back as ints).
// Skipped when json_decode produced a non-finite float, which encode rejects.
if (!self::hasNonFinite($expected)) {
$back = Ron::decode(Ron::encode($expected));
self::assertTrue(self::valuesMatch($expected, $back), 'encode/decode round-trip mismatch');
}
}
/** @return iterable<string, array{0: string}> */
public static function provideValidJsonRoundTripsCases(): iterable {
$files = glob(self::DIR . '/test_parsing/y_*.json');
self::assertNotEmpty($files, 'JSON corpus submodule missing; run: composer install');
foreach ($files as $path) {
yield basename($path) => [$path];
}
}
private static function hasNonFinite(mixed $value): bool {
if (\is_array($value)) {
foreach ($value as $item) {
if (self::hasNonFinite($item)) {
return true;
}
}
return false;
}
return \is_float($value) && !is_finite($value);
}
private static function valuesMatch(mixed $a, mixed $b): bool {
if (\is_array($a) && \is_array($b)) {
if (\count($a) !== \count($b)) {
return false;
}
foreach ($a as $key => $value) {
if (!\array_key_exists($key, $b) || !self::valuesMatch($value, $b[$key])) {
return false;
}
}
return true;
}
if ((\is_int($a) || \is_float($a)) && (\is_int($b) || \is_float($b))) {
// Numeric equality: RON/JSON have one number type, so 1 and 1.0 are equal.
// Spaceship compares numerically and is not rewritten by the strict-comparison fixer.
return ($a <=> $b) === 0;
}
return $a === $b;
}
}