【问题标题】:how wo change pytest Generated parameters如何更改pytest生成的参数
【发布时间】:2019-06-27 04:33:37
【问题描述】:

执行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

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    我认为您正在搜索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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 2022-01-05
      • 2022-12-10
      • 1970-01-01
      相关资源
      最近更新 更多