Python unit testing - pytest fixtures
Key Takeaways
Introduces pytest fixtures for setup and teardown of unit tests
Full Transcript
dear friends in this tutorial we are going to cover a very powerful feature of p/y test framework called fixtures [Music] okay what I have here is a sample database class this is just a fake or a mock class I have created for demos demonstrating fixtures but if you are using any real Python module for let's say Oracle or SQL database it will have all these basic functionality it will have your database object will have your connection and then the third thing will be cursor so cursor will have an ability to execute your database queries here I have some put some fixed database queries and returning some fixed values here so again this is all fake okay now when I start writing the test here I want to write to kind of taste so first test is to verify Jones employee ID and the other one is to verify Thoms employee ID so this database is basically a employ database and all I'm doing is verifying IDs of different employees and I am writing a unit test for them so first let's write unit tests for Chon I will say taste Jones ID here and in order to create the database object I will call my dB this will give me the database object and in database forth if you have some idea on how databases work then you always need to connect to your server it observed now I am just saying server but this will be appropriate connection string okay and once you have your connection you will have a cursor object next so action dot cursor will give you cursor object and cursor dot execute will be able to execute your SQL query here I'm going to copy the query from this class select ID from employee beware name is equal to John this returns me the ID of employee John and let's say this is ID you want to assert that ID is 1 2 3 I think so ID here is 1 2 3 so I just want to assert that similarly you can write another test case for Toms ID I'm just going to quickly change these things and 7 8 9 that's your palms ID okay so if you have seen my previous tutorials before this tutorials and you know this is how you write your test it should be I should have taste underscore prefix and the file name should also have taste into score when you run this test using py taste - me come on it runs fine it will say that is passed ok now what's the problem with this approach you can see that here there are two main issues one issue is you are repeating all these lines of code here you see so if you notice a thousand test cases you will be writing these three lines like thousand times okay which is not good second thing is database connection is costly you could be even writing test cases requiring network connection and those things are not also costly so it's a costly operation which you are performing on running each and every test so again if you have thousand test cases is gonna take some time and waste some resources there has to be a better way of doing this in classic unit style you will use a setup and teardown concept so what setup and teardown does is it will initialize whatever you need for your test cases in the beginning so first let let me use setup and teardown and then I will show you how you can use fixtures instead of setup and teardown because fixture is much better than traditional xunit style setup and teardown first I am going to make my connection and cursor object Google global and write down a setup module method so this is a setup at module level and you are just initializing your connection and cursor object here so you say global connection and cursor is also global now this test has this course are available so it can directly use it so you can get rid of all these lines there is also a teardown method so let me write that write that down tear down module now what tear down means is after test cases have finished execution you want to do some cleanup so you will do coarser clothes first and then connection close okay so I didn't show that those methods earlier but I also have these close methods here which I want to call okay so basically whatever your taste cases need you are initializing that in your setup module and then once you are done executing these you will tear down tear down meaning you will close the connection and do necessary cleanup all right let's this cool so you can see both the test passed it worked as expected so now this is better you solve the two issues that I mentioned and those issues was repeating the same line of code and calling costly database connection every time now you can do this exact same thing of setting up and tear down using beaver test fixtures so let me show you how to use periodic test fixtures I'm going to first remove this these Global's are not needed and import py test module and then write down my fixture I'll say py taste dot fixture okay and what you need in each of these tests is really the cursor okay so all right let me just make a space here okay so what you need is a constant so here I can say cursor and then I'm just going to copy the score here okay so you create your database you connect to your database and then you have your cursor and you will just return the cursor here okay now see what happens when you return this when you use this fixture so in order to use this fixture in your test cases let me just remove all of these all you will do is call cursor here so what happens is when cursor is passed here the EITS member will realize that there is a cursor function which is a fixture so it's gonna call this function and return these object here right here okay so that's that's what it's gonna do and just to make it clear this course and this core function is same as this it was not this okay so I just gene the variable name so this guy here is same as here okay and that's run this test and see what happens okay cool so it works see it passed all those tests okay so this is better because you don't have to create those global variables and also this concept aligns with your dependency injection concept if you have done like Java programming you might have heard this term dependency injection so what I'm doing here is this test has a dependency on cursor and I'm injecting the dependency using this particular feature alright now when you run this test you have to after you're done executing these you have to do connection close as well so for the in connection close what you have to do is you have to use a yield function so first before I do that let me show you by printing that it is doing whatever we expect it to do so I will say setting up here and yeah let me just do this first okay so when you run this test here or it's not printing the statement because in order to print it you how to supply - - capture option and you have to say no no means don't capture the output of s print statement somewhere else but show it on STD out so here you can see that it is printing setting up twice so it is setting calling setting up then it is running the test again calling setting up and then running the test meaning it is not doing whatever we expect it is actually creating these database of object every time you call them here so to restrict that at a module level you can use this coke scope parameter and when you say scope is equal to model it will set up only once so now when you do that you can see setting up is just one time okay now this output this is more visible if you don't use - - V so you can see it is setting up these two dot means it is running to test and that's it okay now how do you do teardown teardown means where do you close your connection and cursor okay so for that you have to return your you just change a return with yield and after this you will say cursor dot close and then connection close so what will happen is it will create this cursor object only once it will pass it to all the test cases execute the test cases after all of that is over it will go here and close the connection and let me let me print this closing data race okay let's run this nice so you can see that it set up the things that we needed to run to this these two dot means it ran those two test cases and then it is closing the database ok so that was all about switches in pure test framework they are pretty powerful they are recommended over using setup and teardown methods because they are much better than setup and teardown so whenever you end right pure test based unit test please use these fixtures alright thank you for watching
Original Description
This tutorial covers a powerful feature in pytest framework called fixtures. It leverages the dependency injection concept for setup and teardown of your unit tests. It is preferred over traditional xunit style setup/teardown methods. The video explains demonstrating problem, issues with test case in the case of code repetition, creating expensive DB connection in every test case and solving problems with fixtures.
Topics that are covered in this Python Video:
0:00 Overview
0:16 Demonstrating problem
3:25 Issues with test case 1. code repetition 2. creating expensive DB connection in every test case
4:32 Setup and teardown methods
7:05 Solving problem with fixtures
9:24 fixtures leverage a concept Dependency injection
Do you want to learn technology from me? Check https://codebasics.io/ for my affordable video courses.
You can find code used in this tutorial here: https://github.com/codebasics/py/tree/master/unittesting_pytest/fixtures
Next Video:
Python unit testing - pytest parameters: https://www.youtube.com/watch?v=2EGgtlf7BN0&list=PLeo1K3hjS3uv5U-Lmlnucd7gqF-3ehIh0&index=39
Website: https://codebasics.io/
Facebook: https://www.facebook.com/codebasicshub
Twitter: https://twitter.com/codebasicshub
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from codebasics · codebasics · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Python Tutorial - 1. Install python on windows
codebasics
Python Tutorial - 2. Variables
codebasics
Python Tutorial - 3. Numbers
codebasics
Python Tutorial - 4. Strings
codebasics
Python Tutorial - 5. Lists
codebasics
Python Tutorial - 6. Install PyCharm on Windows
codebasics
PyCharm Tutorial - 7. Debug python code using PyCharm
codebasics
Python Tutorial - 8. If Statement
codebasics
Python Tutorial - 9. For loop
codebasics
Python Tutorial - 10. Functions
codebasics
Python Tutorial - 11. Dictionaries and Tuples
codebasics
Python Tutorial - 12. Modules
codebasics
Python Tutorial - 13. Reading/Writing Files
codebasics
How to install Julia on Windows
codebasics
Python Tutorial - 14. Working With JSON
codebasics
Julia Tutorial - 1. Variables
codebasics
Julia Tutorial - 2. Numbers
codebasics
Python Tutorial - 15. if __name__ == "__main__"
codebasics
Julia Tutorial - Why Should I Learn Julia Programming Language
codebasics
Python Tutorial - 16. Exception Handling
codebasics
Julia Tutorial - 3. Complex and Rational Numbers
codebasics
Julia Tutorial - 4. Strings
codebasics
Python Tutorial - 17. Class and Objects
codebasics
Julia Tutorial - 5. Functions
codebasics
Julia Tutorial - 6. If Statement and Ternary Operator
codebasics
Julia Tutorial - 7. For While Loop
codebasics
Python Tutorial - 18. Inheritance
codebasics
Julia Tutorial - 8. begin and (;) Compound Expressions
codebasics
Python Tutorial - 12.1 - Install Python Module (using pip)
codebasics
Julia Tutorial - 9. Tasks (a.k.a. Generators or Coroutines)
codebasics
Julia Tutorial - 10. Exception Handling
codebasics
Python Tutorial - 19. Multiple Inheritance
codebasics
Python Tutorial - 20. Raise Exception And Finally
codebasics
Python Tutorial - 21. Iterators
codebasics
Python Tutorial - 22. Generators
codebasics
Python Tutorial - 23. List Set Dict Comprehensions
codebasics
Python Tutorial - 24. Sets and Frozen Sets
codebasics
Python Tutorial - 25. Command line argument processing using argparse
codebasics
Debugging Tips - What is bug and debugging?
codebasics
Debugging Tips - Conditional Breakpoint
codebasics
Debugging Tips - Watches and Call Stack
codebasics
Python Tutorial - 26. Multithreading - Introduction
codebasics
Git Tutorial 3: How To Install Git
codebasics
Git Tutorial 1: What is git / What is version control system?
codebasics
Git Tutorial 2 : What is Github? | github tutorial
codebasics
Git Tutorial 4: Basic Commands: add, commit, push
codebasics
Git Tutorial 5: Undoing/Reverting/Resetting code changes
codebasics
Git Tutorial 6: Branches (Create, Merge, Delete a branch)
codebasics
Git Github Tutorial 10: What is Pull Request?
codebasics
Git Tutorial 7: What is HEAD?
codebasics
Git Tutorial 9: Diff and Merge using meld
codebasics
Difference between Multiprocessing and Multithreading
codebasics
Python Tutorial - 27. Multiprocessing Introduction
codebasics
Python Tutorial - 28. Sharing Data Between Processes Using Array and Value
codebasics
Git Tutorial 8 - .gitignore file
codebasics
Python Tutorial - 29. Sharing Data Between Processes Using Multiprocessing Queue
codebasics
Python Tutorial - 30. Multiprocessing Lock
codebasics
Python Tutorial - 31. Multiprocessing Pool (Map Reduce)
codebasics
What is code?
codebasics
Python unit testing - pytest introduction
codebasics
Related AI Lessons
Chapters (6)
Overview
0:16
Demonstrating problem
3:25
Issues with test case 1. code repetition 2. creating expensive DB connection in
4:32
Setup and teardown methods
7:05
Solving problem with fixtures
9:24
fixtures leverage a concept Dependency injection
🎓
Tutor Explanation
DeepCamp AI