Learn to Code via Tutorials on Repl.it!

← Back to all posts
Python unit tests with PyTest
h
CodeLongAndPros (1591)

How to use unit tests in Python

First, what is a unit test?
This could be a long winded answer, so I'll keep it simple:

It is a test that tests a 'unit' of your app.

I am going to use the pytest framework.

Setup

Let's make a new Python 3 repl.

Create two files:

  • .replit
  • testrunner.py

main.py

In main.py, make a function square() that squares x.

def square(x):
  return x ** 2

That's all you'll need for main.py

.replit

Add this it .replit:

run="pytest testrunner.py "

The Magic

testrunner.py

This is where the magic happens.

testrunner.py has to have this in it:

import pytest
from main import square

If you run this, you get exit 5.

This means you need to add some tests.

To make a test, define a function that starts with test_.

Let's add a basic test to testrunner.py:

def test_square_4():
  assert square(2) is 4

(Note: Only use the is for ints)

If you run your repl, you should see this:

Let's do another test:

def test_square_invalid_four():
  assert square(4) != 4

This one is kinda pointless, for this function. For boolean functions, False is just as good as True.

You can add test_* functions for any function in your app.

Deploying your tests

There are two ways to do this:

  • .replit
  • deploy.sh

Deploy.sh

I use deploy.sh.
Add this to deploy.sh:

pytest testrunner.py || echo "Tests failed, aborting" && exit 1

clear
python3 main.py

And make .replit say this:

run="bash deploy.sh"

.replit

This one is simpler, but less versatile.
Make .replit say this:

run="pytest testrunner.py; clear; python3 main.py"

And that's a wrap!

For more info, look at: