20、pytest中的参数化

官方实例

python 复制代码
# content of 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
python 复制代码
# content of test_expectation_class
import pytest

@pytest.mark.parametrize("n, expected",[(1,2),(3,4)])
class TestClass:
    def test_simple_case(self, n, expected):
        assert n + 1 == expected
        
    def test_weird_simple_case(self, n, expected):
        assert (n * 1) + 1 == expected
python 复制代码
# content of test_parametrize_glob.py
import pytest

pytestmark = pytest.mark.parametrize("n,expected",[(1,2),(3,4)])

class TestClass:
    def test_simple_case(self, n, expected):
        assert n + 1 == expected

    def test_weird_simple_case(self, n, expected):
        assert (n * 1) + 1 == expected

解读与实操

内置的pytest.mark.parametrize装饰器允许对测试函数的参数进行参数化。

注意:参数值按原样传递给测试(没有任何副本),例如,如果你传递一个列表或字典作为参数值,并且测试用例代码对它进行了修改,那么这些修改将在随后的测试用例调用中反映出来。

请注意,你也可以在类或模块上使用参数化标记,类中的函数将调用带有参数集内容。

要将模块中的所有测试参数化,可以将其赋值给pytestmark全局变量。

场景应用

测试函数相同,只是传入参数不同,就可以用这种方法扩展测试用例。特别是针对列表的搜索功能,同一个搜索函数,但是存在多个搜索项。

相关推荐
测试老哥10 小时前
pytest+requests+allure自动化测试接入Jenkins学习
自动化测试·软件测试·学习·测试工具·职场和发展·jenkins·pytest
丿罗小黑12 小时前
Pytest项目_day20(log日志)
pytest
xt198928812 小时前
pytest+yaml+allure接口自动化测试框架
自动化测试·pytest·接口自动化·框架封装
灰阳阳12 小时前
接口自动化测试大全(python+pytest+allure)
python·pytest·接口自动化·allure
5:003 天前
pytest框架-详解
pytest
丿罗小黑5 天前
Pytest项目_day15(yaml)
pytest
丿罗小黑5 天前
Pytest项目_day16(yaml和parametrize结合)
pytest
代码小念6 天前
Pytest+selenium UI自动化测试实战实例(超详细)
selenium·ui·pytest
丿罗小黑6 天前
Pytest项目_day11(fixture、conftest)
pytest