Deep Dive with Pytest Fixtures
For a more complex example, Let’s create a Calculator class with methods to add, subtract, multiplication and division. We’ll explore how fixtures can manage setup and teardown in testing such scenarios.
# calculator.py
class Calculator:
def add(self, a, b):
"""Return the addition of two numbers."""
return a + b
def subtract(self, a, b):
"""Return the subtraction of two numbers."""
return a - b
def multiply(self, a, b):
"""Return the multiplication of two numbers."""
return a * b
def divide(self, a, b):
"""Return the division of two numbers."""
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
Next, we create the test script using Pytest. In this script we will include tests for each arithmetic operation as written in the below code.
In the below code, first we import the pytest module and Calculator class that includes four methods including “add()”, “subtract()”, “multiply()”, and “divide()” for basic arithmetic operations. The “divide()” method raises a ‘ValueError’ if the divisor is zero, to handle the division by zero case. Pytest Fixture “calc” in the above code create a new instance of the ‘Calculator’ class before each test. This ensures that each test is run with a fresh ‘Calculator’ instance, which is a good practice to avoid dependencies between tests. Each test function such as ‘test_addition()’, ‘test_subtraction’ and more receives the ‘calc’ fixture as an argument. The test then use this ‘Calculator’ instance to test various arithmetic operations. For example, ‘test_addition()’ method checks whether the ‘add()’ method correctly adds two numbers or not.
# test_calculator.py
import pytest
from calculator import Calculator
@pytest.fixture
def calc():
"""Provides a Calculator instance."""
return Calculator()
def test_addition(calc):
"""Test addition method."""
assert calc.add(2, 3) == 5
def test_subtraction(calc):
"""Test subtraction method."""
assert calc.subtract(5, 3) == 2
def test_multiplication(calc):
"""Test multiplication method."""
assert calc.multiply(3, 4) == 12
def test_division(calc):
"""Test division method."""
assert calc.divide(8, 2) == 4
def test_division_by_zero(calc):
"""Test division by zero raises ValueError."""
with pytest.raises(ValueError):
calc.divide(10, 0)
Output:
Pytest Tutorial | Unit Testing in Python using Pytest Framework
In the process of development of applications, testing plays a crucial role. It ensures the developers that the application is error-free and the application is running as per the expectation. It should be done to ensure a seamless experience for the user. In this article, we will learn about testing Python applications using Pytest.
Contact Us