pytest

Use a test framework, pytest, to run tests and collect results.

You are getting the first edition of all these pages. Please let me know if you find an error!

Test frameworks

We have created a well-organized unit test in the previous lab. Our test code is looking good, but we still need to address two issues for it to be truly useful:

  1. We would like to know if multiple test cases are failing.
  2. We would like to collect our test results in a human-friendly format.

Automated test frameworks address these find and execute test code (often through naming conventions like test_*), capture assertion exceptions (test case failures), and generate summaries of which tests pass and fail.

Automated test frameworks are an integral part of modern software engineering.

Introducing pytest

We will use an automated test framework for Python called pytest. Test frameworks are language-specific. Java has JUnit, C++ has CPPUnit, JavaScript has multiple options, etc. Automated test frameworks exist for nearly every programming language and do largely the same things.

pytest is a library. Libraries are source code or compiled binaries that provide useful functions. They are almost always written in the same programming language as the program code. Professional software engineers use third-party libraries, often open source, to provide functions that they would otherwise have to write themselves.

In our case, we could write some try-except blocks to catch our assertion exceptions, create counters to track the number of tests passed or failed, and then print out the results. But why do that when we can use a library? No sense in reinventing the wheel.

Installing pytest with pip

We install pytest and another tool we will use later from the CLI. Choose your operating system below and follow the instructions:

pip3 install -U pytest pytest-cov
  
  1. Run these commands first from your Terminal:
    sudo apt update -y && sudo apt upgrade -y
    sudo apt install python3-pip python3-venv
    # Make sure your working directory is the directory the test files are in.
    python3 -m venv .venv  # This will create a subdirectory named .venv/
    
  2. Open Visual Studio Code in the working directory. It is essential that your testing-lab/ directory is the top-level of Visual Studio Code.
  3. Press Ctrl+Shift+P or select View-Command Palette
  4. Search for “environment” and select Python: Create Environment…
  5. Select Venv
  6. Select Use Existing
  7. The integrated Terminal in Visual Studio code should restart, and you should see a little (.venv) at the beginning of the command line. Contact the instructor if you do not.
  8. You will run all subsequent Terminal commands from the integrated Terminal in Visual Studio Code.
  9. From the integrated terminal, run
    pip install pytest pytest-cov
    

What is pip? It is basically the App Store for Python packages. A package contains one or more libraries or executable tools. pip was included when you installed Python on your computer. We will use pip again to install useful packages in future labs.

Running test code with pytest

You should have a testing-lab/ directory containing sample.py and test_sample.py. If not, grab the files from the previous lab Change into the testing-lab/ directory so that it is the working directory in the terminal.

Run pytest test_sample.py in the terminal. You should see console output similar to the following:

collected 3 items                                  

test_sample.py ...                           [100%]

================ 3 passed in 0.01s =================

pytest scans your test file looking for functions that follow the naming convention test_<function_name> and “collects” them. I had three test case functions in my code, but you may have more or less, so your “collected” number may be different. Test case function names must start with test_ for pytest to run them.

pytest then calls each test case separately and checks to see if the test case throws an AssertionError. If so, the test case fails. If not, the test case passes

Let’s introduce errors in our program code sample.py to show pytest collecting multiple test case failures, which is one of our improvements needed for automated unit testing.

Open sample.py and make the following changes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
def palindrome_check(s):
    # cleaned_str = ''.join(s.lower()) 
    cleaned_str = ''.join(s)  # this makes "Kayak" no longer a palindrome because of different case 
    return cleaned_str == cleaned_str[::-1]

def is_prime(n):
    # if n <= 1:
    if n <= 0:  # the algorithm will now say that 1 is prime, which is incorrect by definition
        return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False
    return True

Now run pytest test_sample.py again. Your output should now look something like this:

collected 3 items                                                                                                                                      

test_sample.py FF.                                                                                                                               [100%]

======================================================================= FAILURES =======================================================================
___________________________________________________________________ test_palindrome ____________________________________________________________________

    def test_palindrome():
        assert sample.palindrome_check("kayak")  # the function should return True, giving "assert True"
>       assert sample.palindrome_check("Kayak")
E       AssertionError: assert False
E        +  where False = <function palindrome_check at 0x1023494e0>('Kayak')
E        +    where <function palindrome_check at 0x1023494e0> = sample.palindrome_check

test_sample.py:5: AssertionError
____________________________________________________________________ test_is_prime _____________________________________________________________________

    def test_is_prime():
>       assert sample.is_prime(1) is False
E       assert True is False
E        +  where True = <function is_prime at 0x1023493a0>(1)
E        +    where <function is_prime at 0x1023493a0> = sample.is_prime

test_sample.py:9: AssertionError
=============================================================== short test summary info ================================================================
FAILED test_sample.py::test_palindrome - AssertionError: assert False
FAILED test_sample.py::test_is_prime - assert True is False
============================================================= 2 failed, 1 passed in 0.03s ==============================================================

We can see at the nice human-friendly summary at the end that 2 failed and 1 passed. The names of the test cases that failed are printed, as are the exact assert calls that failed.

Other ways of running pytest

  1. You can run pytest without giving it a target file. pytest will scan the working directory looking for files with the naming convention test_<file>.py. It will collect and run test cases from all test_<file>.py it finds.
  2. Try running pytest --tb=line to get a condensed version of the results if you find the output to be overwhelming.

Recap

We accomplished a couple significant things in this lab:

  1. We installed the pytest package using pip. Again, you only need to do this once.
  2. We ran pytest, which scans for files and functions named test_* and runs them.
  3. pytest collects test case successes and failures independently from one another, allowing us to get more information with each run of our test code.
  4. pytest displays a summary of the results in human-friendly format.
  5. All popular programming languages have a test framework. You will need to seek out one for the language you are working in.

Knowledge check

  • Question: The Python tool we run to install Python packages is called _______.
  • Question: For pytest to find and execute tests automatically, the test files and test cases must begin with __________.
  • Question: (True/False) You can have multiple assert statements in a single test case?
  • Question: Create a file called math.py with the following function:
    def compute_factorial(n):
        if n < 0:
            return "Factorial is not defined for negative numbers."
        elif n == 0 or n == 1:
            return 1
        else:
            factorial = 1
            for i in range(2, n + 1):
                factorial *= i
            return factorial
    
    1. Create a test file.
    2. Implement one or more test cases that cover all program paths in the function.
    3. Use pytest to execute your test code.
Last modified September 30, 2024.