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

Almost equal assertions #36

Merged
merged 1 commit into from
Apr 24, 2012
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions lib/interface/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,34 @@ module.exports = function (chai) {
new Assertion(val, msg).is.ok;
};


/**
* # .almostEqual(actual, expected, [decimal, message])
*
* The same as NumPy's assert_almost_equal, for scalars.
* Assert near equality: abs(expected-actual) < 0.5 * 10**(-decimal)
*
* assert.almostEqual(3.1416, 3.14159, 3, 'these numbers are almost equal');
*
* @name equal
* @param {Number} actual
* @param {Number} expected
* @param {Number} decimal
* @param {String} message
* @api public
*/

assert.almostEqual = function(act, exp, dec, msg) {
var test = new Assertion(act, msg);
dec = dec || 7

test.assert(
Math.abs(test.obj - exp) < 0.5 * Math.pow(10, -dec)
, 'expected ' + test.inspect + ' to equal ' + inspect(exp) + ' up to ' + inspect(dec) + ' decimal places'
, 'expected ' + test.inspect + ' to not equal ' + inspect(exp) + ' up to ' + inspect(dec) + ' decimal places')
};


/**
* # .equal(actual, expected, [message])
*
Expand Down Expand Up @@ -158,6 +186,47 @@ module.exports = function (chai) {
assert.deepEqual = function (act, exp, msg) {
new Assertion(act, msg).to.eql(exp);
};

/**
* # .deepAlmostEqual(actual, expected, [decimal, message])
*
* The same as NumPy's assert_almost_equal, for objects whose leaves are all numbers.
* Assert near equality: abs(expected-actual) < 0.5 * 10**(-decimal) for every leaf
*
* assert.almostEqual({pi: 3.1416}, {pi: 3.14159}, 3);
*
* @name equal
* @param {*} actual
* @param {*} expected
* @param {Number} decimal
* @param {String} message
* @api public
*/

assert.deepAlmostEqual = function(act, exp, dec, msg) {
var test = new Assertion(act, msg);
dec = dec || 7;
var tol = 0.5 * Math.pow(10, -dec);

var deepEq = function(act, exp) {
if (Object(act) === act){
for (var k in act) {
if (!(deepEq(act[k], exp[k]))) {
return false;
}
}
return true;
}
else {
return Math.abs(act - exp) < tol;
}
};

test.assert(
deepEq(test.obj, exp)
, 'expected ' + test.inspect + ' to equal ' + inspect(exp) + ' up to ' + inspect(dec) + ' decimal places'
, 'expected ' + test.inspect + ' to not equal ' + inspect(exp) + ' up to ' + inspect(dec) + ' decimal places')
};

/**
* # .notDeepEqual(actual, expected, [message])
Expand Down