How to reuse same fixture implementation with different scopes?
See original GitHub issueHello!
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!
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:9 (4 by maintainers)
Top Results From Across the Web
Give Pytest fixtures different scopes for different tests
One way to do this to separate out the implementation and then have 2 differently-scoped fixtures return it. So something like:
Read more >Understand 5 Scopes of Pytest Fixtures | by Xiaoxu Gao
Pytest fixtures have five different scopes: function, class, module, package, and session. The scope basically controls how often each fixture will be executed....
Read more >How to use fixtures — pytest documentation
Each method only has to request the fixtures that it actually needs without worrying about order. This is because the act fixture is...
Read more >How I Use Pytest Fixtures for System Testing - Atomic Spin
You can create fixtures with a variety of different scopes. For system tests, session scoped fixtures are appropriate for one-time setup of ...
Read more >Five Advanced Pytest Fixture Patterns - Inspired Python
You can create fixtures with arguments by returning a function — that function is called a factory. Composing Fixtures. Consider two separate fixtures...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@jurisbu correct
@RonnyPfannschmidt Thanks for such a prompt response. As per your suggestions of using contexmanager instead, do you mean something along these lines?