Introduction ๐
pytest is the most popular testing framework in Python โ simple, powerful, and perfect for both beginners and large-scale applications.
Note
๐ก Advanced features: fixtures, parametrization, plugins
๐ก Works with CI/CD and large applications
1. Install pytest ๐ฆ
install.sh
pip install pytest2. Basic Project Structure ๐งฑ
project_structure.txt
my_project/
โโโ app/
โ โโโ math_ops.py
โ
โโโ tests/
โโโ test_math_ops.pyโ pytest auto-discovers files named test_*.py
3. Writing Your First Test โ
Code to test (math_ops.py)
math_ops.py
def add(a, b):
return a + bTest file (test_math_ops.py)
test_math_ops.py
from app.math_ops import add
def test_add():
assert add(2, 3) == 54. Run pytest โถ๏ธ
run_tests.sh
pytestโ pytest auto-detects and runs all tests
5. Assertions in pytest ๐ง
assert_examples.py
assert a == b
assert a != b
assert x > 10
assert "hello" in message
assert isinstance(obj, MyClass)โ pytest shows detailed failure info
6. Grouping Tests in Classes ๐งฉ
test_class.py
class TestMath:
def test_add(self):
assert 2 + 3 == 5
def test_sub(self):
assert 5 - 2 == 3Note
7. Using Fixtures (MOST IMPORTANT) ๐งฐ
Fixtures provide reusable setup code โ used for DB connections, API clients, objects, etc.
fixtures.py
import pytest
@pytest.fixture
def sample_data():
return {"name": "Sathish", "age": 25"}
def test_name(sample_data):
assert sample_data["name"] == "Sathish"โ pytest injects fixture into test
8. Multiple Fixtures
multi_fixtures.py
@pytest.fixture
def x(): return 10
@pytest.fixture
def y(): return 20
def test_add(x, y):
assert x + y == 309. Parametrized Tests ๐
parametrize.py
import pytest
@pytest.mark.parametrize("a,b,result", [
(2, 3, 5),
(10, 5, 15),
(-1, 1, 0),
])
def test_add(a, b, result):
assert a + b == resultโ Test multiple inputs easily
10. Expected Exceptions โ ๏ธ
exceptions.py
import pytest
def divide(a, b):
return a / b
def test_zero_division():
with pytest.raises(ZeroDivisionError):
divide(10, 0)11. Using conftest.py for Global Fixtures ๐๏ธ
conftest.py
import pytest
@pytest.fixture
def api_url():
return "https://api.example.com"โ All tests in the folder can access this fixture
12. Running Specific Tests ๐ฏ
commands.sh
pytest tests/test_math_ops.py
pytest -k "add"
pytest -m slow13. Marking Tests (slow, db, network) ๐ท๏ธ
markers.py
import pytest
@pytest.mark.slow
def test_big():
assert Truerun_mark.py
pytest -m slow14. Code Coverage ๐
coverage_install.sh
pip install pytest-covrun_coverage.sh
pytest --cov=app --cov-report=term-missingโ Shows how much of your code is tested
15. CI/CD Integration (GitHub Actions) โ๏ธ
github_actions.yml
name: Python Tests
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run tests
run: pytestโ Automatically runs tests on every push
16. Snapshot Testing (pytest-snapshot) ๐ธ
Useful for testing API responses, JSON, HTML, etc.
snapshot.py
def test_api(snapshot):
data = {"name": "Sathish", "age": 25}
snapshot.assert_match(data)17. Mocking with pytest + unittest.mock ๐งช
mocking.py
from unittest.mock import patch
@patch("app.api.fetch_data", return_value={"ok": True})
def test_api(mock_fetch):
from app.api import fetch_data
assert fetch_data() == {"ok": True}โ Mocking helps test code without real API/DB calls
18. Final Example โ Full Test Suite ๐
project_example.txt
project/
โโโ app/
โ โโโ calc.py
โ โโโ api.py
โ
โโโ tests/
โโโ test_calc.py
โโโ test_api.py
โโโ conftest.pyBest Practices ๐ก
- โ Keep tests small and independent
- โ Use fixtures for reusable setup
- โ Use parametrization to avoid repetitive tests
- โ Test both success & failure paths
- โ Run tests in CI/CD pipelines
- โ Maintain 80%+ test coverage
Conclusion ๐
You now understand Unit Testing with pytest! Want the next topic? Try Mocking, Integration Testing, Test-Driven Development (TDD), or CI/CD Pipelines. Just tell me! ๐