Skip to content

Commit

Permalink
Merge pull request #395 from cjqed/386-assert-operator-no-eval
Browse files Browse the repository at this point in the history
No longer using eval on assert operator #386
  • Loading branch information
keithamus committed Mar 8, 2015
2 parents 4b33fe3 + da2ec4a commit 83a9e56
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 6 deletions.
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

0 comments on commit 83a9e56

Please sign in to comment.