首页 > 解决方案 > 如何更改 pytest 生成的参数

问题描述

执行 test_equals 函数时是否有可能更改 test_zerodivision 参数

当 test_equals 运行 test_zerodivision 函数参数为 a=1 b=0,但我想更改此函数中的 a 或 b 值

我可以更改 TestClass.params 然后重新加载 pytest_generate_tests 或任何其他方式

我知道如何避免这个问题,但我只想知道如何改变这个值。pytest使用了很多黑魔法,我只是好奇

import pytest


def pytest_generate_tests(metafunc):
    # called once per each test function
    funcarglist = metafunc.cls.params[metafunc.function.__name__]
    argnames = sorted(funcarglist[0])
    metafunc.parametrize(argnames, [[funcargs[name] for name in argnames]
            for funcargs in funcarglist])

class TestClass(object):
    # a map specifying multiple argument sets for a test method
    params = {
        'test_equals': [dict(a=1, b=2), dict(a=3, b=3), ],
        'test_zerodivision': [dict(a=1, b=0), ],
    }

    def test_equals(self, a, b):

        assert a == b

    def test_zerodivision(self, a, b):
        with pytest.raises(ZeroDivisionError):
            a / b

标签: pythonpytest

解决方案


我认为您正在搜索pytest.mark.parametrize。以下是如何在您的代码下实现此功能的示例:

import pytest


class TestClass:    
    @pytest.mark.parametrize(
        ('a', 'b'),
        (
            (1, 1),
            (3, 3),
            ('a', 'a')
        )

    )
    def test_equal(self, a, b):
        assert a == b

    @pytest.mark.parametrize(
        ('a', 'b'),
        (
            (1, 0),
            (0, 0),
            (0.1, 0)
        )
    )
    def test_zerodivision(self, a, b):
        with pytest.raises(ZeroDivisionError):
            a / b

推荐阅读