Unit test
Previous: Classes | Next: Scientific Libraries, Pandas, Numpy |
Required course material for the lesson
Powerpoint: Testing
Online: pytest documentation
Resource: Example code - Unit test
Blog: On testing, by the founder of StackExchange.
Subjects covered
Overview of test methods
Unit test using pytest framework.
Exercises to be handed in
You should make a special folder for the exercises. I will refer to my special folder as unittest in these exercises. You will also see some __pycache__ folders appear in places. This is Pythons cache for "compiled" programs. It is safe to ignore and also to delete, because it may become outdated.
- Use your factorial function from exercise 2 in Making Functions. If you did not do so already, change it to use exceptions instead of sys.exit(), when an error occurs. Now make simple unit tests for the following test cases: 12, 2, 1, 0, -1, 3.0, 3.4, "3", "3.1.", "ABC". The factorial function and all test functions must be in one single file (factorial_test.py in unittest), which you can run pytest on.
- Now remove the factorial function from factorial_test.py and put it in its own file factorial.py. Import it from the factorial_test.py like from factorial import factorial. The first factorial is the name of the .py file, the second factorial is the name of your factorial function. Just run pytest (no file name) in the folder to check it works. It is more normal to have test and function separated.
- Above we removed test code from function code by creating two files. Next, put the files in their own folder in unittest. I would put my factorial.py in unittest/src and factorial_test.py in unittest/test. This way there is a very clear separation between function and test. The problem is making sure the test code loads the function code. Do it wrong a couple of times - it is very instructive.
- Follow the file structure of having a code (or src) folder for programs, a test folder for tests, and now a testdata folder for files containing test data. Now make unit tests and appropriate test data files for your fasta class from last week. In this exercise you just need to make unit test for the method load. You need to hand in both tests and test data. Maybe you should zip it all. Learn to zip :-)
- Add unit tests for the method save in your fasta class.
- Add unit tests for the method delete in your fasta class.
I would not be surprised if you find errors in your fasta class based on these tests. I found flaws in my code.
Exercises for extra practice
- Add unit tests for all methods in your fasta class. That will be a bit of work.