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.
0:03 One of the most popular ones are called fixtures.
0:06 Fixture is a piece of code that you can run before a test function.
0:10 They can be used, for example,
0:11 to create some test objects. Let's say you have a website and you want to
0:16 test that after a user looks in,
0:18 they can perform certain actions. You might have a lot of different tests,
0:23 and each of them requires a user who is logged in like in this example.
0:27 We have a test by item, where we first have to create and log in the
0:32 user. And then we have test admin permissions where again we have the same code
0:37 to create a user and to make sure he's logged in.
0:40 We can easily avoid this duplication by extracting the first two lines from each test into
0:47 a separate fixture. So let's do that.
0:50 Let me cut this and then we are going to create a fixture called authenticated
0:55 user, and to mark function as a fixture.
1:08 We have to add a decorator called pytest.fixture and make it work.
1:12 We have to import pytest, now to make your test.
1:16 Use this fixture. We just have to pass it as a parameter,
1:22 and we can remove it from here, at this admin parameter is actually not needed.
1:28 And again we pass this fixture and we use it in our test.
1:34 If in the future we need yet another test that requires this authenticated user,
1:39 we already have a fixture for that.
1:42 So using fixtures in pytests is a standard way to extract creation of some test objects
1:48 from your tests. If a few tests share the same code at the beginning,
1:53 you can probably take them out to a separate fixture.
1:57 And apart from creating your own fixtures,
1:59 pytest comes with some builtin ones that you can find in the documentation.
2:03 So here you have this list and,
2:05 for example, have a fixture called tmpdir() that you can use when you want
2:11 to create a temporary directory in your tests.