diff --git a/README.md b/README.md index 0d670a2..6ffa228 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,27 @@ AssertionError: bar > 10 at Object.oncomplete (fs.js:297:15) ``` +## assert.equal + +Asserts that two values are non-strictly equal (i.e. uses `==` to compare). + +```js +var foo = 15, bar = "banana" +assert.equal(foo, "15") // OK +assert.equal(foo, bar) // Throws error: + // AssertionError: assert.equal: foo, bar (15 != 'banana') +``` + +## assert.strictEqual + +Asserts that two values are strictly equal (i.e. uses `===` to compare). + +```js +var foo = 15, bar = "15" +assert.strictEqual(foo, bar) // Throws error: + // AssertionError: assert.strictequal: foo, bar (15 !== 15') +``` + ## License (BSD) Copyright (c) 2013, Johan Sköld <johan@skold.cc> @@ -92,4 +113,4 @@ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/index.js b/index.js index b9d5ee5..dc525df 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,7 @@ var callsite = require('callsite') , fs = require('fs') , path = require('path') + , util = require('util') , AssertionError = require('assert').AssertionError /** @@ -15,20 +16,45 @@ module.exports = (process.env.NODE_ENV === 'production') * Asserts that `expression` is true. */ +function fail(extraMessage) { + var stack = callsite() + , file = stack[2].getFileName() + , line = stack[2].getLineNumber() + , message = getAssertionExpression(file, line) + + if (fail.caller !== assert) + message = "assert." + fail.caller.name + ": " + message + + if (extraMessage) + message += " (" + extraMessage + ")" + + var err = new AssertionError({ + message: message, + stackStartFunction: stack[1].getFunction() + }) + + throw err +} + function assert(expression) { if (expression) return - var stack = callsite() - , file = stack[1].getFileName() - , line = stack[1].getLineNumber() + fail() +} - var err = new AssertionError({ - message: getAssertionExpression(file, line), - stackStartFunction: stack[0].getFunction() - }) +assert.equal = function equal(x, y) +{ + if (x == y) return + + fail(util.format("%s != %s", util.inspect(x), util.inspect(y))) +} + +assert.strictEqual = function strictEqual(x, y) +{ + if (x === y) return - throw err + fail(util.format("%s !== %s", util.inspect(x), util.inspect(y))) } /** @@ -51,7 +77,7 @@ function getAssertionExpression(file, lineno) break } - return line.match(/assert\s*\((.*)\)/)[1] + return line.match(/assert(?:\.\w+)?\s*\((.*)\)/)[1] } /**