Dennis O'Keeffe
2 min readAug 28, 2021

--

Heading image

This is Day 7 of the #100DaysOfPython challenge.

This post will demonstrate a basic setup of the PyTest library to run unit tests on your Python code.

Prerequisites

  1. Familiarity with Pipenv. See here for my post on Pipenv.
  2. Familiarity with importing modules and __init__.py

Getting started

Let’s create the hello-pytest directory and install Pillow.

At this stage, we are ready to add our math functions.

Adding helpler math functions

Our example will be very contrived, but we will create an add, subtract and multiply function to demonstrate how to import functions and unit test them.

Inside of src/math.py, add the following code:

The above code contains three functiosn that each do as you would expect from a math helper.

With these in mind, let’s add code to the test file for our math module.

Writing our unit tests

Inside of tests/test_math.py, add the following code:

Each test does as your would expect and asserts on simple math. The assert function will pass if the result is true and fail if not.

We can run our tests now by running pipenv run pytest from the command line.

If done correctly, you should now see the following:

To ensure our tests are working as expected and failing when they should, you can update a function to fail and test that it does fail.

If I update my add function in src/math.py to return x + y + 1 instead of x + y, I can test that the function fails and provides information about the failure.

Changing it back will pass the tests again and we successfully written our first test with PyTest.

Summary

Today’s post demonstrated how to use PyTest to write unit tests for our math module.

Although contrived, the example was helpful in learning how to write unit tests for our code.

If you would like to read into more examples of testing, Pluralsight have a delightful repo that you can read through and see how they make their tests.

I will be writing on more complex usages of PyTest over the coming weeks.

Resources and further reading

  1. The ABCs of Pipenv
  2. Pipenv
  3. pluralsight/intro-to-pytest
  4. What is __init__.py?
  5. PyTest

Photo credit: rstone_design

Originally posted on my blog. To see new posts without delay, read the posts there and subscribe to my newsletter.

I write content for AWS, Kubernetes, Python, JavaScript and more. To view all the latest content, be sure to visit my blog and subscribe to my newsletter. Follow me on Twitter.

--

--