From 9f403bf33119290c262f293207766be1c1e51350 Mon Sep 17 00:00:00 2001 From: Jan Krems Date: Sat, 12 Aug 2017 20:18:56 -0700 Subject: [PATCH] Add `utils.escape` tests and fix unicode escaping Fixes https://github.com/mochajs/mocha/issues/2955 --- lib/utils.js | 7 ++----- package.json | 1 + test/unit/utils.spec.js | 18 ++++++++++++++++++ 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/lib/utils.js b/lib/utils.js index d66eba3bc3..43e28bc4c6 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -18,6 +18,7 @@ var statSync = require('fs').statSync; var watchFile = require('fs').watchFile; var lstatSync = require('fs').lstatSync; var toISOString = require('./to-iso-string'); +var he = require('he'); /** * Ignored directories. @@ -35,11 +36,7 @@ exports.inherits = require('util').inherits; * @return {string} */ exports.escape = function (html) { - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); + return he.encode(String(html), { useNamedReferences: true }); }; /** diff --git a/package.json b/package.json index e199cee1b3..6c7687da1f 100644 --- a/package.json +++ b/package.json @@ -314,6 +314,7 @@ "escape-string-regexp": "1.0.5", "glob": "7.1.1", "growl": "1.9.2", + "he": "1.1.1", "json3": "3.3.2", "lodash.create": "3.1.1", "mkdirp": "0.5.1", diff --git a/test/unit/utils.spec.js b/test/unit/utils.spec.js index ad64fd847c..078d05e5ff 100644 --- a/test/unit/utils.spec.js +++ b/test/unit/utils.spec.js @@ -624,4 +624,22 @@ describe('lib/utils', function () { expect(utils.isPromise({})).to.be(false); }); }); + + describe('escape', function () { + it('replaces the usual xml suspects', function () { + expect(utils.escape('a>bc>d>')).to.be('>a>bc>d>'); + expect(utils.escape('"a"bc"d"')).to.be('"a"bc"d"'); + expect(utils.escape('<>"&')).to.be('<>"&'); + + expect(utils.escape('&a&bc&d&')).to.be('&a&bc&d&'); + expect(utils.escape('&<')).to.be('&amp;&lt;'); + }); + + it('replaces invalid xml characters', function () { + expect(utils.escape('\x1B[32mfoo\x1B[0m')).to.be('foo'); + // Ensure we can handle non-trivial unicode characters as well + expect(utils.escape('💩')).to.be('💩'); + }); + }); });