In this article, I’ll talk about:
1. Unit Testing
2. Unit Testing in Python/Django
…and compile a list of resources for someone who’s just getting into unit testing.
Here we go:
Unit of code:
A unit of code is something that does one thing.
It could be something that:
1. Gets the 5th power of a number
2. Pulls your name from the database and converts it to title case
3. Checks if the logged in client has enough $$
Basically anything that does only one coherent thing.
Tests if a unit of code does what it says it does.
1. Function that returns the 5th power of a number:
Possible Unit Tests:
What does the function do if I pass it a float instead of an integer?
What if I pass in a string?
What if I give it a really, really big number?
What if I pass in an imaginary number?
…and so on…
Why Unit Testing?
1. Code is more robust, bug-free
2. More scalable — adding features is easier
3. Less development time spent in debugging — failing tests will reveal errors
4. Can update libraries easier — tests will tell if something breaks
5. Enough tests = Confidence in your code!
TDD: Test Driven Development
- Write tests
- See them fail
- Write code
- Run tests
- Until all tests pass
Essence of Unit Testing (tl;dr):
1. Treat the unit of code as a black box, or a machine
2. Pass in some input
3. Get the output
4. Compare it to the expected output
5. See if it matches
What to test?
Anything that you’ve written yourself.
What not to test?
Anything that’s a part of the library you’re working with.
Resources for beginning unit testing with Python/Django:
- Read this book
- Watch this video
- Read the official docs on unittest, especially all the assertions.
- Testing in Django
- Try pytest