How to test your Python code using pytest

What is pytest?

When you are developing an application in any programming language or framework and you don’t test it, your application could crash unexpectedly. So, it is advisable to perform the testing of your application with different test cases: both positive and negative.

pytest is a Python testing framework that helps users write the test cases to test their applications. It offers various features, like detailed messages when your test case fails, support for unittest and nose test, etc.

Before moving on, let’s first install the package by running the following command:

pip install pytest

We will be creating a separate test.py file that will contain the test cases for our Python code.

To run the test file, we need to use the below command in our command prompt:

python -m pytest test.py

We will be creating a simple function, that will return the cube of a number, and then write its test cases. Now, let’s see the code.

Positive cases

test.py
main.py
import main
def test_case_1():
assert 27 == main.cube(3)
def test_case_2():
assert 64 == main.cube(4)
def test_case_3():
assert 125 == main.cube(5)

Explanation:

  • In the main.py file:
    • We create a simple cube() function that will accept a number and return the cube.
  • In the test.py file:
    • In line 1, we import the main.py file to access the cube() function.
    • Then, we define three functions that will be treated as three different test cases for our cube() function.
  • When you run the above code, you will see that all the test cases have been passed.

Negative case

Now, let’s see what type of output you can get when the test cases are not passed.

test.py
main.py
import main
def test_case_1():
assert 27 == main.cube(3)
def test_case_2():
assert 60 == main.cube(4)
def test_case_3():
assert 125 == main.cube(5)

Explanation:

  • We just changed one of the test cases and, as we can see that in the output, we are getting detailed information about when and where the test case fails.

So, in this way, you can write your own tests and make sure that your application is well tested before it is deployed in production.

Free Resources