Writing unit tests in python
Jul 29, 2015 • 1 minutes to readA good developer always tests his code. And python being a robust language is very easy to test. Heres a function that adds two numbers and returns their result.
Now here is a test case that will test if your function returns the excepted result:
Thats it !
Running your tests
Install the nose2
python package using pip
pip install nose2
This is how my directory is structured:
. ├── sum_num.py └── tests ├── __init__.py └── test_sum_num.py
Now when you are in the root directory and run nose2 using the command line (command is nose2
), it will check for all the files inside the tests/ directory and look for test cases that have file names that contain in it test and have class names that have the name Test and method names test. So this is how it will look like:
tests/ ---> test_sum_num.py ---> class TestSum ---> method test_sum()
So this is a short run down of how to start running test cases in your projects. You can checkout the official list of assert methods that the unittest.TestsCase
class provides here.
I am writing a book!
While I do appreciate you reading my blog posts, I would like to draw your attention to another project of mine. I have slowly begun to write a book on how to build web scrapers with python. I go over topics on how to start with scrapy and end with building large scale automated scraping systems.
If you are looking to build web scrapers at scale or just receiving more anecdotes on python then please signup to the email list below.