import pytest
"""斷言"""
deff()
:return
3# pytest允許您使用標準python assert來驗證python測試中的期望和值
deftest_function()
:assert f()==
4,"never see you again"
# 自行斷言
# 斷言可以指定一條訊息,assert condition, message
# 訊息將簡單地顯示在跟蹤中assertionerror: message
# 關於預期異常的斷言
deftest_zero_division()
:with pytest.raises(zerodivisionerror)
: result =1/
0# excinfo是乙個exceptioninfo例項,是實際引發的異常的包裝
# 感興趣的主要屬性是 .type,.value和.traceback
deftest_recursion_depth()
:with pytest.raises(runtimeerror)
as excinfo:
deffind_something()
: find_something(
) find_something(
)# print(str(excinfo.type), str(excinfo.value),str(excinfo.traceback), end=' ')
assert
"maximum recursion"
instr
(excinfo.value)
# 為了編寫有關引發的異常的斷言,可以將其 pytest.raises用作上下文管理器
# 將match關鍵字引數傳遞給上下文管理器,以測試正規表示式在異常的字串表示形式上是否匹配
defmyfunc()
:raise valueerror(
"exception 123 raised"
)'''
myfunc引發的valueerror原因是否符合pytest.raises中match的匹配規則
'''"""
pytest --trace-config 要找出環境中哪些外掛程式處於活動狀態
pytest -p no:name 阻止外掛程式載入或登出它們
"""def
test_match()
:with pytest.raises(valueerror, match=r".* 123 .*"):
myfunc(
)# 為失敗的斷言定義自己的解釋
# 通過實現該pytest_assertrepr_compare掛鉤,可以新增您自己的詳細說明
# pytest_assertrepr_compare(config,op,left,right )
# 返回失敗斷言表示式中的比較的說明
defpytest_assertrepr_compare
(op, left, right):if
isinstance
(left, foo)
andisinstance
(right, foo)
and op ==
"=="
:return
["comparing foo instances:"
," vals: {} != {}"
.format
(left.val, right.val),]
class
foo:
def__init__
(self, val)
: self.val = val
def__eq__
(self, other)
:return self.val == other.val
deftest_compare()
: f1 = foo(1)
f2 = foo(2)
assert f1 == f2
pytest (五) pytest中的斷言
pytest 的斷言報告,也很豐富,和詳情,比如 import pytest def test set comparison set1 set 1308 set2 set 8035 assert set1 set2 執行一下 有時候,我們需要對一些異常丟擲作斷言,可以用pytest.raises 比...
Pytest 斷言重寫
pytest是使用普通的斷言語句以及斷言失敗時表示式的詳細內省,僅重寫測試模組本身以及作為外掛程式一部分的任何模組,任何其他匯入的模組都不會被重寫,並且會發生正常的斷言行為。換言之 如果你在其他模組中有斷言,你需要啟用斷言重寫,你需要pytest在匯入之前明確要求重寫這個模組。註冊乙個或多個要在匯入...
pytest中的assert斷言
assert斷言 1.判斷兩個數值是否相等,相等則認為是true 2.判斷兩個值大小關係 3.判斷函式方法的返回值和某個值是否相等或者大小關係 上面3種可以統稱為數值大小比較 4.判斷部分字串是否包含在某個字串中,a in abc 在為true,不在為false 5.判斷 函式結果不為false,不...