【问题标题】:Do the assertions in the luassert library have a `level` parameter similar to the builtin `error` function?luassert 库中的断言是否有类似于内置 `error` 函数的`level` 参数?
【发布时间】:2017-11-30 21:54:37
【问题描述】:

我目前正在使用 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 函数具有类似于内置 error 函数的级别参数。

查看 luassert 的源代码,它似乎是 does care about the stack level,但我无法弄清楚这个功能是内部的还是以某种方式暴露给用户的。

【问题讨论】:

    标签: lua lua-busted


    【解决方案1】:

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

    参见README 中的第二个示例。

    【讨论】:

    • 我实际使用的自定义断言函数调用assert.are.same,如果出现错误,它会显示非常有用的不匹配表的打印输出。如果我定义自己的自定义断言函数,有没有办法仍然得到它?
    • util.deepcompare from require ('luassert.util') 完成了大部分艰苦的工作。见github.com/Olivine-Labs/luassert/blob/…
    【解决方案2】:

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

    $ 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 行让我知道失败的断言是什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-08
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 2011-03-27
      • 2014-05-02
      相关资源
      最近更新 更多