What is pytest: Simple Explanation and Usage
pytest is a popular Python testing framework that makes it easy to write simple and scalable test code. It helps developers check if their code works correctly by running test functions and reporting results clearly.How It Works
Imagine you want to check if your recipe works well every time you cook. pytest acts like a friendly kitchen helper who tries your recipe step-by-step and tells you if something goes wrong. It looks for special test functions in your code, runs them automatically, and shows you which tests passed or failed.
It works by finding Python functions that start with test_ or classes that contain such functions. When you run pytest, it executes these tests and compares the actual results with what you expect. If they match, the test passes; if not, it fails and shows you details to fix the problem.
Example
This example shows a simple test for a function that adds two numbers. The test checks if the function returns the correct sum.
def add(a: int, b: int) -> int: return a + b def test_add(): assert add(2, 3) == 5 assert add(-1, 1) == 0 assert add(0, 0) == 0
When to Use
Use pytest whenever you want to make sure your Python code works as expected. It is great for testing small functions, big projects, or anything in between. Developers use it to catch bugs early, improve code quality, and automate testing so they don’t have to check everything manually.
For example, if you build a web app, you can write tests to check if user login works or if data is saved correctly. Running pytest regularly helps you find problems quickly before users do.
Key Points
- Easy to write: Tests are simple Python functions with clear assertions.
- Automatic discovery: Finds tests by naming conventions without extra setup.
- Detailed reports: Shows which tests passed or failed with helpful info.
- Extensible: Supports plugins and fixtures for advanced testing needs.