[英]PyTest: how to test imported function from another file in project
[英]How to test exception from imported function using Python pytest?
如何使用 pytest 測試導入函數的異常? 例如,在 main file.py 我有:
def function():
if 3 != 3:
raise Exception("Error")
在 testfile.py 我有:
import sys
import os
sys.path.insert(0, '..//main/')
import file
def test_exception():
file.function()
# need to test exception here
您可以像這樣使用pytest.raises
:
def test_exception():
with pytest.raises(SomeExceptionClass) as e:
file.function()
assert "Some informative error message" in str(e.value)
其中SomeExceptionClass
將是您期望發生的特定錯誤。 如果函數沒有引發錯誤(或者如果它引發不同的錯誤類型),這將引發斷言錯誤。
你可以這樣做:
import sys
import os
def function():
raise Exception("Error")
def test_exception():
try:
function()
except Exception as e:
print(e)
test_exception()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.