Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In which order are pytest fixtures executed?

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?

like image 630
ThiefMaster Avatar asked Sep 04 '14 07:09

ThiefMaster


People also ask

Which fixture is instantiated first in pytest?

Higher-scoped fixtures are instantiated first @pytest.

Does pytest run in order?

Pytest by default, it's executes the steps randomly. So use this option for executing in order.

How does fixture work in pytest?

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.

How often is a fixture function in pytest executed?

Fixtures with scope session will only be executed once per session. Every time you run pytest , it's considered to be one session.


2 Answers

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.

like image 135
Chronial Avatar answered Sep 19 '22 13:09

Chronial


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.

like image 20
ebeezer Avatar answered Sep 16 '22 13:09

ebeezer