亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 pytest 覆蓋跳過自定義異常消息斷言?

為什么 pytest 覆蓋跳過自定義異常消息斷言?

偶然的你 2022-06-02 17:55:14
我正在為 api 做一個包裝器。我希望該函數在輸入無效時返回自定義異常消息。def scrape(date, x, y):    response = requests.post(api_url, json={'date': date, 'x': x, 'y': y})    if response.status_code == 200:        output = loads(response.content.decode('utf-8'))        return output    else:        raise Exception('Invalid input')這是對它的測試:from scrape import scrapedef test_scrape():    with pytest.raises(Exception) as e:        assert scrape(date='test', x=0, y=0)        assert str(e.value) == 'Invalid input'但是覆蓋測試由于某種原因跳過了最后一行。有誰知道為什么?我嘗試將代碼更改為with pytest.raises(Exception,  match = 'Invalid input') as e,但出現錯誤:AssertionError: Pattern 'Invalid input' not found in "date data 'test' does not match format '%Y-%m-%d %H:%M:%S'"這是否意味著它實際上是在引用來自 api 而不是我的包裝器的異常消息?
查看完整描述

2 回答

?
莫回無

TA貢獻1865條經驗 獲得超7個贊

由于引發的異常,它不會到達您的第二個斷言。你可以做的就是以這種方式斷言它的價值:


def test_scrape():

    with pytest.raises(Exception, match='Invalid input') as e:

        assert scrape(date='test', x=0, y=0)

我會說您在響應時收到錯誤“AssertionError: Pattern 'Invalid input' not found in "date data 'test' does not match format '%Y-%m-%d %H:%M:%S'"代碼是 200 - 所以沒有引發異常。


查看完整回答
反對 回復 2022-06-02
?
DIEA

TA貢獻1820條經驗 獲得超3個贊

您的抓取函數引發異常,因此函數調用之后的行將不會執行。您可以將最后一個斷言放在 pytest.raises 子句之外,如下所示:


from scrape import scrape


def test_scrape():

    with pytest.raises(Exception) as e:

        assert scrape(date='test', x=0, y=0)

    assert str(e.value) == 'Invalid input'


查看完整回答
反對 回復 2022-06-02
  • 2 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號