1

我目前正在使用 busted/luassert 编写一个测试套件,并且由于我将一些断言放在一个单独的函数中,所以我得到了不准确的堆栈跟踪。例如,考虑以下测试套件 (a_spec.lua):

local function my_custom_assertion(x)     --  1
   assert.is_true(x > 0)                  --  2 <- 
end                                       --  3
                                          --  4
describe("My test suite", function()      --  5
    it("they are positive", function()    --  6
        my_custom_assertion(-10)          --  7 <-
        my_custom_assertion(-20)          --  8 <-
    end)                                  --  9
end)                                      -- 10

当我运行它时,我的测试用例失败了,但堆栈跟踪指向第 2 行,所以我不知道这两个断言中的哪一个是失败的。

$busted spec/a_spec.lua 
◼
0 successes / 1 failure / 0 errors / 0 pending : 0.002242 seconds

Failure → spec/a_spec.lua @ 6
My test suite they are positive
spec/a_spec.lua:2: Expected objects to be the same.
Passed in:
(boolean) false
Expected:
(boolean) true

有没有办法让它指向第 7 行或第 8 行?一种可能的方法是,如果 luassert 的 assert.is_true 函数具有类似于内置错误函数的级别参数。

查看 luassert 的源代码,它似乎确实关心堆栈级别,但我无法弄清楚这个功能是内部的还是以某种方式暴露给用户的。

4

2 回答 2

1

与其通过创建调用的函数来创建自定义断言,不如assert.xyzz()创建一个返回truefalse注册的函数assert:register

请参阅README中的第二个示例。

于 2017-11-30T23:51:42.283 回答
0

事实证明,有一种方法可以解决我的实际问题,即找出哪些断言是触发的,而无需更改我编写测试的方式。通过调用busted( ) 选项-v--verbose它会在断言失败时打印完整的堆栈跟踪,而不是仅提供单个行号。

$ busted -v spec/a_spec.lua

0 successes / 1 failure / 0 errors / 0 pending : 0.003241 seconds

Failure → spec/a_spec.lua @ 6
My test suite they are positive
spec/a_spec.lua:2: Expected objects to be the same.
Passed in:
(boolean) false
Expected:
(boolean) true

stack traceback:
    spec/a_spec.lua:2: in upvalue 'my_custom_assertion'
    spec/a_spec.lua:7: in function <spec/a_spec.lua:6>

提到第 7 行让我知道失败的断言是什么。

于 2017-12-03T04:56:54.647 回答