繁体   English   中英

Python unittest:使 AssertionError 成为错误而不是失败

[英]Python unittest: make AssertionError an error instead of a failure

蟒蛇 2.7。 单元测试文档说:

为了更轻松地迁移现有测试套件,unittest 支持测试引发 AssertionError 以指示测试失败。 但是,建议您改用显式的 TestCase.fail*() 和 TestCase.assert*() 方法,因为 unittest 的未来版本可能会以不同的方式对待 AssertionError。

我在测试代码中使用了很多assert语句,但这些断言的失败应该是测试错误(即“代码没有正确运行这些输入”)而不是失败(即“代码给出了错误的输出”)。

我可以看到以下可能的解决方案:

  1. 重写测试代码以抛出更好类型的异常
  2. 将除测试断言本身( self.assertSomething(...) )之外的所有内容包装在try...except AssertionError: raise SomeOtherException块中
  3. 更改 unittest 的行为,以便它考虑这些错误而不是失败。

选项 1 需要相当长的时间,选项 2 感觉很笨拙; 选项 3 对我来说是最好的,但它可用吗? (以防万一:不,我不能切换到 Python 3。)我在网上看不到任何东西,但是很难使用特定的关键字。

MWE:

import unittest


def add_one_to_int(a):
    assert isinstance(a, int)
    return a + 1


class TestAddOne(unittest.TestCase):
    def test_one_plus_one_is_three(self):
        # This tests fails with
        #   AssertionError: 2 != 3
        # which is fine
        self.assertEqual(add_one_to_int(1), 3)  

    def test_add_one_to_str(self):
        # This tests fails with
        #   AssertionError
        # when I would rather have it an error
        add_one_to_int('some string')

if __name__ == '__main__':
    unittest.main(verbosity=2)  # 2 failures instead of 1 failure, 1 error

我认为选项 3 可以通过类属性“failureException”来实现,正如在 Python 2.7 的 unittest 文档中所定义的:

failureException :此类属性给出了测试方法引发的异常。 如果测试框架需要使用专门的异常,可能携带额外的信息,它必须子类化这个异常,以便与框架“公平竞争”。 该属性的初始值为 AssertionError。

例如:

import unittest

class MyException(Exception): 
    pass

class MyUnitTest(unittest.TestCase):
    failureException = MyException

def add_one_to_int(a):
    assert isinstance(a, int)
    return a + 1


class TestAddOne(MyUnitTest):  # <--------- See above
    def test_one_plus_one_is_three(self):
        # This tests fails with
        #   AssertionError: 2 != 3
        # which is fine
        self.assertEqual(add_one_to_int(1), 3)  

    def test_add_one_to_str(self):
        # This tests fails with
        #   AssertionError
        # when I would rather have it an error
        add_one_to_int('some string')

if __name__ == '__main__':
    unittest.main(verbosity=2)  # ------> FAILED (failures=1, errors=1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM