13
我是pytest的新手,並試圖將一些功能測試腳本轉換成pytest很好地運行的腳本。我的模塊具有自定義錯誤類型,我試圖使用「with pytest.raises()as excinfo」方法。這是一個科學/數值軟件包,我需要測試某些方法在調用時是否一致,因此我不能深入到低層次的東西。謝謝使用pytest.raises捕獲預期的自定義錯誤
我是pytest的新手,並試圖將一些功能測試腳本轉換成pytest很好地運行的腳本。我的模塊具有自定義錯誤類型,我試圖使用「with pytest.raises()as excinfo」方法。這是一個科學/數值軟件包,我需要測試某些方法在調用時是否一致,因此我不能深入到低層次的東西。謝謝使用pytest.raises捕獲預期的自定義錯誤
什麼是阻止您導入特定異常並在您的with
pytest.raises聲明中使用它?爲什麼這不起作用?如果你能提供更多關於你面臨什麼問題的細節,那將會更有幫助。
# your code
class CustomError(Exception):
pass
def foo():
raise ValueError('everything is broken')
def bar():
raise CustomError('still broken')
#############
# your test
import pytest
# import your module, or functions from it, incl. exception class
def test_fooErrorHandling():
with pytest.raises(ValueError) as excinfo:
foo()
assert excinfo.value.message == 'everything is broken'
def test_barSimpleErrorHandling():
# don't care about the specific message
with pytest.raises(CustomError):
bar()
def test_barSpecificErrorHandling():
# check the specific error message
with pytest.raises(MyErr) as excinfo:
bar()
assert excinfo.value.message == 'oh no!'
def test_barWithoutImportingExceptionClass():
# if for some reason you can't import the specific exception class,
# catch it as generic and verify it's in the str(excinfo)
with pytest.raises(Exception) as excinfo:
bar()
assert 'MyErr:' in str(excinfo)
看起來像你的最後'與py.test.raises'應該是'與pytest.raises' – 2014-04-12 05:32:57
@IanHunter現在已經更新,謝謝(你能告訴我現在還在使用「py.test」版本: )) – pfctdayelise 2014-04-13 15:45:22
對於python3:'assert str(excinfo.value)=='一切都壞了' – incognick 2016-09-20 16:58:12