Skip to content
← Back to Community
Python unit tests with PyTest
Profile icon

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.


Let's make a new Python 3 repl.

Create two files:

  • .replit

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

def square(x): return x ** 2

That's all you'll need for


Add this it .replit:

run="pytest "

The Magic

This is where the magic happens. 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

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

I use
Add this to

pytest || echo "Tests failed, aborting" && exit 1 clear python3

And make .replit say this:



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

run="pytest; clear; python3"

And that's a wrap!

For more info, look at:

Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon
Profile icon