pytest Basics
pytest Basics
Python has another popular testing tool called pytest.
Many developers use it because it is simple, powerful, and easy to read.
What Is pytest?
pytest is a testing framework for Python.
It helps you:
- write tests faster
- use simple
assert - run many tests
- read failures clearly
- use advanced features later
Why Learn pytest?
Compared with unittest, pytest often needs less code.
That makes tests easier to write and maintain.
Install pytest
In terminal:
pip install pytest
Basic Test File
Create:
test_math.py
Add:
def add(a, b):
return a + b
def test_add():
assert add(2, 3) == 5
Run Tests
In terminal:
pytest
Example Output
1 passed
How It Works
Test File Name
Use names like:
test_math.py
Test Function Name
Functions should start with:
test_
Example:
def test_add():
Use Plain assert
assert add(2, 3) == 5
If false, the test fails.
Multiple Tests
def add(a, b):
return a + b
def test_add_one():
assert add(1, 1) == 2
def test_add_two():
assert add(0, 5) == 5
def test_add_three():
assert add(-2, 3) == 1
Example Output
3 passed
Example Failure
def test_add():
assert add(2, 2) == 5
Output shows expected vs actual values clearly.
pytest vs unittest
unittest
- class-based style
- methods like
assertEqual()
pytest
- simpler functions
- plain
assert
Both are useful.
Code Along
Create function:
def square(n):
return n * n
Write two pytest tests.
Mini Challenge
Create function:
def is_even(n):
return n % 2 == 0
Write tests for:
2→True3→False0→True
Expected output:
3 passed
Real World Use Case
Many teams use pytest for APIs, web apps, automation tools, data projects, and backend systems.
Quiz
- What is
pytest? - How do you install it?
- What should test function names start with?
- Why do many developers like
pytest?
Assignment
Create a double(n) function and test it with three pytest test functions.
Summary
You learned how to use pytest to write simple and readable automated tests in Python.