pytest: How to pass a class parameter to setup_class

和自甴很熟 提交于 2019-12-04 03:42:51

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

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`

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