1. 程式人生 > 實用技巧 >Pytest學習筆記(七)引數化parametrize

Pytest學習筆記(七)引數化parametrize

可以使用pytest.mark.parametrize裝飾器來對測試用例進行引數化。

對列表中的物件進行迴圈,然後一一賦值,這個物件可以是列表,元組,字典。

import pytest


def add(a, b):
    return a + b


@pytest.mark.parametrize("a,b,expect", [
    [1, 1, 2],
    [2, 3, 5],
    [4, 5, 7]
])
def test_add(a, b, expect):
    assert add(a, b) == expect

執行結果:

還可以對每組引數進行標識,如下:

import pytest


def add(a, b):
    return a + b


@pytest.mark.parametrize('a,b,expect', [
    pytest.param(1, 1, 2, id="first case"),
    pytest.param(2, 3, 5, id="second case"),
    pytest.param(4, 5, 8, id="third case")
])
def test_add(a, b, expect):
    assert add(a, b) == expect

使用mark.xfail對引數進行標識

import pytest


def add(a, b):
    return a + b


@pytest.mark.parametrize('a,b,expect', [
    pytest.param(1, 1, 2, id="first case"),
    pytest.param(2, 3, 5, id="second case"),
    pytest.param(4, 5, 8, id="third case", marks=pytest.mark.xfail(reason="這是個bug"))
])
def test_add(a, b, expect):
    
assert add(a, b) == expect

執行結果: