pytest:如何将类参数传递给setup_class

时间:2013-11-01 22:22:53

标签: python pytest

我正在使用pytest的参数化注释将params传递给一个类。我可以在测试方法中使用参数,但是,我无法弄清楚如何在setup_class方法中使用这些参数。

import pytest

params = ['A','B','C']

@pytest.mark.parametrize('n', params)
class TestFoo:

    def setup_class(cls):
        print ("setup class:TestFoo")
        # Do some setup based on param

    def test_something(self, n):
        assert n != 'D'

    def test_something_else(self, n):
        assert n != 'D'

我尝试将'n'添加为测试方法之类的参数,如下所示:

def setup_class(cls, n):
        print ("setup class:TestFoo")
       # Do some setup based on param

导致错误:

self = <Class 'TestFoo'>

    def setup(self):
        setup_class = xunitsetup(self.obj, 'setup_class')
        if setup_class is not None:
            setup_class = getattr(setup_class, 'im_func', setup_class)
            setup_class = getattr(setup_class, '__func__', setup_class)
>           setup_class(self.obj)
E           TypeError: setup_class() takes exactly 2 arguments (1 given)

在setup_class方法中是否还有其他一些使用参数的方法?

2 个答案:

答案 0 :(得分:3)

你不能。

首先,setup_class每个类只调用一次,即使使用了parametrize fixture - 类只设置了一次。

其次,它不是设计为采用除cls以外的任何其他参数。它不接受来自paramterize和其他装置的参数。

作为解决方案,您可以使用具有“类”范围的参数化夹具:

import pytest

params = ['A', 'B', 'C']


@pytest.fixture(
    scope="class",
    params=params,
)
def n(request):
    print('setup once per each param', request.param)
    return request.param


class TestFoo:

    def test_something(self, n):
        assert n != 'D'

    def test_something_else(self, n):
        assert n != 'D'

有关详细信息,请查看http://docs.pytest.org/en/latest/fixture.html#fixture-parametrize

答案 1 :(得分:-3)

您应该通过将属性分配给cls来将属性传递给测试类。稍后分配给它的所有属性和函数将成为类attrubutes / methods。

参数化装饰器应该用在类方法上(你想测试方法,不是吗?)

所以:

import pytest

params = ['A','B','C']

class TestFoo:

    def setup_class(cls):
        cls.n = params

    @pytest.mark.parametrize('n', params)
    def test_something(self, n):
        assert n != 'D'

    @pytest.mark.parametrize('n', params)
    def test_something_else(self, n):
        assert n != 'D'

    def test_internal(self):
        assert self.n != params

test_internal. It illustrates that参数were set to自我and now自我equals to参与号

{}