簡體   English   中英

如何使用pytest測試異常和錯誤?

[英]How do I test exceptions and errors using pytest?

我的Python代碼中有函數可以響應某些條件引發異常,並且想確認它們在我的pytest腳本中的行為與預期一致

目前我有

def test_something():
    try:
        my_func(good_args)
        assert True
    except MyError as e:
        assert False
    try:
        my_func(bad_args)
        assert False
    except MyError as e:
        assert e.message == "My expected message for bad args"

但這看起來很麻煩(需要對每個案例重復)。

有沒有辦法使用Python測試異常和錯誤,或者這樣做的首選模式?

def test_something():
    with pytest.raises(TypeError) as e:
        my_func(bad_args)
        assert e.message == "My expected message for bad args"

不起作用(即使用assert False替換斷言,它也會通過)。

這條路:

with pytest.raises(<YourException>) as exc_info:
    <your code that should raise YourException>

exception_raised = exc_info.value
<do asserts here>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM