在 class 顶级代码中访问函数参数化

Access function parametrization in class top level code

Pytest 允许通过在 class 级别应用参数化装饰器来参数化 class 中定义的所有测试:在 the documentation example 之后,定义

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

允许在测试中访问 nexpected

也可以在 class 级别放置一些代码,每个测试都会执行这些代码,因此对设置测试很有用:

@pytest.mark.parametrize("n,expected", [(1, 2), (3, 4)])
class TestClass:
    #This code is run before each test :
    with open("file.dat") as f:
       expected_result = f.readlines()

    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("n,expected", [(1, 2), (3, 4)])
class TestClass:
    #This code is run before each test :
    with open("file.dat") as f:
       expected_result = f.readlines()
    assert n < 10

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

产生异常:E NameError: name 'n' is not defined

我想使用参数化参数进行测试设置:有什么方法可以在 class 级别访问它吗?

您可以将代码放在 @pytest.fixture 中,这将允许您访问测试参数

@pytest.mark.parametrize("n,expected", [(1, 2), (3, 4)])
class TestClass:

    @pytest.fixture(scope='function', autouse=True)
    def setup_and_teardown(self, n):
        with open("file.dat") as f:
            self.expected_result = f.readlines()
        assert n < 10
        yield

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

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

这也将支持每个测试的不同参数值

class TestClass:

    @pytest.fixture(scope='function', autouse=True)
    def setup_and_teardown(self, n):
        with open("file.dat") as f:
            self.expected_result = f.readlines()
        yield

    @pytest.mark.parametrize("n,expected", [(1, 2)])
    def test_simple_case(self, n, expected):
        assert n + 1 == expected

    @pytest.mark.parametrize("n,expected", [(3, 4)])
    def test_weird_simple_case(self, n, expected):
        assert (n * 1) + 1 == expected