我對我的硒測試使用pytest,並想知道是否有可能在單個測試中有多個斷言?我可以在pytest中執行多個斷言嗎?
我調用一個比較多個值的函數,我希望測試報告所有不匹配的值。我遇到的問題是,使用「assert」或「pytest.fail」只要發現一個不匹配的值就停止測試。
有沒有辦法讓測試繼續運行並報告所有不匹配的值?
我對我的硒測試使用pytest,並想知道是否有可能在單個測試中有多個斷言?我可以在pytest中執行多個斷言嗎?
我調用一個比較多個值的函數,我希望測試報告所有不匹配的值。我遇到的問題是,使用「assert」或「pytest.fail」只要發現一個不匹配的值就停止測試。
有沒有辦法讓測試繼續運行並報告所有不匹配的值?
正如Jon Clements所評論的那樣,您可以填寫錯誤消息列表,然後聲明列表爲空,並在斷言爲false時顯示每條消息。
具體地說,它可能是類似的東西:
def test_something(self):
errors = []
# replace assertions by conditions
if not condition_1:
errors.append("an error message")
if not condition_2:
errors.append("an other error message")
# assert no error message has been registered, else print messages
assert not errors, "errors occured:\n{}".format("\n".join(errors))
原來的說法是由if
報表時附加消息到errors
名單的情況下,條件不符合所取代。 然後,您斷言errors
列表爲空(空列表爲False),並使斷言消息包含列表中的每條消息。
您也可以按照nose documentation中所述製作測試發生器。我沒有找到描述它的任何pytest文檔,但我知道pytest處理的方式與鼻子完全相同。
非常感謝幫助,完美的工作 – ChrisG29
下面是另一種稱爲Delayed assert的方法,它與@Tryph提供的非常相似,並提供了更好的堆棧跟蹤。
pytest-assume是「一個pytest插件,允許每個測試多次失敗」。這裏是你將如何使用它的一個示例(從README
拍攝):
import pytest
@pytest.mark.parametrize(('x', 'y'), [(1, 1), (1, 0), (0, 1)])
def test_simple_assume(x, y):
pytest.assume(x == y)
pytest.assume(True)
pytest.assume(False)
即使某些斷言失敗,他們都得到評估和報告:
======================================== FAILURES =========================================
_________________________________ test_simple_assume[1-1] _________________________________
> pytest.assume(False)
test_assume.py:7
y = 1
x = 1
----------------------------------------
Failed Assumptions:1
_________________________________ test_simple_assume[1-0] _________________________________
> pytest.assume(x == y)
test_assume.py:5
y = 0
x = 1
> pytest.assume(False)
test_assume.py:7
y = 0
x = 1
----------------------------------------
Failed Assumptions:2
_________________________________ test_simple_assume[0-1] _________________________________
> pytest.assume(x == y)
test_assume.py:5
y = 1
x = 0
> pytest.assume(False)
test_assume.py:7
y = 1
x = 0
----------------------------------------
Failed Assumptions:2
================================ 3 failed in 0.02 seconds =================================
你就不能建列出錯誤列表,然後斷言列表是空的? –
雖然我想報告個別錯誤,所以在報告中它給了我一個不匹配的值列表 – ChrisG29
嗯......如何建立非匹配列表,然後聲明該列表是空的(如果發生錯誤,它不會) - 然後你會得到這個列表作爲「預期的[] - 得到[1,2,7,10]'或者不是那樣做的? –