Python > Quality and Best Practices > Testing > Testing with `pytest`
Basic pytest Function Test
This snippet demonstrates a basic pytest test function that asserts a simple calculation. It showcases the fundamental structure of a pytest test, including importing the `pytest` library (though implicit in this case) and defining a test function that uses `assert` statements to verify the expected behavior of a function.
Code Snippet
This snippet defines a simple `add` function and a corresponding `test_add` function. The `test_add` function uses `assert` statements to check if the `add` function returns the correct results for different inputs. Pytest automatically discovers and runs any function prefixed with `test_`.
def add(x, y):
return x + y
def test_add():
assert add(2, 3) == 5
assert add(-1, 1) == 0
assert add(0, 0) == 0
Concepts Behind the Snippet
This snippet demonstrates the core concept of unit testing: verifying individual components (functions, methods, classes) in isolation. The `assert` statement is a fundamental building block, raising an `AssertionError` if the condition it tests is false. Pytest simplifies test discovery and execution.
Real-Life Use Case
Imagine testing a function in a financial application that calculates compound interest. You would use `pytest` to create multiple test cases with various principal amounts, interest rates, and time periods, asserting that the calculated interest matches the expected values. This ensures the function's accuracy and reliability.
Best Practices
Interview Tip
Be prepared to explain the importance of unit testing, the structure of a pytest test, and the role of `assert` statements. You might be asked to write a simple test case for a given function. Emphasize the benefits of testing for code quality and maintainability.
When to Use Them
Use pytest tests whenever you're developing a non-trivial function or class. Automated testing is crucial for ensuring code correctness, preventing regressions, and facilitating refactoring.
Alternatives
Alternatives to pytest include `unittest` (Python's built-in testing framework), `nose2`, and `doctest`. Pytest is often preferred for its simplicity, flexibility, and extensive plugin ecosystem.
Pros
Cons
FAQ
-
How do I run this test with pytest?
Save the code in a file named `test_example.py` and then run `pytest` from the command line in the same directory. -
What happens if the assertion fails?
Pytest will raise an `AssertionError` and report the failure, indicating which assertion failed and the expected vs. actual values.