nailstorm
nailstorm

Reputation: 39

How to yield an object provided by fixture with autouse=True?

Is there some way to get a yielded object from autouse fixture without explicitly providing it as an input argument in a test function?

Say, I have something like this:

@pytest.fixture(scope="function", autouse=True)
def setup_something():
    something = Something()
    something.do_something(thing=1)
    yield something

Then, when I want to access this object, I do this:

def test_scenario(self):
    something.do_something_else()

The reason for that is one might have a lot of setup/teardown fixtures which provide some object or do other stuff, and mentioning all of them as parameters might be too cumbersome.

Upvotes: 3

Views: 2044

Answers (1)

tmt
tmt

Reputation: 8604

You could set an attribute of a test class instance but I'm far from sure that it would be a good idea.

import pytest

@pytest.fixture(scope="function", autouse=True)
def something(request):
    request.instance.something = Something()
    request.instance.something.do_something(thing=1)
    yield request.instance.something

class Test:
    def test_scenario(self):
        self.something.do_something_else()

Upvotes: 2

Related Questions