pytest: How to pass a class parameter to setup_class

落花浮王杯 提交于 2020-01-01 09:24:11

问题


I am using pytest's parametrize annotations to pass params into a class. I'm able to use the parameters in the test methods, however, I can't figure out how to use the parameters in the setup_class method.

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'

I tried adding 'n' as a parameter like the test methods, like this:

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

Which results in an error:

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)

Is there some other way of using the parameter in the setup_class method?


回答1:


You can't.

First, setup_class is called only once per class, even if there is parametrize fixture used - class is set up only once.

Second, it is not designed to take any other params than cls. It will not accept params from paramterize and other fixtures.

As a solution, you could use a parametrized fixture with "class" scope:

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'

For more info look at http://docs.pytest.org/en/latest/fixture.html#fixture-parametrize




回答2:


You should pass attributes to your test class by assigning it to cls. All attributes and functions that you assign to it later will become class attrubutes / methods.

Parametrized decorator should be used on class methods (you want to test methods, don't you?)

So:

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 will fail on test_internal. It illustrates thatparamswere set toself.nand nowself.nequals toparams`



来源:https://stackoverflow.com/questions/19736363/pytest-how-to-pass-a-class-parameter-to-setup-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!