☕️ Classic, reliable, trusted test framework for Node.js and the browser
Strip ANSI sequences from xunit output (#6107)
Kairos Opsbf76999b2b2a
diff --git a/lib/reporters/xunit.js b/lib/reporters/xunit.jsindex 4842890b..809df451 100644--- a/lib/reporters/xunit.js+++ b/lib/reporters/xunit.js@@ -25,6 +25,10 @@ var EVENT_RUN_END = constants.EVENT_RUN_END;var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;var STATE_FAILED = Runnable.constants.STATE_FAILED;var escape = utils.escape;+var ANSI_ESCAPE_SEQUENCE = new RegExp(+ String.fromCharCode(27) + "\\[[0-?]*[ -/]*[@-~]",+ "g",+);/*** Save timer references to avoid Sinon interfering (see GH-237).@@ -173,7 +177,10 @@ class XUnit extends Base {"failure",{},false,- escape(err.message) + escape(diff) + "\n" + escape(err.stack),+ escapeXml(err.message) ++ escapeXml(diff) ++ "\n" ++ escapeXml(err.stack),),),);@@ -201,7 +208,7 @@ function tag(name, attrs, close, content) {for (var key in attrs) {if (Object.prototype.hasOwnProperty.call(attrs, key)) {- pairs.push(key + '="' + escape(attrs[key]) + '"');+ pairs.push(key + '="' + escapeXml(attrs[key]) + '"');}}@@ -212,6 +219,30 @@ function tag(name, attrs, close, content) {return tag;}+function escapeXml(value) {+ return escape(+ stripInvalidXmlCharacters(String(value).replace(ANSI_ESCAPE_SEQUENCE, "")),+ );+}++function stripInvalidXmlCharacters(value) {+ var result = "";++ for (var i = 0; i < value.length; i += 1) {+ var charCode = value.charCodeAt(i);+ if (+ charCode === 0x09 ||+ charCode === 0x0a ||+ charCode === 0x0d ||+ charCode >= 0x20+ ) {+ result += value[i];+ }+ }++ return result;+}+function testFilePath(filepath, options) {if (options &&diff --git a/test/reporters/xunit.spec.cjs b/test/reporters/xunit.spec.cjsindex 2a255b7a..7d317603 100644--- a/test/reporters/xunit.spec.cjs+++ b/test/reporters/xunit.spec.cjs@@ -429,6 +429,38 @@ describe("XUnit reporter", function () {expect(expectedWrite, "to contain", expectedDiff);});++ it("should remove ANSI escape sequences and invalid XML control characters", function () {+ var xunit = new XUnit(runner);+ var expectedTest = {+ state: STATE_FAILED,+ title: "\x1b[32m" + expectedTitle + "\x1b[39m",+ file: expectedFile,+ parent: {+ fullTitle: function () {+ return expectedClassName;+ },+ },+ duration: 1000,+ err: {+ actual: "foo",+ expected: "bar",+ message: "\x1b[31m" + expectedMessage + "\x1b[39m\u0007",+ stack: "\x1b[31m" + expectedStack + "\x1b[39m\u0007",+ },+ };++ xunit.test.call(fakeThis, expectedTest);+ sinon.restore();++ expect(expectedWrite, "to contain", 'name="' + expectedTitle + '"');+ expect(expectedWrite, "to contain", "<failure>" + expectedMessage);+ expect(expectedWrite, "to contain", expectedStack);+ expect(expectedWrite, "not to contain", "");+ expect(expectedWrite, "not to contain", "");+ expect(expectedWrite, "not to contain", "[31m");+ expect(expectedWrite, "not to contain", "[39m");+ });});describe("on test pending", function () {