如何改变pytest生成参数

问题描述 投票:0回答:1

是否有任何可能的变化时执行test_equals功能test_zerodivision PARAM

当test_equals运行test_zerodivision功能参数是一个= 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
python pytest
1个回答
0
投票

我认为你正在寻找pytest.mark.parametrize。下面是如何实现你的代码根据本functionalty一个例子:

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
© www.soinside.com 2019 - 2024. All rights reserved.