Python > Testing in Python > pytest > Writing Simple Tests with pytest
Simple pytest Test Function
This example demonstrates how to write a simple test function using pytest. We'll create a function that asserts whether two numbers are equal.
Basic Test Function
This code defines three test functions: test_addition
, test_subtraction
, and test_multiplication
. Each function uses the assert
statement to check a condition. If the condition is false, pytest will report the test as failed. To run these tests, simply save this code to a file named test_example.py
and run pytest
from your terminal in the same directory.
def test_addition():
assert 1 + 1 == 2
def test_subtraction():
assert 5 - 3 == 2
def test_multiplication():
assert 2 * 3 == 6
Concepts Behind the Snippet
The core concept here is assertion. An assertion is a statement that verifies a condition is true at a specific point in the code. Testing frameworks like pytest make it easy to write assertions in a structured and repeatable way. Pytest discovers test functions by their naming convention (functions starting with test_
).
Real-Life Use Case
Imagine you're building a calculator application. You would write tests like these to ensure the basic arithmetic operations are functioning correctly. As the application grows in complexity, you'd add more tests covering various scenarios and edge cases.
Best Practices
Interview Tip
When asked about testing, emphasize the importance of test-driven development (TDD). TDD involves writing tests before writing the code they're testing. This helps ensure that the code is designed to be testable and that all requirements are met. You can also mention specific testing frameworks you're familiar with, like pytest or unittest.
When to use them
Use simple assertion tests when you need to quickly verify basic functionality or properties of your code. They are ideal for testing simple functions, data structures, or algorithms. For more complex scenarios involving mocking, database interactions, or external APIs, consider using pytest's more advanced features.
Alternatives
While pytest is popular, Python's built-in unittest
module is another option for writing tests. unittest
is part of the standard library, so no external dependencies are needed. Other alternatives include nose
and doctest
.
Pros of pytest
Cons of pytest
FAQ
-
How do I run these tests?
Save the code to a file (e.g.,test_example.py
) and runpytest
from your terminal in the same directory. -
What happens if a test fails?
Pytest will report the failed assertion and provide information about the expected and actual values. -
Can I run a specific test function?
Yes, you can specify the test function name (e.g.,pytest test_example.py::test_addition
).