目录html
assert
编写断言pytest
容许你使用python
标准的assert
表达式写断言;python
例如,你能够这样作:git
# src/chapter-3/test_sample.py def func(x): return x + 1 def test_sample(): assert func(3) == 5
若是这个断言失败,你会看到func(3)
实际的返回值+ where 4 = func(3)
:github
$ pipenv run pytest -q src/chapter-3/test_sample.py F [100%] =============================== FAILURES ================================ ______________________________ test_sample ______________________________ def test_sample(): > assert func(3) == 5 E assert 4 == 5 E + where 4 = func(3) src/chapter-3/test_sample.py:28: AssertionError 1 failed in 0.05s
pytest
支持显示常见的python
子表达式的值,包括:调用、属性、比较、二进制和一元运算符等(能够参考这个例子 );正则表达式
这容许你在没有模版代码参考的状况下,可使用的python
的数据结构,而无须担忧自省丢失的问题;api
同时,你也能够为断言指定了一条说明信息,用于失败时的状况说明:缓存
assert a % 2 == 0, "value was odd, should be even"
你可使用pytest.raises()
做为上下文管理器,来编写一个触发指望异常的断言:bash
import pytest def myfunc(): raise ValueError("Exception 123 raised") def test_match(): with pytest.raises(ValueError): myfunc()
当用例没有返回ValueError
或者没有异常返回时,断言判断失败;数据结构
若是你但愿同时访问异常的属性,能够这样:ide
import pytest def myfunc(): raise ValueError("Exception 123 raised") def test_match(): with pytest.raises(ValueError) as excinfo: myfunc() assert '123' in str(excinfo.value)
其中,excinfo
是ExceptionInfo
的一个实例,它封装了异常的信息;经常使用的属性包括:.type
、.value
和.traceback
;
注意:
在上下文管理器的做用域中,
raises
代码必须是最后一行,不然,其后面的代码将不会执行;因此,若是上述例子改为:def test_match(): with pytest.raises(ValueError) as excinfo: myfunc() assert '456' in str(excinfo.value)则测试将永远成功,由于
assert '456' in str(excinfo.value)
并不会执行;
你也能够给pytest.raises()
传递一个关键字参数match
,来测试异常的字符串表示str(excinfo.value)
是否符合给定的正则表达式(和unittest
中的TestCase.assertRaisesRegexp
方法相似):
import pytest def myfunc(): raise ValueError("Exception 123 raised") def test_match(): with pytest.raises((ValueError, RuntimeError), match=r'.* 123 .*'): myfunc()
pytest实际调用的是re.search()
方法来作上述检查;而且,pytest.raises()
也支持检查多个指望异常(以元组的形式传递参数),咱们只须要触发其中任意一个;
pytest.raises
还有另外的一种使用形式:
首先,咱们来看一下它在源码中的定义:
# _pytest/python_api.py def raises( # noqa: F811 expected_exception: Union["Type[_E]", Tuple["Type[_E]", ...]], *args: Any, match: Optional[Union[str, "Pattern"]] = None, **kwargs: Any ) -> Union["RaisesContext[_E]", Optional[_pytest._code.ExceptionInfo[_E]]]:
它接收一个位置参数expected_exception
,一组可变参数args
,一个关键字参数match
和一组关键字参数kwargs
;
接着看方法的具体内容:
# _pytest/python_api.py if not args: if kwargs: msg = "Unexpected keyword arguments passed to pytest.raises: " msg += ", ".join(sorted(kwargs)) msg += "\nUse context-manager form instead?" raise TypeError(msg) return RaisesContext(expected_exception, message, match) else: func = args[0] if not callable(func): raise TypeError( "{!r} object (type: {}) must be callable".format(func, type(func)) ) try: func(*args[1:], **kwargs) except expected_exception as e: # We just caught the exception - there is a traceback. assert e.__traceback__ is not None return _pytest._code.ExceptionInfo.from_exc_info( (type(e), e, e.__traceback__) ) fail(message)
其中,args
若是存在,那么它的第一个参数必须是一个可调用的对象,不然会报TypeError
异常;
同时,它会把剩余的args
参数和全部kwargs
参数传递给这个可调用对象,而后检查这个对象执行以后是否触发指定异常;
因此咱们有了一种新的写法:
pytest.raises(ZeroDivisionError, lambda x: 1/x, 0) # 或者 pytest.raises(ZeroDivisionError, lambda x: 1/x, x=0)
这个时候若是你再传递match
参数,是不生效的,由于它只有在if not args:
的时候生效;
pytest.mark.xfail()
也能够接收一个raises
参数,来判断用例是否由于一个具体的异常而致使失败:
@pytest.mark.xfail(raises=IndexError) def test_f(): f()
若是f()
触发一个IndexError
异常,则用例标记为xfailed
;若是没有,则正常执行f()
;
注意:
若是
f()
测试成功,用例的结果是xpassed
,而不是passed
;
pytest.raises
适用于检查由代码故意引起的异常;而@pytest.mark.xfail()
更适合用于记录一些未修复的Bug
;
# src/chapter-3/test_special_compare.py def test_set_comparison(): set1 = set('1308') set2 = set('8035') assert set1 == set2 def test_long_str_comparison(): str1 = 'show me codes' str2 = 'show me money' assert str1 == str2 def test_dict_comparison(): dict1 = { 'x': 1, 'y': 2, } dict2 = { 'x': 1, 'y': 1, } assert dict1 == dict2
上面,咱们检查了三种数据结构的比较:集合、字符串和字典;
$ pipenv run pytest -q src/chapter-3/test_special_compare.py FFF [100%] =============================== FAILURES ================================ __________________________ test_set_comparison __________________________ def test_set_comparison(): set1 = set('1308') set2 = set('8035') > assert set1 == set2 E AssertionError: assert {'0', '1', '3', '8'} == {'0', '3', '5', '8'} E Extra items in the left set: E '1' E Extra items in the right set: E '5' E Full diff: E - {'8', '0', '1', '3'} E + {'8', '3', '5', '0'} src/chapter-3/test_special_compare.py:26: AssertionError _______________________ test_long_str_comparison ________________________ def test_long_str_comparison(): str1 = 'show me codes' str2 = 'show me money' > assert str1 == str2 E AssertionError: assert 'show me codes' == 'show me money' E - show me codes E ? ^ ^ ^ E + show me money E ? ^ ^ ^ src/chapter-3/test_special_compare.py:32: AssertionError _________________________ test_dict_comparison __________________________ def test_dict_comparison(): dict1 = { 'x': 1, 'y': 2, } dict2 = { 'x': 1, 'y': 1, } > assert dict1 == dict2 E AssertionError: assert {'x': 1, 'y': 2} == {'x': 1, 'y': 1} E Omitting 1 identical items, use -vv to show E Differing items: E {'y': 2} != {'y': 1} E Full diff: E - {'x': 1, 'y': 2} E ? ^ E + {'x': 1, 'y': 1}... E E ...Full output truncated (2 lines hidden), use '-vv' to show src/chapter-3/test_special_compare.py:44: AssertionError 3 failed in 0.08s
针对一些特殊的数据结构间的比较,pytest
对结果的显示作了一些优化:
# src/chapter-3/test_foo_compare.py class Foo: def __init__(self, val): self.val = val def __eq__(self, other): return self.val == other.val def test_foo_compare(): f1 = Foo(1) f2 = Foo(2) assert f1 == f2
咱们定义了一个Foo
对象,也复写了它的__eq__()
方法,但当咱们执行这个用例时:
$ pipenv run pytest -q src/chapter-3/test_foo_compare.py F [100%] =============================== FAILURES ================================ ___________________________ test_foo_compare ____________________________ def test_foo_compare(): f1 = Foo(1) f2 = Foo(2) > assert f1 == f2 E assert <test_foo_compare.Foo object at 0x10ecae860> == <test_foo_compare.Foo object at 0x10ecae748> src/chapter-3/test_foo_compare.py:34: AssertionError 1 failed in 0.05s
并不能直观的从中看出来失败的缘由assert <test_foo_compare.Foo object at 0x10ecae860> == <test_foo_compare.Foo object at 0x10ecae748>
;
在这种状况下,咱们有两种方法来解决:
复写Foo
的__repr__()
方法:
def __repr__(self): return str(self.val)
咱们再执行用例:
$ pipenv run pytest -q src/chapter-3/test_foo_compare.py F [100%] =============================== FAILURES ================================ ___________________________ test_foo_compare ____________________________ def test_foo_compare(): f1 = Foo(1) f2 = Foo(2) > assert f1 == f2 E assert 1 == 2 src/chapter-3/test_foo_compare.py:37: AssertionError 1 failed in 0.05s
这时,咱们能看到失败的缘由是由于1 == 2
不成立;
至于
__str__()
和__repr__()
的区别,能够参考StackFlow
上的这个问题中的回答:https://stackoverflow.com/questions/1436703/difference-between-str-and-repr
使用pytest_assertrepr_compare
这个钩子方法添加自定义的失败说明
# src/chapter-3/test_foo_compare.py from .test_foo_compare import Foo def pytest_assertrepr_compare(op, left, right): if isinstance(left, Foo) and isinstance(right, Foo) and op == "==": return [ "比较两个Foo实例:", # 顶头写概要 " 值: {} != {}".format(left.val, right.val), # 除了第一个行,其他均可以缩进 ]
再次执行:
$ pytest -q src/chapter-3/test_foo_compare.py F [100%] =============================== FAILURES ================================ ___________________________ test_foo_compare ____________________________ def test_foo_compare(): f1 = Foo(1) f2 = Foo(2) > assert f1 == f2 E assert 比较两个Foo实例: E 值: 1 != 2 src/chapter-3/test_foo_compare.py:37: AssertionError 1 failed in 0.03s
咱们会看到一个更友好的失败说明;
当断言失败时,pytest
为咱们提供了很是人性化的失败说明,中间每每夹杂着相应变量的自省信息,这个咱们称为断言的自省;
那么,pytest
是如何作到这样的:
pytest
发现测试模块,并引入他们,与此同时,pytest
会复写断言语句,添加自省信息;可是,不是测试模块的断言语句并不会被复写;pytest
会把被复写的模块存储到本地做为缓存使用,你能够经过在测试用例的根文件夹中的conftest.py
里添加以下配置来禁止这种行为;:
import sys sys.dont_write_bytecode = True
可是,它并不会妨碍你享受断言自省的好处,只是不会在本地存储.pyc
文件了。
你能够经过一下两种方法:
docstring
中添加PYTEST_DONT_REWRITE
字符串;--assert=plain
选项;咱们来看一下去使能后的效果:
$ pipenv run pytest -q --assert=plain src/chapter-3/test_foo_compare.py F [100%] =============================== FAILURES ================================ ___________________________ test_foo_compare ____________________________ def test_foo_compare(): f1 = Foo(1) f2 = Foo(2) > assert f1 == f2 E AssertionError src/chapter-3/test_foo_compare.py:37: AssertionError 1 failed in 0.03s
断言失败时的信息就很是的不完整了,咱们几乎看不出任何有用的调试信息;