Using Fixtures for Test Data

Fixtures are a great place to store data to use for testing. You can return anything. Here’s a fixture returning a tuple of mixed type:

 @pytest.fixture()
 def​ a_tuple():
 """Return something more interesting."""
 return​ (1, ​'foo'​, None, {​'bar'​: 23})
 
 
 def​ test_a_tuple(a_tuple):
 """Demo the a_tuple fixture."""
 assert​ a_tuple[3][​'bar'​] == 32

Since test_a_tuple() should fail (23 != 32), we can see what happens when a test with a fixture fails:

 $ ​​cd​​ ​​/path/to/code/ch3
 $ ​​pytest​​ ​​test_fixtures.py::test_a_tuple
 ===================== test session starts ======================
 collected 1 item
 
 test_fixtures.py F
 
 
 =========================== FAILURES ...

Get Python Testing with pytest now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.