亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Pytest斷言的具體使用

 更新時(shí)間:2023年02月07日 09:21:17   作者:cherish1112365  
本文主要介紹了Pytest斷言的具體使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

Pytest使用的斷言是使用python內(nèi)置的斷言assert。Python assert(斷言)用于判斷一個(gè)表達(dá)式,在表達(dá)式條件為 false 的時(shí)候觸發(fā)異常。即pytest測試結(jié)果為False的斷言為斷言失敗即測試用例執(zhí)行失敗,反之為斷言成功即測試用例執(zhí)行成功。

斷言使用場景:

  • 為測試結(jié)果作斷言
  • 為斷言不通過的結(jié)果添加說明信息
  • 為預(yù)期異常作斷言
  • 為失敗斷言作自定義說明信息

assert斷言方法

assert關(guān)鍵字后面接表達(dá)式,常用的assert斷言方法如下:

  • 判斷xx為真:assert xx
  • 判斷xx不為真:assert not xx
  • 判斷b包含a:assert a in b
  • 判斷b不包含a:assert a not in b
  • 判斷a等于b:assert a == b
  • 判斷a不等于b:assert a != b

示例:

# 為測試結(jié)果作斷言
?
import pytest
from func import *
?
class TestFunc:
?def test_add_by_class(self):
? assert add(2,3) == 5
# 為斷言不通過的結(jié)果添加說明信息
?
def test_login():
? ? # 使用python內(nèi)置的斷言
?? ?# "1是不等于2的"是斷言失敗后,拋出異常輸出的自定義提示信息
? ? assert 1 == 2, "1是不等于2的"
? ??
test_login()
?
# 運(yùn)行結(jié)果:
AssertionError: 1是不等于2的

異常斷言Excepiton

異常斷言即為斷言拋出的異常是預(yù)期的異常,執(zhí)行的測試用例是成功的。

使用pytest.raises()作為上下文管理器。當(dāng)拋出異常時(shí),可獲取到對(duì)應(yīng)的異常實(shí)例,然后斷言它拋出的異常是不是預(yù)期的異常。當(dāng)代碼拋出異常時(shí),如果和raises指定的異常類相匹配,則斷言不會(huì)失敗。

官方文檔:How to write and report assertions in tests — pytest documentation

 with pytest.raises()執(zhí)行結(jié)束后會(huì)生成一個(gè)ExceptionInfo的實(shí)例對(duì)象,該對(duì)象包含type , value, traceback屬性。

# 變量存儲(chǔ)該異常的所有信息
with pytest.raises(TypeError) as 變量: 
    # 獲取變量的所有屬性,即type、value、traceback
    print(變量.__dict__)

注意:斷言type的時(shí)候,異常類型是不需要加引號(hào)的。斷言value值的時(shí)候需轉(zhuǎn)換str類型,value屬性可作異常的說明信息。

示例如下:

import pytest
 
def test_zero_division_long():
    with pytest.raises(ZeroDivisionError) as excinfo:
        1 / 0
 
    # 斷言異常類型 type
    assert excinfo.type == ZeroDivisionError
    # 斷言異常 value 值
    assert "division by zero" in str(excinfo.value)

with pytest.raise(ZeroDivisionError)用于對(duì)于故意測試異常代碼的情況(已知異常),斷言通過用例執(zhí)行成功顯示passed,不通過會(huì)顯示failed。

示例如下:

# 為預(yù)期異常作斷言完整示例,執(zhí)行用例為True
 
# ./func.py
def add(a,b):
    if isinstance(a,int) and isinstance(b,int):
        return a+b
    else:
        raise TypeError('數(shù)據(jù)類型錯(cuò)誤')
 
# ./test_case/test_func.py
import pytest
from func import *
 
class TestFunc:
 
 # 正常測試用例
 def test_add_by_class(self):
    assert add(2,3) == 5
 
 # 異常測試用例,期望結(jié)果為拋出TypeError異常
 def test_add_by_func_aaa(self,*args, **kwargs):
    with pytest.raises(TypeError) as E:
        add('3',4)
    print(E.type)
    print(E.value)
    print(E.traceback)  
 
