如何使用参数创建Test类?

时间:2015-05-29 01:42:58

标签: python pytest

以下是当前测试代码的样子:

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)

我想将测试代码转换为Test类:

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的文档,但我无法弄清楚如何在[100,200,...]中运行TestSimulation的速度。 setup_class()方法只能有cls个参数。

我想要的是一个测试类:

  • 调用do_simulation()一次,然后存储结果。
  • 调用所有测试方法来检查模拟结果。
  • 我可以将不同的参数添加到do_simulation()

1 个答案:

答案 0 :(得分:1)

您可以使用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):
        ...