pytest文檔74-參數化parametrize加marks標記(pytest.param)


前言

pytest 使用 parametrize 參數化的時候,有多組測試數據,需要對其中的一些測試數據加標記跳過,可以用pytest.param實現。

pytest.param

先看下 pytest.param 源碼,可以傳三個參數

  • param values :按順序傳參數集值的變量args
  • keyword marks : marks關鍵字參數,要應用於此參數集的單個標記或標記列表。
  • keyword str id: id字符串關鍵字參數,測試用例的id屬性
def param(*values, **kw):
    """Specify a parameter in `pytest.mark.parametrize`_ calls or
    :ref:`parametrized fixtures <fixture-parametrize-marks>`.

    .. code-block:: python

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

    :param values: variable args of the values of the parameter set, in order.
    :keyword marks: a single mark or a list of marks to be applied to this parameter set.
    :keyword str id: the id to attribute to this parameter set.
    """
    return ParameterSet.param(*values, **kw)

使用示例

import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

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

運行結果:1 passed, 1 xfailed in 0.08 seconds

skip跳過用例

上面的案例是標記xfail,想標記skip跳過用例也是可以的

import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

@pytest.mark.parametrize("user,psw",
                         [("yoyo1", "123456"),
                          ("yoyo2", "123456"),
                          pytest.param("yoyo3", "123456", marks=pytest.mark.skip)])
def test_login(user, psw):
    print(user + " : " + psw)
    assert 1 == 1

運行結果:2 passed, 1 skipped in 0.03 seconds

上面的2個參數也可以用pytest.param格式

import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

@pytest.mark.parametrize("user,psw",
                         [pytest.param("yoyo1", "123456"),
                          pytest.param("yoyo2", "123456"),
                          pytest.param("yoyo3", "123456", marks=pytest.mark.skip)])
def test_login1(user, psw):
    print(user + " : " + psw)
    assert 1 == 1

id參數

id參數是給用例添加標題內容,沒加id參數的時候,用例會默認拿請求的參數當用例標題

添加id參數

import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/

@pytest.mark.parametrize("user,psw",
                         [pytest.param("yoyo1", "123456", id="test case1: yoyo1"),
                          pytest.param("yoyo2", "123456", id="test case2: yoyo2"),
                          pytest.param("yoyo3", "123456", marks=pytest.mark.skip, id="test case3: yoyo3")])
def test_login1(user, psw):
    print(user + " : " + psw)
    assert 1 == 1

運行結果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM