How to exchange objects with devices for all tests using pytest?

What is the best way to identify an object in a device with a session scope and autouse = True, so it will be available for all tests?

@pytest.fixture(scope='session', autouse=True)
def setup_func(request):
    obj = SomeObj()

Next, I want some kind of magic that I previously created objto appear in every test context without the need for each test to determine the fixture setup_func.

def test_one():
   obj.do_something_fancy()
+4
source share
2 answers

My recommendation will add the device to conftest.pyand will definitely return the object that you want to create from the lamp.

As already noted, this makes "autouse" seemingly worthless.

conftest.py:

@pytest.fixture(scope='session', autouse=True)
def someobj(request):
    return SomeObj()

(, test_foo.py):

def test_foo(someobj):
    assert isinstance(someobj, SomeObj)

, .

, conftest.py:

someobj = None
@pytest.fixture(scope='session', autouse=True)
def prep_someobj(request):
    someobj = SomeObj()

:

from . import conftest

def test_foo():
    assert isinstance(conftest.someobj, SomeObj)

-, , .

+4

- . , , , . ,

class SomeObj():
    """This object definition may exist in another module and be imported."""
    def __init__(self):
        self.x = 5

    def do_something_fancy(self, y):
        return self.x * y


class TestX():
    # Object instance to share across tests
    someobj = SomeObj()

    def test_x(self):
        assert TestX.someobj.x == 5

    def test_fancy(self):
        fancy_factor = 10
        result = TestX.someobj.do_something_fancy(fancy_factor)
        assert result == 50
0

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


All Articles