Follow this tutorial here to create a unittest

https://docs.python.org/3/library/unittest.html#basic-example

Assuming that you have a folder like

mypackage\
    uberlib.py
    models.py
test\
    test_uberlib.py
    test_models.py
main.py

You can run both tests by using

python3 -m unittest discover -s test

or a specific test

python3 -m unittest test.test_uberlib

To use coverage, first you need to install it (using pip)

pip install coverage

And then type

coverage run --source mypackage --branch -m unittest discover -s test

Note: --source mypackage means only the source code in mypackage folder will be covered, --branch is for measuring branch coverage. Read more here.

To see coverage report, use:

coverage report

If you fancy HTML based report, use this and a report will be generated into a folder named htmlcov in your project folder. Open index.html inside the folder to see the report

coverage html

That’s it. It’s pretty cool eh?

Advertisements