Get startedGet started for free

Chain Fixtures Requests

1. Chain Fixtures Requests

Let's talk about fixture chain requests.

2. What is a chain request

Chain fixture requests is a feature that allows a fixture to request another fixture. You can see a diagram with an example of chain fixture requests with one test function and two fixtures. In this case, the tests function requests "Fixture 1", and "Fixture 1", in turn, requests "Fixture 2". Thus, the test function will run with both fixtures.

3. Why and when to use

When should we use this feature? Chain fixture requests help us to keep the code modular and divided by functions. That is especially helpful when we have more than one fixture and want to make them depend on each other. Note, that we could do that manually without chain requests. But in this case it would involve more custom code, that potentially could cause new errors. So, as before, this feature can save a couple of hours of development.

4. Example of chain requests

Take a look at this code and assume the "pytest" package is already imported. Let's divide the code into three parts. The first part is the fixture "setup underscore data" that is requested by the other fixture. The second part is the fixture "process underscore data", which the test function requests. The final third part is the test function "test underscore process underscore data". In this case, the code will be executed from the end to the beginning: firstly, the test function will request the fixture "process_data", then "process_data" will request the "setup_data" function. After that, the "setup_data" will be executed and returned to "process_data", and finally, the "test_process_data" will execute the "assert" statement. Note that in this case, "process_data" - is only a dependent fixture because it was not requested by other fixtures, but it requested the "setup_data" fixture. And vice versa, the "setup_data" function is only a dependable one because it is requested by "process_data", but does not request any other fixture by itself.

5. How to use chain requests

So, how can one use chain fixture requests on their own? To do that, we have to prepare the program we want to test, the test functions, and their fixture functions. Then, simply put a fixture name to the other fixture's signature so it knew what to request upon execution. In this piece of code, the "process data" is a fixture that requests "setup data", thus, "process data" depends on "setup data".

6. Summary

To recap. Chain fixture requests is a feature that allows a fixture to use another fixture. It helps to divide the code into functions and keep it modular. An example use case is the steps of data pipeline and data preparation, such as data initialization, data loading, data preprocessing, etc. Finally, to use chain fixture requests, simply pass the dependable fixture name to the dependent fixture function.

7. Let's practice!

Try to practice with chain fixture requests!