這篇文章將為大家詳細(xì)講解有關(guān)pytest如何編寫(xiě)斷言,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
在綏芬河等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場(chǎng)前瞻性、產(chǎn)品創(chuàng)新能力,以專(zhuān)注、極致的服務(wù)理念,為客戶(hù)提供成都網(wǎng)站制作、網(wǎng)站設(shè)計(jì) 網(wǎng)站設(shè)計(jì)制作定制設(shè)計(jì),公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站制作,全網(wǎng)整合營(yíng)銷(xiāo)推廣,成都外貿(mào)網(wǎng)站建設(shè),綏芬河網(wǎng)站建設(shè)費(fèi)用合理。編寫(xiě)斷言
使用assert編寫(xiě)斷言
pytest允許你使用python標(biāo)準(zhǔn)的assert表達(dá)式寫(xiě)斷言;
例如,你可以這樣做:
# test_sample.py def func(x): return x + 1 def test_sample(): assert func(3) == 5
如果這個(gè)斷言失敗,你會(huì)看到func(3)實(shí)際的返回值:
/d/Personal Files/Python/pytest-chinese-doc/src (5.1.2) λ pytest test_sample.py ================================================= test session starts ================================================= platform win32 -- Python 3.7.3, pytest-5.1.2, py-1.8.0, pluggy-0.12.0 rootdir: D:\Personal Files\Python\pytest-chinese-doc\src, inifile: pytest.ini collected 1 item test_sample.py F [100%] ====================================================== FAILURES ======================================================= _____________________________________________________ test_sample _____________________________________________________ def test_sample(): > assert func(3) == 5 E assert 4 == 5 E + where 4 = func(3) test_sample.py:28: AssertionError ================================================== 1 failed in 0.05s ==================================================
pytest支持顯示常見(jiàn)的python子表達(dá)式的值,包括:調(diào)用、屬性、比較、二進(jìn)制和一元運(yùn)算符等(參考pytest支持的python失敗時(shí)報(bào)告的演示);
這允許你在沒(méi)有模版代碼參考的情況下,可以使用的python的數(shù)據(jù)結(jié)構(gòu),而無(wú)須擔(dān)心丟失自省的問(wèn)題;
同時(shí),你也可以為斷言指定了一條說(shuō)明信息,用于失敗時(shí)的情況說(shuō)明:
assert a % 2 == 0, "value was odd, should be even"
編寫(xiě)觸發(fā)期望異常的斷言
你可以使用pytest.raises()作為上下文管理器,來(lái)編寫(xiě)一個(gè)觸發(fā)期望異常的斷言:
import pytest def myfunc(): raise ValueError("Exception 123 raised") def test_match(): with pytest.raises(ValueError): myfunc()
當(dāng)用例沒(méi)有返回ValueError或者沒(méi)有異常返回時(shí),斷言判斷失敗;
如果你希望同時(shí)訪問(wèn)異常的屬性,可以這樣:
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的一個(gè)實(shí)例,它封裝了異常的信息;常用的屬性包括:.type、.value和.traceback;
注意:在上下文管理器的作用域中,raises代碼必須是最后一行,否則,其后面的代碼將不會(huì)執(zhí)行;所以,如果上述例子改成:
def test_match(): with pytest.raises(ValueError) as excinfo: myfunc() assert '456' in str(excinfo.value)
則測(cè)試將永遠(yuǎn)成功,因?yàn)閍ssert '456' in str(excinfo.value)并不會(huì)執(zhí)行;
你也可以給pytest.raises()傳遞一個(gè)關(guān)鍵字參數(shù)match,來(lái)測(cè)試異常的字符串表示str(excinfo.value)是否符合給定的正則表達(dá)式(和unittest中的TestCase.assertRaisesRegexp方法類(lèi)似):
import pytest def myfunc(): raise ValueError("Exception 123 raised") def test_match(): with pytest.raises((ValueError, RuntimeError), match=r'.* 123 .*'): myfunc()
pytest實(shí)際調(diào)用的是re.search()方法來(lái)做上述檢查;并且,pytest.raises()也支持檢查多個(gè)期望異常(以元組的形式傳遞參數(shù)),我們只需要觸發(fā)其中任意一個(gè);
pytest.raises還有另外的一種使用形式:
首先,我們來(lái)看一下它在源碼中的定義:
# _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]]]:
它接收一個(gè)位置參數(shù)expected_exception,一組可變參數(shù)args,一個(gè)關(guān)鍵字參數(shù)match和一組關(guān)鍵字參數(shù)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如果存在,那么它的第一個(gè)參數(shù)必須是一個(gè)可調(diào)用的對(duì)象,否則會(huì)報(bào)TypeError異常;同時(shí),它會(huì)把剩余的args參數(shù)和所有kwargs參數(shù)傳遞給這個(gè)可調(diào)用對(duì)象,然后檢查這個(gè)對(duì)象執(zhí)行之后是否觸發(fā)指定異常;
所以我們有了一種新的寫(xiě)法:
pytest.raises(ZeroDivisionError, lambda x: 1/x, 0) # 或者 pytest.raises(ZeroDivisionError, lambda x: 1/x, x=0)
這個(gè)時(shí)候如果你再傳遞match參數(shù),是不生效的,因?yàn)樗挥性趇f not args:的時(shí)候生效;
另外,pytest.mark.xfail()也可以接收一個(gè)raises參數(shù),來(lái)判斷用例是否因?yàn)橐粋€(gè)具體的異常而導(dǎo)致失?。?/p>
@pytest.mark.xfail(raises=IndexError) def test_f(): f()
如果f()觸發(fā)一個(gè)IndexError異常,則用例標(biāo)記為xfailed;如果沒(méi)有,則正常執(zhí)行f();
注意:如果f()測(cè)試成功,用例的結(jié)果是xpassed,而不是passed;
pytest.raises適用于檢查由代碼故意引發(fā)的異常;而@pytest.mark.xfail()更適合用于記錄一些未修復(fù)的Bug;
特殊數(shù)據(jù)結(jié)構(gòu)比較時(shí)的優(yōu)化
# 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
上面,我們檢查了三種數(shù)據(jù)結(jié)構(gòu)的比較:集合、字符串和字典;
/d/Personal Files/Python/pytest-chinese-doc/src (5.1.2) λ pytest test_special_compare.py ================================================= test session starts ================================================= platform win32 -- Python 3.7.3, pytest-5.1.2, py-1.8.0, pluggy-0.12.0 rootdir: D:\Personal Files\Python\pytest-chinese-doc\src, inifile: pytest.ini collected 3 items 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 Use -v to get the full diff 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 ? ^ ^ ^ 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 Use -v to get the full diff test_special_compare.py:44: AssertionError ================================================== 3 failed in 0.09s ==================================================
針對(duì)一些特殊的數(shù)據(jù)結(jié)構(gòu)間的比較,pytest對(duì)結(jié)果的顯示做了一些優(yōu)化:
集合、列表等:標(biāo)記出第一個(gè)不同的元素;
字符串:標(biāo)記出不同的部分;
字典:標(biāo)記出不同的條目;
更多例子參考pytest支持的python失敗時(shí)報(bào)告的演示
為失敗斷言添加自定義的說(shuō)明
# 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
我們定義了一個(gè)Foo對(duì)象,也復(fù)寫(xiě)了它的__eq__()方法,但當(dāng)我們執(zhí)行這個(gè)用例時(shí):
/d/Personal Files/Python/pytest-chinese-doc/src (5.1.2) λ pytest test_foo_compare.py ================================================= test session starts ================================================= platform win32 -- Python 3.7.3, pytest-5.1.2, py-1.8.0, pluggy-0.12.0 rootdir: D:\Personal Files\Python\pytest-chinese-doc\src, inifile: pytest.ini collected 1 item 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 <src.test_foo_compare.Foo object at 0x0000020E90C4E978> == <src.test_foo_compare.Foo object at 0x0000020E90C4E630> test_foo_compare.py:37: AssertionError ================================================== 1 failed in 0.04s ==================================================
并不能直觀的看出來(lái)失敗的原因;
在這種情況下,我們有兩種方法來(lái)解決:
復(fù)寫(xiě)Foo的__repr__()方法:
def __repr__(self): return str(self.val)
我們?cè)賵?zhí)行用例:
luyao@NJ-LUYAO-T460 /d/Personal Files/Python/pytest-chinese-doc/src (5.1.2) λ pytest test_foo_compare.py ================================================= test session starts ================================================= platform win32 -- Python 3.7.3, pytest-5.1.2, py-1.8.0, pluggy-0.12.0 rootdir: D:\Personal Files\Python\pytest-chinese-doc\src, inifile: pytest.ini collected 1 item 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 test_foo_compare.py:37: AssertionError ================================================== 1 failed in 0.06s ==================================================
這時(shí),我們能看到失敗的原因是因?yàn)? == 2不成立;
至于__str__()和__repr__()的區(qū)別,可以參考StackFlow上的這個(gè)問(wèn)題中的回答:https://stackoverflow.com/questions/1436703/difference-between-str-and-repr
使用pytest_assertrepr_compare這個(gè)鉤子方法添加自定義的失敗說(shuō)明
# conftest.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 [ "比較兩個(gè)Foo實(shí)例:", # 頂頭寫(xiě)概要 " 值: {} != {}".format(left.val, right.val), # 除了第一個(gè)行,其余都可以縮進(jìn) ]
再次執(zhí)行:
/d/Personal Files/Python/pytest-chinese-doc/src (5.1.2) λ pytest test_foo_compare.py ================================================= test session starts ================================================= platform win32 -- Python 3.7.3, pytest-5.1.2, py-1.8.0, pluggy-0.12.0 rootdir: D:\Personal Files\Python\pytest-chinese-doc\src, inifile: pytest.ini collected 1 item 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 比較兩個(gè)Foo實(shí)例: E 值: 1 != 2 test_foo_compare.py:37: AssertionError ================================================== 1 failed in 0.05s ==================================================
我們會(huì)看到一個(gè)更友好的失敗說(shuō)明;
關(guān)于斷言自省的細(xì)節(jié)
當(dāng)斷言失敗時(shí),pytest為我們提供了非常人性化的失敗說(shuō)明,中間往往夾雜著相應(yīng)變量的自省信息,這個(gè)我們稱(chēng)為斷言的自??;
那么,pytest是如何做到這樣的:
pytest發(fā)現(xiàn)測(cè)試模塊,并引入他們,與此同時(shí),pytest會(huì)復(fù)寫(xiě)斷言語(yǔ)句,添加自省信息;但是,不是測(cè)試模塊的斷言語(yǔ)句并不會(huì)被復(fù)寫(xiě);
復(fù)寫(xiě)緩存文件
pytest會(huì)把被復(fù)寫(xiě)的模塊存儲(chǔ)到本地作為緩存使用,你可以通過(guò)在測(cè)試用例的根文件夾中的conftest.py里添加如下配置:
import sys sys.dont_write_bytecode = True
來(lái)禁止這種行為;
但是,它并不會(huì)妨礙你享受斷言自省的好處,只是不會(huì)在本地存儲(chǔ).pyc文件了。
去使能斷言自省
你可以通過(guò)一下兩種方法:
在需要去使能模塊的docstring中添加PYTEST_DONT_REWRITE字符串;
執(zhí)行pytest時(shí),添加--assert=plain選項(xiàng);
我們來(lái)看一下去使能后的效果:
/d/Personal Files/Python/pytest-chinese-doc/src (5.1.2) λ pytest test_foo_compare.py --assert=plain ================================================= test session starts ================================================= platform win32 -- Python 3.7.3, pytest-5.1.2, py-1.8.0, pluggy-0.12.0 rootdir: D:\Personal Files\Python\pytest-chinese-doc\src, inifile: pytest.ini collected 1 item 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 test_foo_compare.py:37: AssertionError ================================================== 1 failed in 0.05s ==================================================
斷言失敗時(shí)的信息就非常的不完整了,我們幾乎看不出任何有用的Debug信息;
關(guān)于“pytest如何編寫(xiě)斷言”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
標(biāo)題名稱(chēng):pytest如何編寫(xiě)斷言-創(chuàng)新互聯(lián)
文章位置:http://jinyejixie.com/article20/dhdpco.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開(kāi)發(fā)、微信小程序、電子商務(wù)、網(wǎng)站營(yíng)銷(xiāo)、移動(dòng)網(wǎng)站建設(shè)、標(biāo)簽優(yōu)化
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容
全網(wǎng)營(yíng)銷(xiāo)推廣知識(shí)