Pytest Advanced

Advanced PythonTestingFree Lesson

Advertisement

Introduction

Pytest is a popular testing framework with powerful features for writing clean, maintainable tests.

Fixtures

import pytest

@pytest.fixture
def sample_data():
    return {"name": "test", "values": [1, 2, 3]}

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

def test_with_fixture(sample_data, db_connection):
    assert sample_data["name"] == "test"

Parametrized Tests

@pytest.mark.parametrize("input,expected", [
    (2, 4),
    (3, 9),
    (4, 16),
])
def test_square(input, expected):
    assert input ** 2 == expected

Markers

@pytest.mark.slow
def test_complex_computation():
    pass

@pytest.mark.integration
def test_api_integration():
    pass

# Run only marked tests
# pytest -m slow
# pytest -m "not slow"

Practice Problems

  1. Create fixtures for test data
  2. Parametrize tests for multiple inputs
  3. Use markers to categorize tests
  4. Set up test discovery configuration
  5. Create conftest.py for shared fixtures

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement