目錄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
斷言失敗時的信息就很是的不完整了,咱們幾乎看不出任何有用的調試信息;