-
Notifications
You must be signed in to change notification settings - Fork 576
/
test.ts
59 lines (53 loc) · 1.72 KB
/
test.ts
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
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
import * as JSONC from "../../../jsonc.ts";
import { assertEquals } from "../../../../testing/asserts.ts";
import { walk } from "../../../../fs/mod.ts";
import { fromFileUrl } from "../../../../path/mod.ts";
function getError<T>(
fn: () => T,
): [hasError: boolean, error: unknown, result?: T] {
try {
const res = fn();
return [false, null, res];
} catch (error: unknown) {
return [true, error];
}
}
// Exclude these test cases as they are correctly parsed as JSONC.
const ignoreFile = new Set([
"n_object_trailing_comment.json",
"n_object_trailing_comment_slash_open.json",
"n_structure_object_with_comment.json",
]);
// Make sure that the JSON.parse and JSONC.parse results match.
for await (
const dirEntry of walk(fromFileUrl(new URL("./", import.meta.url)))
) {
if (!dirEntry.isFile) {
continue;
}
if (ignoreFile.has(dirEntry.name)) {
continue;
}
// Register a test case for each file.
Deno.test({
name: `[jsonc] parse JSONTestSuite:${dirEntry.name}`,
async fn() {
const text = await Deno.readTextFile(dirEntry.path);
const [hasJsonError, jsonError, jsonResult] = getError(() => {
JSON.parse(text);
});
const [hasJsoncError, jsoncError, jsoncResult] = getError(() => {
JSONC.parse(text, { allowTrailingComma: false });
});
// If an error occurs in JSON.parse() but no error occurs in JSONC.parse(), or vice versa, an error is thrown.
if (hasJsonError !== hasJsoncError) {
throw new AggregateError(
[jsonError, jsoncError],
`failed to parse: '${text}'`,
);
}
assertEquals(jsonResult, jsoncResult);
},
});
}