• 10 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 8/30/22

Add Tests Using Pytest

You need to install Pytest before you can use it. To do this, use PyPI by running the following command on the terminal:

pip install -U pytest

Check that Pytest has been installed by typing the  pytest  command. Pytest will then run all the tests in our project.

Type the pytest command in the terminal to check that it has been installed.
Run your tests!

As you can see, no tests were actually executed. That’s because we haven’t created any yet, so don’t worry!

Before we do this, let’s start off by creating a test file called  test.py.

Create a Test Using Pytest

To better understand how Pytest works, let’s write the following source code in a file called  source.py  :

def reverse_str(initial_string):
    final_string = ''
    index = len(initial_string)
    while index > 0:
        final_string += initial_string[index - 2]
        index = index - 1
    return final_string

We’ve created a function that will be passed a string of characters as a parameter, which it will then return in reverse order.

I’ve written a new function in the  test.py  file that will test the  reverse_str(initial_string)  function.

I’ll name it  test_should_reverse_string  because it’s a test to check if the function correctly returns the string in reverse order. In the code, I’ll use the keyword  assert, followed by a space and then I’ll write what I want to test. So, if the assertion is true, the code passes the test! 

In my case, I want to test that the result of executing the  reverse_str('abc')  function is that the returned string equals   'cba'  .

from source import reverse_str

def test_should_reverse_string():
    assert reverse_str('abc') == 'cba'

Let’s test it! Run the  pytest test.py  command.

The test has failed and Pytest specifies the error in the terminal.
A failed test

Oh no, it didn’t work! But Pytest was kind enough to tell us which line failed, as well as the difference between what was returned by the function and what we expected.

The function returned  bac, while we were hoping to get  cba. Hmmm. 🤔

Let’s check the code again to see if we’ve missed an error.

Oh, there’s actually an error in line 5! I’d better correct it right now.

def reverse_str(initial_string):
    final_string = ''
    index = len(initial_string)
    while index > 0:
        final_string += initial_string[index - 1] #Replace index - 2 with index - 1
        index = index - 1
    return final_string

Let’s run the tests again by entering the  pytest test.py  command.

After correcting the error, the test is successful as specified by Pytest in the terminal.
Yes! The test was successful!

Everything is green, our tests are all valid.

Here’s a screencast that summarizes the steps we went through above to execute your first test using Pytest:

Organize Your Test Files in a Project

Before you even start writing all the tests for your project, it’s important to organize our project architecture so that we keep our source code and tests separate. However, there are a number of methods that enable you to easily find the source code associated with your tests.   

First of all, you can create a dedicated folder structure specifically for your testing. This method will group all the tests for an application together in the same place. 

Best practices for organizing tests:

  • Create a test folder structure to mirror the source file directory.

  • Name the test files with the same name as the source file with a prefix of  test_ .

The tree structure shows all the test files and follows the source code tree structure.
Test folder structure

Pytest will actually execute tests on all files that start with  test_  or end with  _test . If you use this method, you can easily run the  pytest  command to execute all of the tests in your project.

Create the First Tests For the Project

Now we’re going to write our own tests for the Calculator project.

The first test is to check that the behavior of the  addition  method within the  Operators  class is correct.

Let’s have a look at the various steps.

Before doing anything, we need to create a test file in our test folder structure and we’ll name it  test_operators.py . Next, we need to import the module containing the source file into the test file so that we can use the various elements.

This is done by adding the following import instruction:

from calculate.operators import Operators

Let’s now write the relevant test

def test_should_make_multiple_addition():
    sut = Operators()
    operation = "5.5 + 10 + 30 + 13.7"
    expected_value = 59.2
    assert sut.addition(operation) == expected_value

 Now you can run the  pytest  command in the project root to check if it passes the test.

The test is successful after running it using the pytest command.
First test for the Calculator project

The test was successful!

I’m going to summarize all of these steps in the screencast below. You can follow each step to set up the first test for this project yourself.

Over to You!

Now you’re going to set up all of the unit tests for the super-calculator project, which will test the code logic. I hope you’re going to practice using Pytest to execute the tests.

Your Mission:

  • Add a test package containing the test folder structure.

  • Create a sequence of tests for the view module using Pytest.

  • Create a sequence of tests for the operators module using Pytest.

Find a suggested solution on GitHub!

Let’s Recap!

  • It’s advisable to organize your tests in a dedicated test directory that copies the source code folder structure.

  • To create a test, you need to define a function starting with the  test_  prefix or ending with the  _test  suffix.

  • The  assert  keyword is used to check the elements that we want to check.

  • Run tests on a module using the  pytest module_name.py  command.

Now you know how to create unit tests using the Pytest framework. It would also be useful to know some of the features of the Unittest framework. So, in the next chapter, we’ll see how to set up unit tests using the Unittest framework.

Example of certificate of achievement
Example of certificate of achievement