Modern Python Projects Transcripts
Chapter: Testing code
Lecture: Fixtures
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
Let's talk about some useful features of pytest. One of the most popular ones are called fixtures.
0:07
Fixture is a piece of code that you can run before a test function. They can be used, for example,
0:12
to create some test objects. Let's say you have a website and you want to test that after a user looks in,
0:19
they can perform certain actions. You might have a lot of different tests, and each of them requires a user who is logged in like in this example.
0:28
We have a test by item, where we first have to create and log in the user. And then we have test admin permissions where again we have the same code
0:38
to create a user and to make sure he's logged in. We can easily avoid this duplication by extracting the first two lines from each test into
0:48
a separate fixture. So let's do that. Let me cut this and then we are going to create a fixture called authenticated
0:56
user, and to mark function as a fixture. We have to add a decorator called pytest.fixture and make it work.
1:13
We have to import pytest, now to make your test. Use this fixture. We just have to pass it as a parameter,
1:23
and we can remove it from here, at this admin parameter is actually not needed. And again we pass this fixture and we use it in our test.
1:35
If in the future we need yet another test that requires this authenticated user, we already have a fixture for that.
1:43
So using fixtures in pytests is a standard way to extract creation of some test objects
1:49
from your tests. If a few tests share the same code at the beginning, you can probably take them out to a separate fixture.
1:58
And apart from creating your own fixtures, pytest comes with some builtin ones that you can find in the documentation. So here you have this list and,
2:06
for example, have a fixture called tmpdir() that you can use when you want to create a temporary directory in your tests.