# ./run_test.py
import pytest
 
if __name__ == '__main__':
 pytest.main(['-v'])
# 木有拋出預(yù)期異常的示例,執(zhí)行用例為False
 
# ./func.py
def add(a,b):
 # 指定異常,從此處直接拋出異常
    raise NameError("名稱錯(cuò)誤")
    if isinstance(a,int) and isinstance(b,int):
        return a+b
    else:
        raise TypeError('數(shù)據(jù)類型錯(cuò)誤')
 
# ./test_case/test_func.py
import pytest
from func import *
 
class TestFunc:
    # 異常測試用例,期望結(jié)果為爆出TypeError異常
    def test_add_by_func_aaa(self,*args, **kwargs):
        with pytest.raises(TypeError):
            add('3',4)
  
# ./run_test.py
import pytest
 
if __name__ == '__main__':
 pytest.main(['-v'])

可將match關(guān)鍵字參數(shù)傳遞給上下文管理器pytest.raises(),來測試正則表達(dá)式與異常的信息表達(dá)形式是否匹配。match方法相當(dāng)于re.search功能。

注意:這種方法只能斷言value,不能斷言type。

示例如下:

import pytest
 
def test_zero_division_long():
    with pytest.raises(ZeroDivisionError, match=".*zero.*") as excinfo:
        1 / 0
 
# match方法相當(dāng)于re.search功能,即match="zero"也是允許的
def test_zero_division_long():
    with pytest.raises(ZeroDivisionError, match="zero") as excinfo:
        1 / 0

pytest. raised()函數(shù)還有另一種形式,在這里傳遞一個(gè)函數(shù),該函數(shù)將使用給定的*args和**kwargs執(zhí)行,并斷言引發(fā)了給定的異常。在沒有異?;蝈e(cuò)誤異常的情況下,報(bào)告器將為您提供有用的輸出。

pytest.raises(ExpectedException, func, *args, **kwargs)

斷言某個(gè)測試用例中可能出現(xiàn)多個(gè)不同的預(yù)期異常的解決辦法:

在with pytest.raises()中傳入異常類型的參數(shù),從傳入一個(gè)異常類型,改變?yōu)閭魅胍粋€(gè)異常類型組成的元組。同樣只是傳入一個(gè)參數(shù)。

示例如下:

# ./func.py
def add(a,b):
    raise NameError('名字錯(cuò)了')
    if isinstance(a,int) and isinstance(b,int):
        return a+b
    else:
        raise TypeError('數(shù)據(jù)類型錯(cuò)誤')
 
# ./test_case/test_func.py
import pytest
from func import *
 
class TestFunc:
    # 異常測試用例,期望結(jié)果為爆出TypeError異常
    def test_add_by_func_aaa(self,*args, **kwargs):
    # 將預(yù)期中多個(gè)錯(cuò)誤信息組成一個(gè)元組
        with pytest.raises((TypeError,NameError),match=r'.*錯(cuò).*$') as E:
            add('3',4)
 
 
# ./run_test.py
import pytest
 
if __name__ == '__main__':
 pytest.main(['-v'])

檢查斷言裝飾器

檢查異常裝飾器@pytest.mark.xfail():用于對(duì)于檢查未修復(fù)的錯(cuò)誤,即可能發(fā)生的異常。斷言通過用例執(zhí)行成功會(huì)顯示xfailed,不通過顯示failed。

作用:檢查是否有異常,不確定是否有異常。

示例如下:

# 單個(gè)異常時(shí)斷言裝飾器使用
 
@pytest.mark.xfail(raises=ZeroDivisionError)
def test_f():
    1 / 0
# 多個(gè)異常時(shí)斷言裝飾器使用
@pytest.mark.xfail(raises=(TypeError, NameError))
def test_add_by_func_aaa2():
    add("3", 4)

到此這篇關(guān)于Pytest斷言的具體使用的文章就介紹到這了,更多相關(guān)Pytest斷言內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論