如何创建带参数的测试 class?

How to create a Test class with parameters?

这是当前测试代码的样子:

def do_simulation(speed):
    df = run_simulation(speed)

    # following is a lot of assert that checks the values in df
    assert df["X"].iloc[0] == 0
    assert df["Y"].iloc[-1] == 2
    assert ...
    ....

def test_simulation():
    do_simulation(100)
    do_simulation(200)

我想将测试代码转换为测试class:

class TestSimulation(object):

    def setup_class(cls):
        cls.df = run_simulation(100) # I want to change the speed parameter

    def test_1():
        "comment 1"
        assert self.df["X"].iloc[0] == 0

    def test_2():
        "comment 2"
        assert self.df["Y"].iloc[-1] == 2

我阅读了 py.test 的文档,但我不知道如何 运行 TestSimulation 的速度 [100, 200, ...]。 setup_class() 方法只能有 cls 个参数。

我想要的是一个测试class:

你可以使用一个pytest fixture and parametrize它:

@pytest.fixture(
    scope='module', # so that it's reused in the module scope
    params=[100, 200]
)
def simulation(request):
    speed = request.param
    # create the simulation
    return df

class Test:

    def test1(self, simulation):
        ...

    def test2(self, simulation):
        ...