# Python Unit Testing With PyTest

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

- Familiarity with Pipenv. See here for my post on Pipenv.
- Familiarity with importing modules and
`__init__.py`

## Getting started

Let's create the `hello-pytest`

directory and install Pillow.

`1 2 3 4 5 6 7 8 9 10 11 12`

`# Make the `hello-pytest` directory $ mkdir hello-pytest $ cd hello-pytest # Init the virtual environment $ pipenv --three $ pipenv install --dev pytest # Create a folder to place files $ mkdir src tests # Create the required files $ touch src/math.py src/__init__.py tests/test_math.py tests/__init__.py`

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:

`1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37`

`def add(x: int, y: int) -> int: """add two numbers together Args: x (int): first number to add y (int): second number to add Returns: int: sum of x and y """ return x + y def subtract(x: int, y: int) -> int: """subtract one number from another Args: x (int): first number to subtract y (int): second number to subtract Returns: int: resut of x subtract y """ return x - y def multiply(x: int, y: int) -> int: """multiply two numbers together Args: x (int): first number in the multiplication y (int): second number in the multiplication Returns: int: product of x and y """ return x * y`

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:

`1 2 3 4 5 6 7 8 9 10 11 12 13`

`from src.math import add, subtract, multiply def test_add(): assert add(3, 2) == 5 def test_subtract(): assert subtract(3, 2) == 1 def test_multiply(): assert multiply(3, 2) == 6`

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:

`1 2 3 4 5 6 7 8`

`============================================= test session starts ============================================= platform darwin -- Python 3.9.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 rootdir: /Users/dennisokeeffe/code/blog-projects/hello-pytest collected 3 items tests/test_math.py ... [100%] ============================================== 3 passed in 0.02s ==============================================`

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.

`1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19`

`============================================= test session starts ============================================= platform darwin -- Python 3.9.6, pytest-6.2.4, py-1.10.0, pluggy-0.13.1 rootdir: /Users/dennisokeeffe/code/blog-projects/hello-pytest collected 3 items tests/test_math.py F.. [100%] ================================================== FAILURES =================================================== __________________________________________________ test_add ___________________________________________________ def test_add(): > assert add(3, 2) == 5 E assert 6 == 5 E + where 6 = add(3, 2) tests/test_math.py:5: AssertionError =========================================== short test summary info =========================================== FAILED tests/test_math.py::test_add - assert 6 == 5 ========================================= 1 failed, 2 passed in 0.08s =========================================`

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

*Photo credit: rstone_design*

## Dennis O'Keeffe

Melbourne, Australia

## Related articles

### 5 Handy Python Tips For Beginners

- 100daysofpython

After 30+ days of my 100 day Python journey, I stop to reflect on the five tips that have been unusual by helpful coming into the language.

### Regression With Scikit Learn (Part 4)

- python
- 100daysofpython
- machine learning

In our final coverage of regression using SciKit Learn, we look at how we can use regression with regularization.

### Regression With Scikit Learn (Part 3)

- python
- 100daysofpython
- machine learning

In part three, we look at using k-fold cross-validation to prevent dependency on a particular train/test split.

### Regression With Scikit Learn (Part 2)

- python
- 100daysofpython
- machine learning

In second blog post on linear regression, we take what we learned in part one and look deeper into the basics of linear regression and applying a train-test-split to our data.

### Regression With Scikit Learn (Part 1)

- python
- 100daysofpython
- machine learning

Continuing with our look into supervised learning, today we explore the basics linear regression by applying it to another Scikit Learn toy dataset.

### Measuring Classifier Model Performance

- python
- 100daysofpython
- machine learning

See how we can visual test the performance capability of our K-Nearest Neighbors classifier using Scikit Learn.

1,200+ PEOPLE ALREADY JOINED ❤️️

## Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.