python - 抑制单元测试中的补充错误消息

标签 python unit-testing python-2.7

我正在使用assertRegexpMatches在我的单元测试中:

self.assertRegexpMatches(text, regexp, msg='custom short message')

问题是unittest将它自己的错误消息添加到msg中指定为参数:

AssertionError: <custom short message>: '<regexp>' not found in '<text>'

由于要匹配的文本很大(~1页),它会弄乱测试报告。有什么方法可以抑制单元测试添加 '<regexp>' not found in '<text>'指定错误消息的一部分?

最佳答案

根据the source code ,只要使用 TestCase.assertRegexpMatches 就不可能抑制该消息。

def assertRegexpMatches(self, text, expected_regexp, msg=None):
    """Fail the test unless the text matches the regular expression."""
    if isinstance(expected_regexp, basestring):
        expected_regexp = re.compile(expected_regexp)
    if not expected_regexp.search(text):
        msg = msg or "Regexp didn't match"
        msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text) #<-
        raise self.failureException(msg)

您需要定义自己的断言方法或使用自定义字符串类,如下所示:

示例(不是漂亮的解决方案,但有效):

import unittest

class CustomString(str):
    # XXX: implementation dependant
    # redefine `__repr__` because `assertRegexpMatches` use `%r`
    def __repr__(self):
        return '<Huge string>'

class TestFoo(unittest.TestCase):
    def test_foo(self):
        self.assertRegexpMatches(CustomString('1234'), 'abcd', msg='custom msg')

if __name__ == '__main__':
    unittest.main()

或使用 re.searchassertTrue:

class TestFoo(unittest.TestCase):
    def test_foo(self):
        self.assertTrue(re.search(regexp, text), msg='custom msg')

关于python - 抑制单元测试中的补充错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21157905/

相关文章:

python - 在具有排除索引的数组中找到最大值

python - 通过维护列表中值的映射顺序来随机化两个列表

python - 为什么我的某些文件在安装使用 setuptools 打包的 python 模块时不可用?

python - 在 urwid 'Frame' 对象中没有属性 'rows'

python - 如何清除列表代理中的内容

unit-testing - 在mockito中验证的想法是什么以及我什么时候应该使用它

c# - 如何故意使所有 C# 单元测试失败

python - 如何在 Windows 中安装 pacparser?

python - 仅在 matplotlib 中的大陆上绘制

java - 测试 Spring @MVC 注解