Create A Pytest Fixture

Introduction To Pytest

This video goes over the basics of implementing your own pytest fixture to help dry out repetition code boilerplate. It covers moving a repeated variable into a seperate function decorated with @pytest.fixture and then importing that into your test functions as an argument.


[0:00] Let's use a pytest fixture to help dry out these tests. We'll start by importing pytest. Now let's move our common test variable or in this case Bob to his own separate function.

[0:15] Using a decorator we can register the function as a pytest fixture. And now we can go about injecting that fixture as an argument to our tests.And we can get rid of the previous variables we setup.

[0:31] Let's run the tests to make sure they pass...And they do. Behind the scenes here pytest is going to look at the arguments include in the test functions and see if they have a matching fixture registered.

[0:41] And if so executes that function, and passes whatever it returns down to the test as an argument. This can help to keep your tests a bit more focused and easier to read.