我正在為 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 - 所以沒有引發異常。

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'
添加回答
舉報
0/150
提交
取消