py.test session level fixtures in setup_method

谁说胖子不能爱 提交于 2019-12-05 03:00:40

I used this kind of a setup for a test class with pytest<=3.7.0 (it stopped working with pytest 3.7.1 release):

# conftest.py:

import pytest

# autouse=True does not work for fixtures that return value
# request param for fixture function is only required if the fixture uses it:
# e.g. for a teardown or parametrization. Otherwise don't use it.
@pytest.fixture(scope="session")
def myfixture():
    return "myfixture"

# test_aaa.py

import pytest

class TestAAA(object):
    @classmethod
    @pytest.fixture(scope="class", autouse=True)
    def setup(self, myfixture):
        self.myfixture = myfixture

    def test_function1(self):
        # now you can use myfixture without passing it as param to each test function   
        assert self.myfixture == "myfixture"

I don't think you can do it directly. However, you can decorate the whole class with pytest.mark.usefixtures, if that helps:

@pytest.mark.usefixtures(['myfixture'])
class TestAAA(object):
    ...

IIRC, setup_method will be called before any of the automatically applied fixtures.

You can also utilize autouse for class-level fixtures like so:

class TestAAA(object):
    @pytest.fixture(autouse=True)
    def init_aaa(self, myfixture):
        ...

For the example provided above, the object returned from the fixture can be set as an attribute of the test class. Any methods of this class will have access.

# test_fixture.py

import pytest

class TestAAA():
@pytest.fixture(scope="class", autouse=True)
def setup(self, myfixture):
    TestAAA.myfixture = myfixture

def test_function1(self):
    assert self.myfixture == "myfixture"

or if you inherit from unittest.Testcase you can do the following

# test_fixture.py

import pytest
from unittest import TestCase

class TestAAA(TestCase):
    @pytest.fixture(scope="class", autouse=True)
    def setup(self, myfixture):
        self.myfixture = myfixture

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