< Unit Testing < Pytest

Create a Python Program

Create the following Python program. Save it as multiply.py

def multiply(x, y):
    result = x * y
    return result


def main():
    multiplicand = float(input("Enter a multiplicand: "))
    multiplier = float(input("Enter a multiplier: "))
    product = multiply(multiplicand, multiplier)
    print(f"The product is: {product}")


if __name__ == "__main__":
    main()

Create a Test Program

Create the following Pytest test program. Save it as test_multiply.py

import multiply

def test_input():
    input_values = [
        "2",
        "2"
    ]

    def input(prompt=None):
        return input_values.pop(0)

    multiply.input = input
    assert multiply.main() == None

Test Success

Test the program by running pytest in a terminal or command prompt in the same folder as the two programs above and observe the results.

pytest

Test Failure

Change the test source code somehow, such as replacing one of the input numeric values with characters. Test the program by running pytest again and observe the results.

This article is issued from Wikiversity. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.