Closed

Description
Hello!
I am looking for a way to reuse same fixture or same fixture implementation in different scopes. I would like to avoid copy-pasting implementation in multiple fixtures with different scopes defined. What would be recommended approach?
So far I have thought about (ab)using yield from
as in following example. Not sure if this can lead to some unexpected issues.
@pytest.fixture(session='function')
def my_fixture_fun():
yield from fixture_impl()
@pytest.fixture(scope='module')
def my_fixture_mod():
yield from fixture_impl()
@pytest.fixture(scope='session')
def my_fixture_ses():
yield from fixture_impl()
def fixture_impl():
# Rather long on complicated fixture implementation here
print('SETUP: Fixture implmentation')
yield
print('TEARDOWN: Fixture implmentation')
Any other ideas or suggestions?
Thanks!
Metadata
Metadata
Assignees
Labels
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
pytestbot commentedon Apr 24, 2018
GitMate.io thinks possibly related issues are #538 (Fixture scope documentation), #1552 (Suggestion: add new 'parametrization' fixture scope), #2732 (Fixture scope mixing?), #3393 (Customize the fixture ordering on the same scope level), and #668 (autouse fixtures break scope rules).
RonnyPfannschmidt commentedon Apr 24, 2018
iriginally multi scoped fixtures was planned for pytest 3.0, but it demonstrated impossible to implement without a major refactoring, what you do there is the common workaround, but its suggested to use a contextmanager instead of yield from
ghost commentedon Apr 24, 2018
@RonnyPfannschmidt Thanks for such a prompt response. As per your suggestions of using contexmanager instead, do you mean something along these lines?
RonnyPfannschmidt commentedon Apr 24, 2018
@jurisbu correct
ghost commentedon Apr 24, 2018
Satisfactory answer received. Closing.
iAnanich commentedon Aug 6, 2021
Same idea can be applied to async fixtures/tests:
oleg-kondaurov commentedon Oct 13, 2021
@RonnyPfannschmidt @jurisbu @iAnanich Is it possible to somehow trigger the test state to become
error
orfail
in case if an exception is raised in setup or teardown block of the contextmanager?Current example causes the unhandled exception and pytest process close:
dmos62 commentedon May 19, 2022
I've been doing this:
Seemed more straightforward than a context manager. Any downsides to this?
nicoddemus commentedon May 19, 2022
Currently we add an attribute to the function decorated by
@pytest.fixture
:pytest/src/_pytest/fixtures.py
Line 1197 in 611b579
So the fixtures above will actually point to the wrong definition... I'm surprised it works.