fix(yaml): handle Boolean instances correctly (#5894)

This commit is contained in:
Tim Reichen 2024-09-03 13:15:31 +02:00 committed by GitHub
parent 5bed4c81b5
commit 890958ca48
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 51 additions and 12 deletions

View File

@ -18,8 +18,20 @@ export const bool: Type<"scalar", boolean> = {
construct: (data: string): boolean => YAML_TRUE_BOOLEANS.includes(data),
resolve: (data: string): boolean => YAML_BOOLEANS.includes(data),
represent: {
lowercase: (object: boolean): string => object ? "true" : "false",
uppercase: (object: boolean): string => object ? "TRUE" : "FALSE",
camelcase: (object: boolean): string => object ? "True" : "False",
// deno-lint-ignore ban-types
lowercase: (object: boolean | Boolean): string => {
const value = object instanceof Boolean ? object.valueOf() : object;
return value ? "true" : "false";
},
// deno-lint-ignore ban-types
uppercase: (object: boolean | Boolean): string => {
const value = object instanceof Boolean ? object.valueOf() : object;
return value ? "TRUE" : "FALSE";
},
// deno-lint-ignore ban-types
camelcase: (object: boolean | Boolean): string => {
const value = object instanceof Boolean ? object.valueOf() : object;
return value ? "True" : "False";
},
},
};

View File

@ -135,22 +135,49 @@ Deno.test({
});
Deno.test({
name: "stringify() serializes boolean values",
name: "stringify() handles boolean values",
fn() {
assertEquals(stringify([true, false]), "- true\n- false\n");
assertEquals(stringify(true), "true\n");
assertEquals(stringify(false), "false\n");
// casing can be controlled with styles options
assertEquals(stringify(new Boolean(true)), "true\n");
assertEquals(stringify(new Boolean(false)), "false\n");
},
});
Deno.test({
name: "stringify() handles boolean with styles option",
fn() {
assertEquals(
stringify([true, false], { styles: { "!!bool": "camelcase" } }),
"- True\n- False\n",
stringify(true, { styles: { "!!bool": "camelcase" } }),
"True\n",
);
assertEquals(
stringify([true, false], { styles: { "!!bool": "uppercase" } }),
"- TRUE\n- FALSE\n",
stringify(false, { styles: { "!!bool": "camelcase" } }),
"False\n",
);
assertEquals(
stringify(new Boolean(true), { styles: { "!!bool": "camelcase" } }),
"True\n",
);
assertEquals(
stringify(true, { styles: { "!!bool": "uppercase" } }),
"TRUE\n",
);
assertEquals(
stringify(false, { styles: { "!!bool": "uppercase" } }),
"FALSE\n",
);
assertEquals(
stringify(new Boolean(true), { styles: { "!!bool": "uppercase" } }),
"TRUE\n",
);
assertThrows(
() => stringify([true, false], { styles: { "!!bool": "octal" } }),
() => stringify(true, { styles: { "!!bool": "octal" } }),
TypeError,
'!<tag:yaml.org,2002:bool> tag resolver accepts not "octal" style',
);
assertThrows(
() => stringify(false, { styles: { "!!bool": "octal" } }),
TypeError,
'!<tag:yaml.org,2002:bool> tag resolver accepts not "octal" style',
);