Skip to content

Advanced Pytest

๐Ÿงช Advanced Testing with Pytest

Pytest is the most popular testing framework for Python. It makes it easy to write small tests, yet scales to support complex functional testing.


๐ŸŸข Level 1: Foundations

1. Simple Assertions

Pytest uses standard Python assert statements.

def test_add():
    assert 1 + 1 == 2

2. Parameterization

Run the same test logic with multiple inputs.

import pytest

@pytest.mark.parametrize("input,expected", [(1, 2), (2, 3), (3, 4)])
def test_increment(input, expected):
    assert input + 1 == expected

๐ŸŸก Level 2: Fixtures (The Power of Pytest)

Fixtures provide a clean way to setup and teardown test data or resources.

@pytest.fixture
def db_connection():
    conn = connect_db()
    yield conn
    conn.close()

def test_query(db_connection):
    assert db_connection.query("SELECT 1") == 1

๐Ÿ”ด Level 3: Mocking & Patching

3. unittest.mock Integration

Use mocking to isolate the code under test from external dependencies like APIs or Databases.

from unittest.mock import patch

@patch("requests.get")
def test_api_call(mock_get):
    mock_get.return_value.status_code = 200
    # ... your test code ...