From 19b6e58700902179cb513e761a676cd42f8a84ae Mon Sep 17 00:00:00 2001 From: Matheus Nogueira Date: Mon, 15 Jul 2024 19:24:15 -0300 Subject: [PATCH] fix: escape quotes in assertion field (#3934) * fix: escape quotes in assertion field * fix * fix --- web/src/services/Assertion.service.ts | 25 +++++++++++++++++-- .../__tests__/Assertion.service.test.ts | 13 ++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/web/src/services/Assertion.service.ts b/web/src/services/Assertion.service.ts index acec18d9a8..a5bc923e6a 100644 --- a/web/src/services/Assertion.service.ts +++ b/web/src/services/Assertion.service.ts @@ -18,7 +18,7 @@ const AssertionService = () => ({ if (!input) return input; const formatted = input.trim(); - if (isJson(input)) return `'${input}'`; + if (isJson(input)) return `'${this.escapeString(input, `'`)}'`; if (Object.values(Attributes).includes(formatted)) return formatted; if (Object.values(Attributes).some(aa => formatted.includes(aa))) return formatted; @@ -29,7 +29,28 @@ const AssertionService = () => ({ return isQuoted ? formatted : this.quotedString(formatted); }, quotedString(str: string): string { - return `\"${str}\"`; + return `\"${this.escapeString(str, `"`)}\"`; + }, + escapeString(str: string, quoteCharacter: string): string { + // Couldn't find a regex to solve this problem :( + // Feel free to refactor this if you know how to escape quotes without + // double escaping already escaped quotes. + // + // Examples: + // ' ==> \\' + // \\' ==> \\' + let newString = ''; + let lastCharacter = ''; + for (let i = 0; i < str.length; i += 1) { + if (str[i] === quoteCharacter && lastCharacter !== '\\') { + newString += `\\${quoteCharacter}`; + } else { + newString += str[i]; + } + + lastCharacter = str[i]; + } + return newString; }, getSpanIds(resultList: TRawAssertionResult[]) { const spanIds = resultList diff --git a/web/src/services/__tests__/Assertion.service.test.ts b/web/src/services/__tests__/Assertion.service.test.ts index 8b3da14038..f82c3d01b2 100644 --- a/web/src/services/__tests__/Assertion.service.test.ts +++ b/web/src/services/__tests__/Assertion.service.test.ts @@ -39,4 +39,17 @@ describe('AssertionService', () => { expect(result).toEqual([id1, id2, id3]); }); }); + describe('escapeString', () => { + it('should escape simple quotes', () => { + const {escapeString} = AssertionService; + const escaped = escapeString(`'This should be escaped'`, `'`); + expect(escaped).toBe(`\\'This should be escaped\\'`); + }); + + it('should not escape already escaped string', () => { + const {escapeString} = AssertionService; + const escaped = escapeString(`\\'This should be escaped\\'`, `'`); + expect(escaped).toBe(`\\'This should be escaped\\'`); + }); + }); });