lunarmodules / luassert

Assertion library for Lua
MIT License
202 stars 77 forks source link

fix(assert) prevent assert() to crash when level is given #141

Closed thibaultcha closed 7 years ago

thibaultcha commented 7 years ago

When commonly using the Lua idiom:

local result = assert(some_method())

in tests written with busted, it happens that some_method() might return more than 2 values: a boolean, a string and something else. However, if the assertion fails because ret #1 is falsy, and if ret #3 is not a number, the actual error (ret #2) would be supersed with:

luassert/assert.lua:155: attempt to perform arithmetic on a string value

This can be annoying to debug (temporarily remove the ret #3 value from some_method() or caching the return values before calling assert()) just in order to see what the actual error is.

This proposes to check that level is a number before trying to perform arithmetic on it, and provide another variable with a default of 2 in case not. The only drawback is that if ret #3 already is a number, we might get a wrong level. That is probably less likely than the above happening, it has been quite common in our tests.

Tieske commented 7 years ago

It'd be nicer if all types could be caught properly. If using a table as the level value (with a custom metatable to detect it's a level value) it will also handle numbers properly.

Would require an extra function call to create the type. eg;

assert(test, "error message", assert.level(3))
Tieske commented 7 years ago

as #144 was merged, this can be closed now.