Getting started with pytest Transcripts
Chapter: pytest Fixtures
Lecture: Moving setup and teardown into a fixture

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Alright. Ready for fixtures. So I'm gonna grab, I'm just gonna grab all of this and put it in a new file.
0:08 We'll call it a test count because this will be our real test. Now I want to pull up the the setup into a fixture.
0:20 So let's I have to import we need to import pytest so we can do a pytest.fixture. And let's call it since we're calling it within the code
0:36 is DB. DB is kind of general. What's let's do a Cards_dB, And then we need to do all this.
0:50 We're gonna move this set up and tear down into this with temporary directors. db_dir,db_path We don't need the count. So this is the setup,
1:10 this is the tear down in the middle will yield the database. So this goes to the test and I can put a little space in there.
1:21 So this works. So the cards db. Is doing the is a fixture when a test calls it or uses it
1:29 High test to run the setup and then run the test and give it a database to the test and then close it afterwards.
1:37 This is kind of exactly what we want to have happen. So let's see if we can use it within our empty call.
1:44 So if we use cards DB here then given an empty database, it's already empty when count is called. Now I can move this over when the count is called.
2:03 We don't need to tear down. count return zero. Well that's a lot shorter. It's so simple that I don't know. No, no. really need these comments.
2:14 Sweet. That's a little tiny test. Now one Item. Does that make this one better? Cards Db given one item. So we start out empty.
2:30 So we still need to add it. Oh we changed the name. So I was using DB before we changed the name to cards DB. So we better change that.
2:41 I can move these over cards. DB. Add card given a database with one item. So it starts out empty and I added one item and then called count.
2:56 And we don't need to close it because that's being done for us by the fixture
3:00 count returns one. This really focuses our tests on just really what we're doing. Uh This is pretty cool. So let's give this a try.
3:09 We don't want the initial test count. Something's wrong by using DB somewhere still right there.
3:27 Sweet. Let's take a look at what's going on. If we do the setup show. So pytest test count. Set up,
3:38 show and we can see that the cards DB the setup is getting called. And then we took the pytest calls test empty and then the tear down and then
3:51 set up the second test and tear down. And because it's happening around that we know that it's gonna be and it's going into
3:57 a temporary directory. It's gonna be empty before each test. So this is awesome. This is exactly what we want.

Talk Python's Mastodon Michael Kennedy's Mastodon