Unit Testing/Pytest/Test Exceptions
< Unit Testing | Pytest
Create a Python Program
editCreate 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
editCreate the following Pytest test program. Save it as test_multiply.py
import pytest
import multiply
def test_invalid_input():
input_values = [
"2",
"X"
]
def input(prompt=None):
return input_values.pop(0)
multiply.input = input
with pytest.raises(ValueError):
multiply.main()
Test Success
editTest 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
editChange the test source code somehow, such as replacing the invalid input with valid input. Test the program by running pytest again and observe the results.