Skip to content

Commit

Permalink
fix: decoder undefined json bug (#210)
Browse files Browse the repository at this point in the history
When the stringified json contains a undefined or NaN value we need to replace it by null to allow for json.parse to work.
Previously we used a simple replace. Now its a regex that only replaces unquoted instances of undefined & NaN.
  • Loading branch information
dstallenberg committed Dec 11, 2023
1 parent 4daf7b2 commit f3cd2e7
Showing 1 changed file with 14 additions and 5 deletions.
19 changes: 14 additions & 5 deletions libraries/search-javascript/lib/testbuilding/JavaScriptDecoder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
*/

import { ImplementationError } from "@syntest/diagnostics";
import { getLogger, Logger } from "@syntest/logging";
import { Decoder } from "@syntest/search";

import { JavaScriptTestCase } from "../testcase/JavaScriptTestCase";
Expand All @@ -30,9 +31,11 @@ import { assertionFunction } from "./assertionFunctionTemplate";
import { ContextBuilder } from "./ContextBuilder";

export class JavaScriptDecoder implements Decoder<JavaScriptTestCase, string> {
protected static LOGGER: Logger;
private targetRootDirectory: string;

constructor(targetRootDirectory: string) {
JavaScriptDecoder.LOGGER = getLogger(JavaScriptDecoder.name);
this.targetRootDirectory = targetRootDirectory;
}

Expand Down Expand Up @@ -76,9 +79,10 @@ export class JavaScriptDecoder implements Decoder<JavaScriptTestCase, string> {
}

if (decodings.length === 0) {
throw new ImplementationError(
JavaScriptDecoder.LOGGER.warn(
"No statements in test case after error reduction"
);
continue;
}

const metaCommentBlock = this.generateMetaComments(testCase);
Expand Down Expand Up @@ -230,10 +234,15 @@ export class JavaScriptDecoder implements Decoder<JavaScriptTestCase, string> {
continue;
}

// TODO dirty hack because json.parse does not allow undefined/NaN
// TODO undefined/NaN can happen in arrays
stringified = stringified.replace("undefined", "null");
stringified = stringified.replace("NaN", "null");
// Dirty hack because json.parse does not allow undefined/NaN
stringified = stringified.replaceAll(
/undefined(?=[^"]*(?:"[^"]*"[^"]*)*$)/g,
"null"
);
stringified = stringified.replaceAll(
/NaN(?=[^"]*(?:"[^"]*"[^"]*)*$)/g,
"null"
);

// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const value = JSON.parse(stringified);
Expand Down

0 comments on commit f3cd2e7

Please sign in to comment.