Skip to content

Commit

Permalink
fix: escape quotes in assertion field (#3934)
Browse files Browse the repository at this point in the history
* fix: escape quotes in assertion field

* fix

* fix
  • Loading branch information
mathnogueira authored Jul 15, 2024
1 parent 9a86b59 commit 19b6e58
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
25 changes: 23 additions & 2 deletions web/src/services/Assertion.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down
13 changes: 13 additions & 0 deletions web/src/services/__tests__/Assertion.service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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\\'`);
});
});
});

0 comments on commit 19b6e58

Please sign in to comment.