Python unit tests with PyTest
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
Let's make a new Python 3 repl.
Create two files:
In main.py, make a function
square() that squares
def square(x): return x ** 2
That's all you'll need for main.py
Add this it .replit:
run="pytest 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
This means you need to add some tests.
To make a test, define a function that starts with
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
You can add
test_* functions for any function in your app.
Deploying your tests
There are two ways to do this:
Add this to deploy.sh:
pytest testrunner.py || echo "Tests failed, aborting" && exit 1 clear python3 main.py
.replit say this:
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: