pytest參數化:@pytest.mark.parametrize

內置的pytest.mark.parametrize裝飾器可以用來對測試函數進行參數化處理。下面是一個典型的範
例,檢查特定的輸入所期望的輸出是否匹配:
test_expectation.py

import pytest
@pytest.mark.parametrize("test_input, expected", [("3+5", 8), ("2+4", 6), ("6*9", 42),])
def test_eval(test_input, expected):
    assert eval(test_input) == expected

裝飾器@parametrize定義了三組不同的(test_input, expected)數據,test_eval則會使用這三組數據
執行三次:

$ pytest
=========================== test session starts ============================
platform linux ‐‐ Python 3.x.y, pytest‐4.x.y, py‐1.x.y, pluggy‐0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
collected 3 items
test_expectation.py ..F [100%]
================================= FAILURES =================================
____________________________ test_eval[6*9‐42] _____________________________
test_input = '6*9', expected = 42
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
def test_eval(test_input, expected):
> assert eval(test_input) == expected
E AssertionError: assert 54 == 42
E + where 54 = eval('6*9')
test_expectation.py:8: AssertionError
==================== 1 failed, 2 passed in 0.12 seconds ====================

該示例中,只有一組數據是失敗的。通常情況下你可以在traceback中看到作爲函數參數的input和output。
注意你也可以對模塊或者class使用參數化的marker來讓多個測試函數在不同的測試集下運行。
你也可以對參數集中的某個參數使用mark,比如下面使用了內置的mark.xfail:
test_exception.py

import pytest
@pytest.mark.parametrize("test_input, expected", [("3+5", 8), ("2+4", 6), ("6*9", 42, marks=pytest.mark.xfail),])
def test_eval(test_input, expected):
    assert eval(test_input) == expected

運行結果如下:

$ pytest
=========================== test session starts ============================
platform linux ‐‐ Python 3.x.y, pytest‐4.x.y, py‐1.x.y, pluggy‐0.x.y
cachedir: $PYTHON_PREFIX/.pytest_cache
rootdir: $REGENDOC_TMPDIR, inifile:
collected 3 items
test_expectation.py ..x [100%]
=================== 2 passed, 1 xfailed in 0.12 seconds ====================

之前結果是失敗的用例在這裏已經被標記爲xfailed了。
如果參數化的列表是一個空列表,比如參數是某個函數動態生成的,請參考
empty_parameter_set_mark選項。
可以對一個函數使用多個parametrize的裝飾器,這樣多個裝飾器的參數會組合進行調用:

import pytest
@pytest.mark.parametrize("x", [0, 1])
@pytest.mark.parametrize("y", [2, 3])
def test_foo(x, y):
    pass

這會窮舉x和y的所有組合並進行調用。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章