【问题标题】:How can you suppress traces for failed test cases using Nose?如何使用 Nose 抑制失败测试用例的跟踪?
【发布时间】:2012-07-10 16:12:18
【问题描述】:

我正在编写一个带鼻子的测试服,并希望失败的案例显示类似的输出

“失败:is_even(5):不偶数”

而不是默认输出:

======================================================================
FAIL: seed_db.test_generator(5,)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/nose/case.py", line 197, in runTest
    self.test(*self.arg)
  File "/home/apurcell/tests/prism/seed_db.py", line 59, in is_even
    nose.tools.eq_(x % 2, 0, msg="Not even")
  File "/usr/local/lib/python2.7/dist-packages/nose/tools.py", line 31, in eq_
    assert a == b, msg or "%r != %r" % (a, b)
    AssertionError: Not even

----------------------------------------------------------------------

鼻子有什么选择吗?

【问题讨论】:

    标签: python testing nose nosetests


    【解决方案1】:

    以下输出与您想要的类似但不完全相同(它还会更改成功的测试输出,这可能不是您想要的)。它使用 tap.py 输出 TAP(测试任何协议)而不是通常的 unittest 输出。

    nosetests --with-tap --tap-stream testcases-rsysflow.py
    

    输出如下:

    bjb@rhino$ nosetests testcases-rrrr.py --with-tap --tap-stream
    # TAP results for TestThing
    ok 1 - test_create_and_get (testcases-rrrr.TestThing)
    ok 2 - test_del_one (testcases-rrrr.TestThing)
    ok 3 - test_get_all (testcases-rrrr.TestThing)
    not ok 4 - test_get_not_exist (testcases-rrrr.TestThing)
    ok 5 - test_get_wrong_indir (testcases-rrrr.TestThing)
    ok 6 - test_replace_and_get (testcases-rrrr.TestThing)
    ok 7 - test_set_should_fail (testcases-rrrr.TestThing)
    1..7
    

    使用测试任何协议(我说的是协议,而不是这个特定的实现),您可以在错误破折号后输出诊断信息 - 但我不知道如何使用这个实现来做到这一点。

    这个实现很方便,因为我只需要安装 tap.py (pip install tap.py) 并将这两个命令行参数放在我的 unittest 测试的鼻子测试调用上,然后 poof - TAP 格式的输出。现在可以将其插入 Jenkins。

    【讨论】:

      【解决方案2】:

      如果你想改变鼻子的行为,你应该写一个插件(see API documentation here)。就您而言,听起来您想更改报告错误的方式,因此您需要提供formatError()formatFailure()。可能您想编辑异常消息(包括行号),并限制回溯的大小。

      【讨论】:

        【解决方案3】:

        一种可能的解决方案是将错误流重定向到类似对象的流中,并在那里处理不同的输出。这可能类似于以下代码 sn-p:

        import sys
        
        class MyErrorStream():
            def write(self, txt):
                # Do something if
                # output contains
                # special exception
                altered_txt = 'My special exception is:\n' + txt
        
                sys.__stderr__.write(altered_txt)
        
        if(__name__ == '__main__'):
            error_stream = MyErrorStream()
            sys.stderr = error_stream
        
            assert(1 == 0)
        

        但是这个解决方案不是最好的。改变堆栈跟踪的另一种方法是修改处理输出的内部鼻子类。您可以对其进行子类化并覆盖/扩展创建输出文本的方法。因为我没有使用鼻子,所以我不能给出最小的代码 sn-p。 不过还是希望能帮到你。

        【讨论】:

        • 有人找到解决办法了吗?
        猜你喜欢
        • 2015-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-04
        • 2021-01-29
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        相关资源
        最近更新 更多