Python: How to use the "pytest" Module

Python: How to use the "pytest" Module

Overview

This article will explain how to use the "pytest" module in the Python programming language. "pytest" is used to detect whether statements are True or False by using the assert command (1).

Materials

  • Python 3.6+ or PyPy3 (1)

  • Python modules: pytest, random

  • IDE or Terminal

Installing Pytest

Run the command in the Terminal to download pytest if it is not installed (2):

pip install -U pytest

Procedure

  • Create any Python script where the name of the file must begin with the word "test" and the function of the script has to start with the word "test" or have the first four letters be "test"

  • In the function, have a statement be assessed with the assert keyword to validate if the statement is True or False

  • In the Terminal, type "pytest" to check the files

import random

def test_check_multiplication():
    a = random.randint(1, 2)
    b = random.randint(1, 2)
    c = random.randint(1, 4)
    assert a * b == c
  • If the file and function does not begin with "test", then 0 items will be collected. As shown below, the name of the file begins with the word "testing" and not "test".

  • Items refer to the amount of files that was received in the directory where the "pytest" command is being ran in. "pytest" checks every Python file that begins with the name "test" and each of those files has a function that begins with "test" and contains an assert statement to check, otherwise 0 items will be collected.

  • Since this file utilizes the random module to generate random integers for a, b, and c and then sees if a * b == c, this file has to be ran a couple of times to see if the result is a success or the result is True

A Pytest Error

A Pytest Success

Printing the Statement in the Terminal

  • Instead of writing "pytest", write "pytest -s" and include "print()" statements in the function to output the variable values in the Terminal
import random

def testing_check_multiplication():
    a = random.randint(1, 2)
    b = random.randint(1, 2)
    c = random.randint(1, 4)

    print("Variable a:", a)
    print("Variable b:", b)
    print("a * b:", a * b)
    print("Variable c:", c)

    assert a * b == c

Sources

https://docs.pytest.org/en/8.0.x/ (1)

https://docs.pytest.org/en/6.2.x/getting-started.html (2)

Source Code

https://github.com/AndrewDass1/SCRIPTS/tree/main/Python/Pytest%20Scripts/Pytest%20and%20Random