Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

No longer using eval on assert operator #386 #395

Merged
merged 1 commit into from Mar 8, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 29 additions & 3 deletions lib/chai/interface/assert.js
Expand Up @@ -1004,10 +1004,36 @@ module.exports = function (chai, util) {
*/

assert.operator = function (val, operator, val2, msg) {
if (!~['==', '===', '>', '>=', '<', '<=', '!=', '!=='].indexOf(operator)) {
throw new Error('Invalid operator "' + operator + '"');
var ok;
switch(operator) {
case '==':
ok = val == val2;
break;
case '===':
ok = val === val2;
break;
case '>':
ok = val > val2;
break;
case '>=':
ok = val >= val2;
break;
case '<':
ok = val < val2;
break;
case '<=':
ok = val <= val2;
break;
case '!=':
ok = val != val2;
break;
case '!==':
ok = val !== val2;
break;
default:
throw new Error('Invalid operator "' + operator + '"');
}
var test = new Assertion(eval(val + operator + val2), msg);
var test = new Assertion(ok, msg);
test.assert(
true === flag(test, 'object')
, 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2)
Expand Down
23 changes: 20 additions & 3 deletions test/assert.js
Expand Up @@ -556,13 +556,20 @@ describe('assert', function () {
});

it('operator', function() {
// For testing undefined and null with == and ===
var w;

assert.operator(1, '<', 2);
assert.operator(2, '>', 1);
assert.operator(1, '==', 1);
assert.operator(1, '<=', 1);
assert.operator(1, '>=', 1);
assert.operator(1, '!=', 2);
assert.operator(1, '!==', 2);
assert.operator(1, '!==', '1');
assert.operator(w, '==', undefined);
assert.operator(w, '===', undefined);
assert.operator(w, '==', null);

err(function () {
assert.operator(1, '=', 2);
Expand All @@ -579,6 +586,10 @@ describe('assert', function () {
err(function () {
assert.operator(1, '==', 2);
}, "expected 1 to be == 2");

err(function () {
assert.operator(1, '===', '1');
}, "expected 1 to be === \'1\'");

err(function () {
assert.operator(2, '<=', 1);
Expand All @@ -591,10 +602,16 @@ describe('assert', function () {
err(function () {
assert.operator(1, '!=', 1);
}, "expected 1 to be != 1");


err(function () {
assert.operator(1, '!==', 1);
}, "expected 1 to be !== 1");

err(function () {
assert.operator(1, '!==', '1');
}, "expected 1 to be !== \'1\'");
assert.operator(w, '===', null);
}, "expected undefined to be === null");


});

it('closeTo', function(){
Expand Down