Chapter 3pytest Fixtures

Now that you’ve seen the basics of pytest, let’s turn our attention to fixtures, which are essential to structuring test code for almost any non-trivial software system. Fixtures are functions that are run by pytest before (and sometimes after) the actual test functions. The code in the fixture can do whatever you want it to. You can use fixtures to get a data set for the tests to work on. You can use fixtures to get a system into a known state before running a test. Fixtures are also used to get data ready for multiple tests.

Here’s a simple fixture that returns a number:

 import​ pytest
 
 
 @pytest.fixture()
 def​ some_data():
 """Return answer to ultimate question."""
 return​ 42
 
 

Get Python Testing with pytest now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.