Convert tests to vitest (#2127)

* Convert tests to vitest
* fix git tests
* Cleanup
* Convert ignore comments
* address code review comments
This commit is contained in:
Igor Savin
2026-03-02 22:33:52 +02:00
committed by GitHub
parent 1245255892
commit d65683434d
38 changed files with 3453 additions and 3138 deletions
+5 -5
View File
@@ -18,14 +18,14 @@ module.exports = {
start: true,
stop: true,
ok: true,
sinon: true,
vi: true,
strictEqual: true,
define: true,
expect: true,
chai: true,
},
env: {
mocha: true,
beforeEach: true,
afterEach: true,
describe: true,
it: true,
},
rules: {
// Disabling for tests, for now.
-6
View File
@@ -1,9 +1,3 @@
global.handlebarsEnv = null;
beforeEach(function () {
global.handlebarsEnv = Handlebars.create();
});
describe('basic context', function () {
it('most basic', function () {
expectTemplate('{{foo}}').withInput({ foo: 'foo' }).toCompileTo('foo');
+2 -2
View File
@@ -785,13 +785,13 @@ describe('builtin helpers', function () {
var called;
console.info = console.log = function () {
expect(arguments.length).to.equal(0);
expect(arguments.length).toBe(0);
called = true;
console.log = $log;
};
expectTemplate('{{log}}').withInput({ blah: 'whee' }).toCompileTo('');
expect(called).to.be.true();
expect(called).toBe(true);
});
/* eslint-enable no-console */
});
+6
View File
@@ -0,0 +1,6 @@
// Pre-setup for browser tests. Must run before the main setup file
// imports the Handlebars library, so that noConflict() captures this value.
globalThis.Handlebars = 'no-conflict';
// Polyfill Node.js 'global' for specs that reference it at module level
globalThis.global = globalThis;
+27
View File
@@ -0,0 +1,27 @@
import './common.js';
import Handlebars from '../../lib/handlebars.js';
globalThis.Handlebars = Handlebars;
globalThis.CompilerContext = {
browser: true,
compile: function (template, options) {
var templateSpec = handlebarsEnv.precompile(template, options);
return handlebarsEnv.template(safeEval(templateSpec));
},
compileWithPartial: function (template, options) {
return handlebarsEnv.compile(template, options);
},
};
function safeEval(templateSpec) {
/* eslint-disable no-eval, no-console */
try {
return eval('(' + templateSpec + ')');
} catch (err) {
console.error(templateSpec);
throw err;
}
/* eslint-enable no-eval, no-console */
}
-11
View File
@@ -3,20 +3,9 @@ require('./common');
var fs = require('fs'),
vm = require('vm');
var chai = require('chai');
var dirtyChai = require('dirty-chai');
chai.use(dirtyChai);
global.expect = chai.expect;
global.sinon = require('sinon');
global.Handlebars = 'no-conflict';
var filename = 'dist/handlebars.js';
if (global.minimizedTest) {
filename = 'dist/handlebars.min.js';
}
var distHandlebars = fs.readFileSync(
require.resolve('../../' + filename),
'utf-8'
+33 -48
View File
@@ -1,22 +1,4 @@
var global = (function () {
return this;
})();
var AssertError;
if (Error.captureStackTrace) {
AssertError = function AssertError(message, caller) {
Error.prototype.constructor.call(this, message);
this.message = message;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, caller || AssertError);
}
};
AssertError.prototype = new Error();
} else {
AssertError = Error;
}
var global = globalThis;
/**
* @deprecated Use "expectTemplate(template)...toCompileTo(output)" instead
@@ -33,15 +15,10 @@ global.shouldCompileToWithPartials = function shouldCompileToWithPartials(
hashOrArray,
partials,
expected,
message
message // eslint-disable-line no-unused-vars
) {
var result = compileWithPartials(string, hashOrArray, partials);
if (result !== expected) {
throw new AssertError(
"'" + result + "' should === '" + expected + "': " + message,
shouldCompileToWithPartials
);
}
expect(result).toBe(expected);
};
/**
@@ -76,21 +53,15 @@ global.compileWithPartials = function (string, hashOrArray, partials) {
};
/**
* @deprecated Use chai's expect-style API instead (`expect(actualValue).to.equal(expectedValue)`)
* @see https://www.chaijs.com/api/bdd/
* @deprecated Use vitest's expect API instead
*/
// eslint-disable-next-line no-unused-vars
global.equals = global.equal = function equals(a, b, msg) {
if (a !== b) {
throw new AssertError(
"'" + a + "' should === '" + b + "'" + (msg ? ': ' + msg : ''),
equals
);
}
expect(a).toBe(b);
};
/**
* @deprecated Use chai's expect-style API instead (`expect(actualValue).to.equal(expectedValue)`)
* @see https://www.chaijs.com/api/bdd/#method_throw
* @deprecated Use vitest's expect API instead
*/
global.shouldThrow = function (callback, type, msg) {
var failed;
@@ -99,25 +70,24 @@ global.shouldThrow = function (callback, type, msg) {
failed = true;
} catch (caught) {
if (type && !(caught instanceof type)) {
throw new AssertError('Type failure: ' + caught);
throw new Error('Type failure: ' + caught);
}
if (
msg &&
!(msg.test ? msg.test(caught.message) : msg === caught.message)
) {
throw new AssertError(
throw new Error(
'Throw mismatch: Expected ' +
caught.message +
' to match ' +
msg +
'\n\n' +
caught.stack,
shouldThrow
caught.stack
);
}
}
if (failed) {
throw new AssertError('It failed to throw', shouldThrow);
throw new Error('It failed to throw');
}
};
@@ -200,18 +170,29 @@ HandlebarsTestBench.prototype.withMessage = function (message) {
};
HandlebarsTestBench.prototype.toCompileTo = function (expectedOutputAsString) {
expect(this._compileAndExecute()).to.equal(
expectedOutputAsString,
this.message
);
expect(this._compileAndExecute()).toBe(expectedOutputAsString);
};
// see chai "to.throw" (https://www.chaijs.com/api/bdd/#method_throw)
HandlebarsTestBench.prototype.toThrow = function (errorLike, errMsgMatcher) {
var self = this;
expect(function () {
var caught;
try {
self._compileAndExecute();
}).to.throw(errorLike, errMsgMatcher, this.message);
} catch (e) {
caught = e;
}
expect(caught).toBeDefined();
if (typeof errorLike === 'function') {
expect(caught).toBeInstanceOf(errorLike);
if (errMsgMatcher) {
expect(caught.message).toMatch(errMsgMatcher);
}
} else if (errorLike) {
// errorLike is a string or regex message matcher (single-argument form)
expect(caught.message).toMatch(errorLike);
}
};
HandlebarsTestBench.prototype._compileAndExecute = function () {
@@ -237,3 +218,7 @@ HandlebarsTestBench.prototype._combineRuntimeOptions = function () {
combinedRuntimeOptions.decorators = this.decorators;
return combinedRuntimeOptions;
};
beforeEach(function () {
global.handlebarsEnv = Handlebars.create();
});
-8
View File
@@ -1,13 +1,5 @@
require('./common');
var chai = require('chai');
var dirtyChai = require('dirty-chai');
chai.use(dirtyChai);
global.expect = chai.expect;
global.sinon = require('sinon');
global.Handlebars = require('../../lib');
global.CompilerContext = {
-63
View File
@@ -1,63 +0,0 @@
/* eslint-disable no-console */
var fs = require('fs'),
Mocha = require('mocha'),
path = require('path');
var errors = 0,
testDir = path.dirname(__dirname),
grep = process.argv[2];
// Lazy hack, but whatever
if (grep === '--min') {
global.minimizedTest = true;
grep = undefined;
}
var files = fs
.readdirSync(testDir)
.filter(function (name) {
return /.*\.js$/.test(name);
})
.map(function (name) {
return testDir + path.sep + name;
});
if (global.minimizedTest) {
run('./runtime', function () {
run('./browser', function () {
/* eslint-disable no-process-exit */
process.exit(errors);
/* eslint-enable no-process-exit */
});
});
} else {
run('./runtime', function () {
run('./browser', function () {
run('./node', function () {
/* eslint-disable no-process-exit */
process.exit(errors);
/* eslint-enable no-process-exit */
});
});
});
}
function run(env, callback) {
var mocha = new Mocha();
mocha.ui('bdd');
mocha.files = files.slice();
if (grep) {
mocha.grep(grep);
}
files.forEach(function (name) {
delete require.cache[name];
});
console.log('Running env: ' + env);
require(env);
mocha.run(function (errorCount) {
errors += errorCount;
callback();
});
}
-73
View File
@@ -1,73 +0,0 @@
require('./common');
var fs = require('fs'),
vm = require('vm');
var chai = require('chai');
var dirtyChai = require('dirty-chai');
chai.use(dirtyChai);
global.expect = chai.expect;
global.sinon = require('sinon');
global.Handlebars = 'no-conflict';
var filename = 'dist/handlebars.runtime.js';
if (global.minimizedTest) {
filename = 'dist/handlebars.runtime.min.js';
}
vm.runInThisContext(
fs.readFileSync(__dirname + '/../../' + filename),
filename
);
var parse = require('@handlebars/parser').parse;
var compiler = require('../../dist/cjs/handlebars/compiler/compiler');
var JavaScriptCompiler = require('../../dist/cjs/handlebars/compiler/javascript-compiler');
global.CompilerContext = {
browser: true,
compile: function (template, options) {
// Hack the compiler on to the environment for these specific tests
handlebarsEnv.precompile = function (
precompileTemplate,
precompileOptions
) {
return compiler.precompile(
precompileTemplate,
precompileOptions,
handlebarsEnv
);
};
handlebarsEnv.parse = parse;
handlebarsEnv.Compiler = compiler.Compiler;
handlebarsEnv.JavaScriptCompiler = JavaScriptCompiler;
var templateSpec = handlebarsEnv.precompile(template, options);
return handlebarsEnv.template(safeEval(templateSpec));
},
compileWithPartial: function (template, options) {
// Hack the compiler on to the environment for these specific tests
handlebarsEnv.compile = function (compileTemplate, compileOptions) {
return compiler.compile(compileTemplate, compileOptions, handlebarsEnv);
};
handlebarsEnv.parse = parse;
handlebarsEnv.Compiler = compiler.Compiler;
handlebarsEnv.JavaScriptCompiler = JavaScriptCompiler;
return handlebarsEnv.compile(template, options);
},
};
function safeEval(templateSpec) {
/* eslint-disable no-eval, no-console */
try {
return eval('(' + templateSpec + ')');
} catch (err) {
console.error(templateSpec);
throw err;
}
/* eslint-enable no-eval, no-console */
}
+1 -1
View File
@@ -53,7 +53,7 @@ describe('helpers', function () {
runWithIdentityHelper('{{{{identity}}}}{{{{/identity}}}}', '');
});
xit('helper for nested raw block works if nested raw blocks are broken', function () {
it.skip('helper for nested raw block works if nested raw blocks are broken', function () {
// This test was introduced in 4.4.4, but it was not the actual problem that lead to the patch release
// The test is deactivated, because in 3.x this template cases an exception and it also does not work in 4.4.3
// If anyone can make this template work without breaking everything else, then go for it,
+36 -89
View File
@@ -1,98 +1,45 @@
<!doctype html>
<html>
<head>
<title>Mocha</title>
<title>Handlebars UMD Smoke Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/node_modules/mocha/mocha.css" />
<style>
.headless .suite > h1,
.headless .test.pass {
display: none;
}
</style>
<script>
// Show only errors in "headless", non-interactive mode.
if (/headless=true/.test(location.href)) {
document.documentElement.className = 'headless';
}
</script>
<script src="/node_modules/sinon/pkg/sinon.js"></script>
<script src="/node_modules/chai/chai.js"></script>
<script src="/node_modules/dirty-chai/lib/dirty-chai.js"></script>
<script src="/node_modules/mocha/mocha.js"></script>
<script>
window.expect = chai.expect;
mocha.setup('bdd');
</script>
<script src="/dist/handlebars.js"></script>
<script src="/spec/env/common.js"></script>
<script>
var CompilerContext = {
compile: function(template, options) {
var templateSpec = handlebarsEnv.precompile(template, options);
return handlebarsEnv.template(safeEval(templateSpec));
},
compileWithPartial: function(template, options) {
return handlebarsEnv.compile(template, options);
}
};
function safeEval(templateSpec) {
try {
var ret;
eval('ret = ' + templateSpec);
return ret;
} catch (err) {
console.error(templateSpec);
throw err;
}
}
</script>
<script src="/tmp/tests.js"></script>
<script>
onload = function(){
mocha.globals(['mochaResults'])
// The test harness leaks under FF. We should have decent global leak coverage from other tests
if (!navigator.userAgent.match(/Firefox\/([\d.]+)/)) {
mocha.checkLeaks();
}
var runner = mocha.run();
// Reporting to test-runner
var failedTests = [];
runner.on('end', function(){
window.mochaResults = runner.stats;
window.mochaResults.reports = failedTests;
});
runner.on('fail', logFailure);
function logFailure(test, err){
var flattenTitles = function(test){
var titles = [];
while (test.parent.title){
titles.push(test.parent.title);
test = test.parent;
}
return titles.reverse();
};
failedTests.push({
name: test.title,
result: false,
message: err.message,
stack: err.stack,
titles: flattenTitles(test)
});
};
};
</script>
</head>
<body>
<div id="mocha"></div>
<h1>Handlebars UMD Smoke Test</h1>
<pre id="results"></pre>
<script src="/dist/handlebars.js"></script>
<script>
var results = document.getElementById('results');
var failures = 0;
var tests = 0;
function assert(condition, message) {
tests++;
if (!condition) {
failures++;
results.textContent += 'FAIL: ' + message + '\n';
} else {
results.textContent += 'PASS: ' + message + '\n';
}
}
try {
assert(typeof Handlebars !== 'undefined', 'Handlebars is defined');
assert(typeof Handlebars.compile === 'function', 'Handlebars.compile exists');
assert(typeof Handlebars.template === 'function', 'Handlebars.template exists');
assert(typeof Handlebars.VERSION === 'string', 'Handlebars.VERSION exists');
var template = Handlebars.compile('Hello {{name}}!');
var output = template({ name: 'World' });
assert(output === 'Hello World!', 'Basic compilation works: ' + output);
} catch (e) {
failures++;
results.textContent += 'ERROR: ' + e.message + '\n';
}
results.textContent += '\n' + tests + ' tests, ' + failures + ' failures\n';
window.mochaResults = { passes: tests - failures, failures: failures };
</script>
</body>
</html>
+31 -26
View File
@@ -34,30 +34,35 @@ describe('javascript-compiler api', function () {
.toCompileTo('food');
});
});
describe('#compilerInfo', function () {
var $superCheck, $superInfo;
beforeEach(function () {
$superCheck = handlebarsEnv.VM.checkRevision;
$superInfo = handlebarsEnv.JavaScriptCompiler.prototype.compilerInfo;
});
afterEach(function () {
handlebarsEnv.VM.checkRevision = $superCheck;
handlebarsEnv.JavaScriptCompiler.prototype.compilerInfo = $superInfo;
});
it('should allow compilerInfo override', function () {
handlebarsEnv.JavaScriptCompiler.prototype.compilerInfo = function () {
return 'crazy';
};
handlebarsEnv.VM.checkRevision = function (compilerInfo) {
if (compilerInfo !== 'crazy') {
throw new Error("It didn't work");
}
};
expectTemplate('{{foo}} ')
.withInput({ foo: 'food' })
.toCompileTo('food ');
});
});
// Monkey-patching VM.checkRevision is not possible when VM is an ESM
// namespace object (browser mode), so skip these tests in that context.
(CompilerContext.browser ? describe.skip : describe)(
'#compilerInfo',
function () {
var $superCheck, $superInfo;
beforeEach(function () {
$superCheck = handlebarsEnv.VM.checkRevision;
$superInfo = handlebarsEnv.JavaScriptCompiler.prototype.compilerInfo;
});
afterEach(function () {
handlebarsEnv.VM.checkRevision = $superCheck;
handlebarsEnv.JavaScriptCompiler.prototype.compilerInfo = $superInfo;
});
it('should allow compilerInfo override', function () {
handlebarsEnv.JavaScriptCompiler.prototype.compilerInfo = function () {
return 'crazy';
};
handlebarsEnv.VM.checkRevision = function (compilerInfo) {
if (compilerInfo !== 'crazy') {
throw new Error("It didn't work");
}
};
expectTemplate('{{foo}} ')
.withInput({ foo: 'food' })
.toCompileTo('food ');
});
}
);
describe('buffer', function () {
var $superAppend, $superCreate;
beforeEach(function () {
@@ -105,7 +110,7 @@ describe('javascript-compiler api', function () {
handlebarsEnv.JavaScriptCompiler.isValidJavaScriptVariableName(
validVariableName
)
).to.be.true();
).toBe(true);
});
});
[('123test', 'abc()', 'abc.cde')].forEach(function (invalidVariableName) {
@@ -114,7 +119,7 @@ describe('javascript-compiler api', function () {
handlebarsEnv.JavaScriptCompiler.isValidJavaScriptVariableName(
invalidVariableName
)
).to.be.false();
).toBe(false);
});
});
});
+72 -75
View File
@@ -297,112 +297,109 @@ describe('precompiler', function () {
});
describe('#loadTemplates', function () {
it('should throw on missing template', function (done) {
Precompiler.loadTemplates({ files: ['foo'] }, function (err) {
equal(err.message, 'Unable to open template file "foo"');
done();
function loadTemplatesAsync(inputOpts) {
// eslint-disable-next-line compat/compat
return new Promise(function (resolve, reject) {
Precompiler.loadTemplates(inputOpts, function (err, opts) {
if (err) {
reject(err);
} else {
resolve(opts);
}
});
});
});
it('should enumerate directories by extension', function (done) {
Precompiler.loadTemplates(
{ files: [__dirname + '/artifacts'], extension: 'hbs' },
function (err, opts) {
equal(opts.templates.length, 2);
equal(opts.templates[0].name, 'example_2');
}
done(err);
}
);
it('should throw on missing template', async function () {
try {
await loadTemplatesAsync({ files: ['foo'] });
throw new Error('should have thrown');
} catch (err) {
equal(err.message, 'Unable to open template file "foo"');
}
});
it('should enumerate all templates by extension', function (done) {
Precompiler.loadTemplates(
{ files: [__dirname + '/artifacts'], extension: 'handlebars' },
function (err, opts) {
equal(opts.templates.length, 5);
equal(opts.templates[0].name, 'bom');
equal(opts.templates[1].name, 'empty');
equal(opts.templates[2].name, 'example_1');
done(err);
}
);
it('should enumerate directories by extension', async function () {
var opts = await loadTemplatesAsync({
files: [__dirname + '/artifacts'],
extension: 'hbs',
});
equal(opts.templates.length, 2);
equal(opts.templates[0].name, 'example_2');
});
it('should handle regular expression characters in extensions', function (done) {
Precompiler.loadTemplates(
{ files: [__dirname + '/artifacts'], extension: 'hb(s' },
function (err) {
// Success is not throwing
done(err);
}
);
it('should enumerate all templates by extension', async function () {
var opts = await loadTemplatesAsync({
files: [__dirname + '/artifacts'],
extension: 'handlebars',
});
equal(opts.templates.length, 5);
equal(opts.templates[0].name, 'bom');
equal(opts.templates[1].name, 'empty');
equal(opts.templates[2].name, 'example_1');
});
it('should handle BOM', function (done) {
var opts = {
it('should handle regular expression characters in extensions', async function () {
await loadTemplatesAsync({
files: [__dirname + '/artifacts'],
extension: 'hb(s',
});
// Success is not throwing
});
it('should handle BOM', async function () {
var opts = await loadTemplatesAsync({
files: [__dirname + '/artifacts/bom.handlebars'],
extension: 'handlebars',
bom: true,
};
Precompiler.loadTemplates(opts, function (err, opts) {
equal(opts.templates[0].source, 'a');
done(err);
});
equal(opts.templates[0].source, 'a');
});
it('should handle different root', function (done) {
var opts = {
it('should handle different root', async function () {
var opts = await loadTemplatesAsync({
files: [__dirname + '/artifacts/empty.handlebars'],
simple: true,
root: 'foo/',
};
Precompiler.loadTemplates(opts, function (err, opts) {
equal(opts.templates[0].name, __dirname + '/artifacts/empty');
done(err);
});
equal(opts.templates[0].name, __dirname + '/artifacts/empty');
});
it('should accept string inputs', function (done) {
var opts = { string: '' };
Precompiler.loadTemplates(opts, function (err, opts) {
equal(opts.templates[0].name, undefined);
equal(opts.templates[0].source, '');
done(err);
});
it('should accept string inputs', async function () {
var opts = await loadTemplatesAsync({ string: '' });
equal(opts.templates[0].name, undefined);
equal(opts.templates[0].source, '');
});
it('should accept string array inputs', function (done) {
var opts = { string: ['', 'bar'], name: ['beep', 'boop'] };
Precompiler.loadTemplates(opts, function (err, opts) {
equal(opts.templates[0].name, 'beep');
equal(opts.templates[0].source, '');
equal(opts.templates[1].name, 'boop');
equal(opts.templates[1].source, 'bar');
done(err);
it('should accept string array inputs', async function () {
var opts = await loadTemplatesAsync({
string: ['', 'bar'],
name: ['beep', 'boop'],
});
equal(opts.templates[0].name, 'beep');
equal(opts.templates[0].source, '');
equal(opts.templates[1].name, 'boop');
equal(opts.templates[1].source, 'bar');
});
it('should accept stdin input', function (done) {
it('should accept stdin input', async function () {
var stdin = require('mock-stdin').stdin();
Precompiler.loadTemplates({ string: '-' }, function (err, opts) {
equal(opts.templates[0].source, 'foo');
done(err);
});
var promise = loadTemplatesAsync({ string: '-' });
stdin.send('fo');
stdin.send('o');
stdin.end();
var opts = await promise;
equal(opts.templates[0].source, 'foo');
});
it('error on name missing', function (done) {
var opts = { string: ['', 'bar'] };
Precompiler.loadTemplates(opts, function (err) {
it('error on name missing', async function () {
try {
await loadTemplatesAsync({ string: ['', 'bar'] });
throw new Error('should have thrown');
} catch (err) {
equal(
err.message,
'Number of names did not match the number of string inputs'
);
done();
});
}
});
it('should complete when no args are passed', function (done) {
Precompiler.loadTemplates({}, function (err, opts) {
equal(opts.templates.length, 0);
done(err);
});
it('should complete when no args are passed', async function () {
var opts = await loadTemplatesAsync({});
equal(opts.templates.length, 0);
});
});
});
+5 -5
View File
@@ -403,7 +403,7 @@ describe('Regressions', function () {
property: 'a',
test: { a: 'b' },
})
).to.equal('b');
).toBe('b');
});
function registerTemplate(Handlebars, compileTemplate) {
@@ -479,19 +479,19 @@ describe('Regressions', function () {
newHandlebarsInstance = Handlebars.create();
});
afterEach(function () {
sinon.restore();
vi.restoreAllMocks();
});
it('should only compile global partials once', function () {
var templateSpy = sinon.spy(newHandlebarsInstance, 'template');
var templateSpy = vi.spyOn(newHandlebarsInstance, 'template');
newHandlebarsInstance.registerPartial({
dude: 'I am a partial',
});
var string = 'Dudes: {{> dude}} {{> dude}}';
newHandlebarsInstance.compile(string)(); // This should compile template + partial once
newHandlebarsInstance.compile(string)(); // This should only compile template
equal(templateSpy.callCount, 3);
sinon.restore();
expect(templateSpy).toHaveBeenCalledTimes(3);
vi.restoreAllMocks();
});
});
+3 -4
View File
@@ -57,11 +57,10 @@ describe('runtime', function () {
});
describe('#noConflict', function () {
if (!CompilerContext.browser) {
return;
}
it('should reset on no conflict', function () {
if (!CompilerContext.browser) {
return;
}
var reset = Handlebars;
Handlebars.noConflict();
equal(Handlebars, 'no-conflict');
+71 -42
View File
@@ -57,8 +57,8 @@ describe('security issues', function () {
functionCalls.push('called');
},
});
}).to.throw(Error);
expect(functionCalls.length).to.equal(0);
}).toThrow();
expect(functionCalls.length).toBe(0);
});
it('should throw an exception when calling "{{#blockHelperMissing .}}{{/blockHelperMissing}}"', function () {
@@ -109,20 +109,23 @@ describe('security issues', function () {
});
describe('GH-1563', function () {
it('should not allow to access constructor after overriding via __defineGetter__', function () {
if ({}.__defineGetter__ == null || {}.__lookupGetter__ == null) {
return this.skip(); // Browser does not support this exploit anyway
var browserSupportsExploit =
{}.__defineGetter__ != null && {}.__lookupGetter__ != null;
it.skipIf(!browserSupportsExploit)(
'should not allow to access constructor after overriding via __defineGetter__',
function () {
expectTemplate(
'{{__defineGetter__ "undefined" valueOf }}' +
'{{#with __lookupGetter__ }}' +
'{{__defineGetter__ "propertyIsEnumerable" (this.bind (this.bind 1)) }}' +
'{{constructor.name}}' +
'{{/with}}'
)
.withInput({})
.toThrow(/Missing helper: "__defineGetter__"/);
}
expectTemplate(
'{{__defineGetter__ "undefined" valueOf }}' +
'{{#with __lookupGetter__ }}' +
'{{__defineGetter__ "propertyIsEnumerable" (this.bind (this.bind 1)) }}' +
'{{constructor.name}}' +
'{{/with}}'
)
.withInput({})
.toThrow(/Missing helper: "__defineGetter__"/);
});
);
});
describe('GH-1595: dangerous properties', function () {
@@ -169,7 +172,7 @@ describe('security issues', function () {
});
afterEach(function () {
sinon.restore();
vi.restoreAllMocks();
});
describe('control access to prototype methods via "allowedProtoMethods"', function () {
@@ -181,19 +184,25 @@ describe('security issues', function () {
function checkProtoMethodAccess(compileOptions) {
it('should be prohibited by default and log a warning', function () {
var spy = sinon.spy(console, 'error');
var spy = vi
.spyOn(console, 'error')
.mockImplementation(function () {});
expectTemplate('{{aMethod}}')
.withInput(new TestClass())
.withCompileOptions(compileOptions)
.toCompileTo('');
expect(spy.calledOnce).to.be.true();
expect(spy.args[0][0]).to.match(/Handlebars: Access has been denied/);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy.mock.calls[0][0]).toMatch(
/Handlebars: Access has been denied/
);
});
it('should only log the warning once', function () {
var spy = sinon.spy(console, 'error');
var spy = vi
.spyOn(console, 'error')
.mockImplementation(function () {});
expectTemplate('{{aMethod}}')
.withInput(new TestClass())
@@ -205,12 +214,16 @@ describe('security issues', function () {
.withCompileOptions(compileOptions)
.toCompileTo('');
expect(spy.calledOnce).to.be.true();
expect(spy.args[0][0]).to.match(/Handlebars: Access has been denied/);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy.mock.calls[0][0]).toMatch(
/Handlebars: Access has been denied/
);
});
it('can be allowed, which disables the warning', function () {
var spy = sinon.spy(console, 'error');
var spy = vi
.spyOn(console, 'error')
.mockImplementation(function () {});
expectTemplate('{{aMethod}}')
.withInput(new TestClass())
@@ -222,11 +235,13 @@ describe('security issues', function () {
})
.toCompileTo('returnValue');
expect(spy.callCount).to.equal(0);
expect(spy).not.toHaveBeenCalled();
});
it('can be turned on by default, which disables the warning', function () {
var spy = sinon.spy(console, 'error');
var spy = vi
.spyOn(console, 'error')
.mockImplementation(function () {});
expectTemplate('{{aMethod}}')
.withInput(new TestClass())
@@ -236,11 +251,13 @@ describe('security issues', function () {
})
.toCompileTo('returnValue');
expect(spy.callCount).to.equal(0);
expect(spy).not.toHaveBeenCalled();
});
it('can be turned off by default, which disables the warning', function () {
var spy = sinon.spy(console, 'error');
var spy = vi
.spyOn(console, 'error')
.mockImplementation(function () {});
expectTemplate('{{aMethod}}')
.withInput(new TestClass())
@@ -250,7 +267,7 @@ describe('security issues', function () {
})
.toCompileTo('');
expect(spy.callCount).to.equal(0);
expect(spy).not.toHaveBeenCalled();
});
it('can be turned off, if turned on by default', function () {
@@ -300,19 +317,25 @@ describe('security issues', function () {
function checkProtoPropertyAccess(compileOptions) {
it('should be prohibited by default and log a warning', function () {
var spy = sinon.spy(console, 'error');
var spy = vi
.spyOn(console, 'error')
.mockImplementation(function () {});
expectTemplate('{{aProperty}}')
.withInput(new TestClass())
.withCompileOptions(compileOptions)
.toCompileTo('');
expect(spy.calledOnce).to.be.true();
expect(spy.args[0][0]).to.match(/Handlebars: Access has been denied/);
expect(spy).toHaveBeenCalledTimes(1);
expect(spy.mock.calls[0][0]).toMatch(
/Handlebars: Access has been denied/
);
});
it('can be explicitly prohibited by default, which disables the warning', function () {
var spy = sinon.spy(console, 'error');
var spy = vi
.spyOn(console, 'error')
.mockImplementation(function () {});
expectTemplate('{{aProperty}}')
.withInput(new TestClass())
@@ -322,11 +345,13 @@ describe('security issues', function () {
})
.toCompileTo('');
expect(spy.callCount).to.equal(0);
expect(spy).not.toHaveBeenCalled();
});
it('can be turned on, which disables the warning', function () {
var spy = sinon.spy(console, 'error');
var spy = vi
.spyOn(console, 'error')
.mockImplementation(function () {});
expectTemplate('{{aProperty}}')
.withInput(new TestClass())
@@ -338,11 +363,13 @@ describe('security issues', function () {
})
.toCompileTo('propertyValue');
expect(spy.callCount).to.equal(0);
expect(spy).not.toHaveBeenCalled();
});
it('can be turned on by default, which disables the warning', function () {
var spy = sinon.spy(console, 'error');
var spy = vi
.spyOn(console, 'error')
.mockImplementation(function () {});
expectTemplate('{{aProperty}}')
.withInput(new TestClass())
@@ -352,7 +379,7 @@ describe('security issues', function () {
})
.toCompileTo('propertyValue');
expect(spy.callCount).to.equal(0);
expect(spy).not.toHaveBeenCalled();
});
it('can be turned off, if turned on by default', function () {
@@ -373,14 +400,16 @@ describe('security issues', function () {
describe('compatibility with old runtimes, that do not provide the function "container.lookupProperty"', function () {
beforeEach(function simulateRuntimeWithoutLookupProperty() {
var oldTemplateMethod = handlebarsEnv.template;
sinon.replace(handlebarsEnv, 'template', function (templateSpec) {
templateSpec.main = wrapToAdjustContainer(templateSpec.main);
return oldTemplateMethod.call(this, templateSpec);
});
vi.spyOn(handlebarsEnv, 'template').mockImplementation(
function (templateSpec) {
templateSpec.main = wrapToAdjustContainer(templateSpec.main);
return oldTemplateMethod.call(this, templateSpec);
}
);
});
afterEach(function () {
sinon.restore();
vi.restoreAllMocks();
});
it('should work with simple properties', function () {
+34 -77
View File
@@ -1,91 +1,48 @@
<!doctype html>
<html>
<head>
<title>Mocha</title>
<title>Handlebars Runtime UMD Smoke Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/node_modules/mocha/mocha.css" />
<style>
.headless .suite > h1,
.headless .test.pass {
display: none;
}
</style>
<script>
// Show only errors in "headless", non-interactive mode.
if (/headless=true/.test(location.href)) {
document.documentElement.className = 'headless';
}
</script>
<script src="/node_modules/sinon/pkg/sinon.js"></script>
<script src="/node_modules/chai/chai.js"></script>
<script src="/node_modules/dirty-chai/lib/dirty-chai.js"></script>
<script src="/node_modules/mocha/mocha.js"></script>
<script>
window.expect = chai.expect;
mocha.setup('bdd');
</script>
</head>
<body>
<h1>Handlebars Runtime UMD Smoke Test</h1>
<pre id="results"></pre>
<script src="/spec/vendor/require.js"></script>
<script src="/spec/env/common.js"></script>
<script>
var results = document.getElementById('results');
var failures = 0;
var tests = 0;
function assert(condition, message) {
tests++;
if (!condition) {
failures++;
results.textContent += 'FAIL: ' + message + '\n';
} else {
results.textContent += 'PASS: ' + message + '\n';
}
}
requirejs.config({
paths: {
'handlebars.runtime': '/dist/handlebars.runtime'
}
});
require(['handlebars.runtime'], function(Handlebars) {
try {
assert(typeof Handlebars !== 'undefined', 'Handlebars runtime loaded via RequireJS');
assert(typeof Handlebars.template === 'function', 'Handlebars.template exists');
assert(typeof Handlebars.VERSION === 'string', 'Handlebars.VERSION exists');
} catch (e) {
failures++;
results.textContent += 'ERROR: ' + e.message + '\n';
}
results.textContent += '\n' + tests + ' tests, ' + failures + ' failures\n';
window.mochaResults = { passes: tests - failures, failures: failures };
});
</script>
<script>
onload = function(){
require(['handlebars.runtime'], function(Handlebars) {
describe('runtime', function() {
it('should load', function() {
equal(!!Handlebars.template, true);
equal(!!Handlebars.VERSION, true);
});
});
mocha.globals(['mochaResults'])
// The test harness leaks under FF. We should have decent global leak coverage from other tests
if (!navigator.userAgent.match(/Firefox\/([\d.]+)/)) {
mocha.checkLeaks();
}
var runner = mocha.run();
// Reporting to test-runner
var failedTests = [];
runner.on('end', function(){
window.mochaResults = runner.stats;
window.mochaResults.reports = failedTests;
});
runner.on('fail', logFailure);
function logFailure(test, err){
var flattenTitles = function(test){
var titles = [];
while (test.parent.title){
titles.push(test.parent.title);
test = test.parent;
}
return titles.reverse();
};
failedTests.push({
name: test.title,
result: false,
message: err.message,
stack: err.stack,
titles: flattenTitles(test)
});
}
});
};
</script>
</head>
<body>
<div id="mocha"></div>
</body>
</html>
+37 -96
View File
@@ -1,112 +1,53 @@
<!doctype html>
<html>
<head>
<title>Mocha</title>
<title>Handlebars UMD Module Smoke Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/node_modules/mocha/mocha.css" />
<style>
.headless .suite > h1,
.headless .test.pass {
display: none;
}
</style>
<script>
// Show only errors in "headless", non-interactive mode.
if (/headless=true/.test(location.href)) {
document.documentElement.className = 'headless';
}
</script>
<script src="/node_modules/sinon/pkg/sinon.js"></script>
<script src="/node_modules/chai/chai.js"></script>
<script src="/node_modules/dirty-chai/lib/dirty-chai.js"></script>
<script src="/node_modules/mocha/mocha.js"></script>
<script>
window.expect = chai.expect;
mocha.setup('bdd');
</script>
</head>
<body>
<h1>Handlebars UMD Module Smoke Test</h1>
<pre id="results"></pre>
<script src="/spec/vendor/require.js"></script>
<script src="/spec/env/common.js"></script>
<script>
var results = document.getElementById('results');
var failures = 0;
var tests = 0;
function assert(condition, message) {
tests++;
if (!condition) {
failures++;
results.textContent += 'FAIL: ' + message + '\n';
} else {
results.textContent += 'PASS: ' + message + '\n';
}
}
requirejs.config({
paths: {
handlebars: '/dist/handlebars',
tests: '/tmp/tests'
handlebars: '/dist/handlebars'
}
});
var CompilerContext = {
compile: function(template, options) {
var templateSpec = handlebarsEnv.precompile(template, options);
return handlebarsEnv.template(safeEval(templateSpec));
},
compileWithPartial: function(template, options) {
return handlebarsEnv.compile(template, options);
}
};
function safeEval(templateSpec) {
require(['handlebars'], function(Handlebars) {
try {
var ret;
eval('ret = ' + templateSpec);
return ret;
} catch (err) {
console.error(templateSpec);
throw err;
assert(typeof Handlebars !== 'undefined', 'Handlebars loaded via RequireJS');
assert(typeof Handlebars.compile === 'function', 'Handlebars.compile exists');
assert(typeof Handlebars.template === 'function', 'Handlebars.template exists');
assert(typeof Handlebars.VERSION === 'string', 'Handlebars.VERSION exists');
var template = Handlebars.compile('Hello {{name}}!');
var output = template({ name: 'UMD' });
assert(output === 'Hello UMD!', 'Basic compilation works: ' + output);
} catch (e) {
failures++;
results.textContent += 'ERROR: ' + e.message + '\n';
}
}
results.textContent += '\n' + tests + ' tests, ' + failures + ' failures\n';
window.mochaResults = { passes: tests - failures, failures: failures };
});
</script>
<script>
onload = function(){
require(['handlebars'], function(Handlebars) {
window.Handlebars = Handlebars;
require(['tests'], function() {
mocha.globals(['mochaResults'])
// The test harness leaks under FF. We should have decent global leak coverage from other tests
if (!navigator.userAgent.match(/Firefox\/([\d.]+)/)) {
mocha.checkLeaks();
}
var runner = mocha.run();
// Reporting to test-runner
var failedTests = [];
runner.on('end', function(){
window.mochaResults = runner.stats;
window.mochaResults.reports = failedTests;
});
runner.on('fail', logFailure);
function logFailure(test, err){
var flattenTitles = function(test){
var titles = [];
while (test.parent.title){
titles.push(test.parent.title);
test = test.parent;
}
return titles.reverse();
};
failedTests.push({
name: test.title,
result: false,
message: err.message,
stack: err.stack,
titles: flattenTitles(test)
});
};
});
});
};
</script>
</head>
<body>
<div id="mocha"></div>
</body>
</html>
+6 -6
View File
@@ -89,18 +89,18 @@ describe('utils', function () {
describe('#isType', function () {
it('should check if variable is type Array', function () {
expect(Handlebars.Utils.isArray('string')).to.equal(false);
expect(Handlebars.Utils.isArray([])).to.equal(true);
expect(Handlebars.Utils.isArray('string')).toBe(false);
expect(Handlebars.Utils.isArray([])).toBe(true);
});
it('should check if variable is type Map', function () {
expect(Handlebars.Utils.isMap('string')).to.equal(false);
expect(Handlebars.Utils.isMap(new Map())).to.equal(true);
expect(Handlebars.Utils.isMap('string')).toBe(false);
expect(Handlebars.Utils.isMap(new Map())).toBe(true);
});
it('should check if variable is type Set', function () {
expect(Handlebars.Utils.isSet('string')).to.equal(false);
expect(Handlebars.Utils.isSet(new Set())).to.equal(true);
expect(Handlebars.Utils.isSet('string')).toBe(false);
expect(Handlebars.Utils.isSet(new Set())).toBe(true);
});
});
});