Python > Testing in Python > pytest > Running Tests with pytest
Simple Test Function with pytest
This snippet demonstrates a basic test function using pytest. It shows how to write a simple assertion to verify expected behavior.
Defining a Test Function
This code defines a test function named `test_addition`. Pytest automatically discovers and runs functions prefixed with `test_`. Inside the function, the `assert` statement checks if the expression `1 + 1 == 2` is true. If the assertion fails, pytest reports the test as a failure.
def test_addition():
assert 1 + 1 == 2
Running the Test
To run this test, save the code in a file named `test_example.py`. Then, open your terminal, navigate to the directory where you saved the file, and run the command `pytest`. Pytest will find and execute the `test_addition` function, and report the test result.
# Save the code above as test_example.py
# In the terminal, navigate to the directory where test_example.py is saved.
# Run: pytest
Concepts Behind the Snippet
This snippet illustrates the core concept of unit testing: verifying that individual units of code (in this case, a simple addition operation) behave as expected. Pytest simplifies this process by providing a clear and concise syntax for writing tests and a powerful test runner.
Real-Life Use Case
Imagine you are building a calculator application. You can use pytest to write tests for the `add` function, ensuring it correctly adds numbers. This helps catch bugs early in the development process.
Best Practices
Interview Tip
Be prepared to explain the importance of unit testing and how pytest simplifies the testing process. Discuss the benefits of writing tests, such as catching bugs early, improving code quality, and facilitating refactoring.
When to use them
Use unit tests for every unit of code to ensure the correctness of the code and its functionality.
Memory footprint
The memory footprint of pytest in such a small example is minimal. For larger projects, consider using strategies to optimize memory usage, such as test isolation.
Alternatives
Alternatives to pytest include `unittest` (Python's built-in testing framework) and `nose`. Pytest is often preferred for its simplicity, discoverability, and rich set of features.
Pros
Cons
FAQ
-
What does 'assert' do in pytest?
The `assert` statement checks if a condition is true. If the condition is false, the test fails and pytest reports an `AssertionError`. -
Why are test functions prefixed with 'test_'?
Pytest automatically discovers and runs functions that start with `test_`. This is a naming convention that allows pytest to identify which functions are test functions.