bluebird75 / luaunit

LuaUnit is a popular unit-testing framework for Lua, with an interface typical of xUnit libraries (Python unittest, Junit, NUnit, ...). It supports several output formats (Text, TAP, JUnit, ...) to be used directly or work with Continuous Integration platforms (Jenkins, Maven, ...).
Other
572 stars 137 forks source link

assert for function returning, nil/msg? #139

Closed jjvbsag closed 3 years ago

jjvbsag commented 3 years ago

Lua has a convention for functions to return nil and an error string in case of problems. Is there an assert for this? If not, how would you implement it?

Example:

    local ok,msg=output:set(-2)
    assertEquals("invalid value",msg)
    assertIsNil(ok)

I'd prefer something like

    assertNilMsg("invalid value",output:set(-2))

I tried by myself with

local function assertNilMsg(want,ok,msg)
    assertEquals(want,msg)
    assertIsNil(ok)
end

but in error case I get the wrong line in the test results

Failed tests:
-------------
1) TestLuaunitNilMsg.test3
/opt/unittest/luaunit-nil-msg.lua:17: expected: "good value"

Line 17 is my assertNilMsg and not the test case

bluebird75 commented 3 years ago

Hi,

It's easy to write your own assert functions. Just look on how luaunit write them. For example, here the code for assertIsNil() 👍

function M.assertIsNil(value, extra_msg_or_nil)
    if value ~= nil then
        failure("expected: nil, actual: " ..prettystr(value), extra_msg_or_nil, 2)
    end
end

In your case, this should be something along the lines of :

local function assertNilMsg(want,ok,msg)
    if ok ~= nil or want ~= msg   then
        failure("Expected: nil with msg '"..want.."', got "..prettystr(ok).." with msg '"..msg.."'", nil, 2)
    end
end

A few advices : it is better to always show what you expected and what you actually got in the same message. The failure() function will take care of generating the proper error.

jjvbsag commented 3 years ago

Thank you. You code will throw an error, is msg is nil, so I changed it to


function M.assertNilMsg(want,ok,msg)
    if ok ~= nil or want ~= msg   then
        failure("Expected: nil with msg "..prettystr(want)..", got "..prettystr(ok).." with msg "..prettystr(msg), nil, 2)
    end
end

But thanks for the inspiration. Regards