For an application I'm testing I'd like to create an autouse=True
fixture which monkeypatches smtplib.SMTP.connect
to fail tests if they try to send an email unexpectedly.
However, in cases where I do expect tests to send emails, I want to use a different fixture logging those emails instead (most likely by using the smtpserver
fixture from pytest-localserver
and monkeypatching the connect
method to use the host/port returned by that fixture)
Of course that can only work if the autouse fixture is executed before the other fixture (loaded as funcarg). Is there any specific order in which fixtures are executed and/or is there a way to guarantee the execution order?
Higher-scoped fixtures are instantiated first @pytest.
Pytest by default, it's executes the steps randomly. So use this option for executing in order.
pytest fixtures are functions attached to the tests which run before the test function is executed. Fixtures are a set of resources that have to be set up before and cleaned up once the Selenium test automation execution is completed.
Fixtures with scope session will only be executed once per session. Every time you run pytest , it's considered to be one session.
The easiest way to control the order in which fixtures are executed, is to just request the previous fixture in the later fixture. So to make sure b
runs before a
:
@pytest.fixture(autouse=True, scope="function") def b(): pass @pytest.fixture(scope="function") def a(b): pass
For details on the general fixture resolution order, see Maxim's excellent answer below or have a look at the documentation.
I was just having this problem with two function
-scoped autouse fixtures. I wanted fixture b
to run before fixture a
, but every time, a
ran first. I figured maybe it was alphabetical order, so I renamed a
to c
, and now b
runs first. Pytest doesn't seem to have this documented. It was just a lucky guess. :-)
That's for autouse fixtures. Considering broader scopes (eg. module
, session
), a fixture is executed when pytest encounters a test that needs it. So if there are two tests, and the first test uses a session
-scoped fixture named sb
and not the one named sa
, then sb
will get executed first. When the next test runs, it will kick off sa
, assuming it requires sa
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With