py.test session level fixtures in setup_method

China☆狼群 提交于 2019-12-06 21:27:38

问题


Is there a way to somehow use pytest fixtures from conftest.py in a test class's setup? I need to initialize an object when the session starts and use it in some test classes' setup.

Something like this:

# conftest.py:

import pytest

@pytest.fixture(scope="session", autouse=True)
def myfixture(request):
    return "myfixture"

# test_aaa.py

class TestAAA(object):

    def setup(self, method, myfixture):
        print("setup myfixture: {}".format(myfixture))

    ...

回答1:


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"



回答2:


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):
        ...



回答3:


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")


来源:https://stackoverflow.com/questions/37436871/py-test-session-level-fixtures-in-setup-method

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