Py.test session level levels in setup_method

Is there a way to somehow use the pytest devices from conftest.py in the setup test class ? I need to initialize an object when starting a session and use it in the settings of some test classes.

Something like that:

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

    ...
+7
source share
3 answers

I used this 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"
+4
source

I do not think you can do this directly. However, you can decorate the whole class pytest.mark.usefixturesif this helps:

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

IIRC, setup_method .

autouse :

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

In the above example, the object returned from the device 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.Testcaseyou 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")
0
source

Source: https://habr.com/ru/post/1615430/


All Articles