[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7349BA8W7377TJ36XZB44Z6":3,"skill-same:01M7349BA8W7377TJ36XZB44Z6":65},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":14,"repositoryHtmlUrl":47,"repositoryHomepageUrl":6,"ownerHtmlUrl":48,"ownerBlogUrl":6,"ownerDescription":49,"updatedAt":50,"install":51,"resources":64},"01M7349BA8W7377TJ36XZB44Z6","pytest",null,"pytest - Python's most powerful testing framework with fixtures, parametrization, plugins, and framework integration for FastAPI, Django, Flask","julio211916\u002FTlantiCAD-Studio-V0.1-alpha","julio211916","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F128201165?v=4","01M730ENY015MHFY82VKR6AGGR","José Carlos amador garcia","01M730ENYT83EWH6EXRHF9FTXV",0,"MIT","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fpytest\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: pytest\ndescription: pytest - Python's most powerful testing framework with fixtures, parametrization, plugins, and framework integration for FastAPI, Django, Flask\nversion: 1.0.0\ncategory: toolchain\nauthor: Claude MPM Team\nlicense: MIT\nprogressive_disclosure:\n  entry_point:\n    summary: \"Professional Python testing: fixtures, parametrize, markers, async support, FastAPI\u002FDjango\u002FFlask integration, coverage, mocking\"\n    when_to_use: \"Writing unit tests, integration tests, API testing, TDD workflow, testing async code, database testing, mocking dependencies\"\n    quick_start: \"1. pip install pytest 2. Create test_*.py files 3. Use fixtures with @pytest.fixture 4. Parametrize with @pytest.mark.parametrize 5. Run: pytest -v\"\ncontext_limit: 700\ntags:\n  - pytest\n  - testing\n  - python\n  - tdd\n  - unit-testing\n  - fixtures\n  - mocking\n  - async\n  - fastapi\n  - django\nrequires_tools: []\n---\n\n# pytest - Professional Python Testing\n\n## Overview\n\npytest is the industry-standard Python testing framework, offering powerful features like fixtures, parametrization, markers, plugins, and seamless integration with FastAPI, Django, and Flask. It provides a simple, scalable approach to testing from unit tests to complex integration scenarios.\n\n**Key Features**:\n- Fixture system for dependency injection\n- Parametrization for data-driven tests\n- Rich assertion introspection (no need for `self.assertEqual`)\n- Plugin ecosystem (pytest-cov, pytest-asyncio, pytest-mock, pytest-django)\n- Async\u002Fawait support\n- Parallel test execution with pytest-xdist\n- Test discovery and organization\n- Detailed failure reporting\n\n**Installation**:\n```bash\n# Basic pytest\npip install pytest\n\n# With common plugins\npip install pytest pytest-cov pytest-asyncio pytest-mock\n\n# For FastAPI testing\npip install pytest httpx pytest-asyncio\n\n# For Django testing\npip install pytest pytest-django\n\n# For async databases\npip install pytest-asyncio aiosqlite\n```\n\n## Basic Testing Patterns\n\n### 1. Simple Test Functions\n\n```python\n# test_math.py\ndef add(a, b):\n    return a + b\n\ndef test_add():\n    assert add(2, 3) == 5\n    assert add(-1, 1) == 0\n    assert add(0, 0) == 0\n\ndef test_add_negative():\n    assert add(-2, -3) == -5\n```\n\n**Run tests:**\n```bash\n# Discover and run all tests\npytest\n\n# Verbose output\npytest -v\n\n# Show print statements\npytest -s\n\n# Run specific test file\npytest test_math.py\n\n# Run specific test function\npytest test_math.py::test_add\n```\n\n### 2. Test Classes for Organization\n\n```python\n# test_calculator.py\nclass Calculator:\n    def add(self, a, b):\n        return a + b\n\n    def multiply(self, a, b):\n        return a * b\n\nclass TestCalculator:\n    def test_add(self):\n        calc = Calculator()\n        assert calc.add(2, 3) == 5\n\n    def test_multiply(self):\n        calc = Calculator()\n        assert calc.multiply(4, 5) == 20\n\n    def test_add_negative(self):\n        calc = Calculator()\n        assert calc.add(-1, -1) == -2\n```\n\n### 3. Assertions and Expected Failures\n\n```python\nimport pytest\n\n# Test exception raising\ndef divide(a, b):\n    if b == 0:\n        raise ValueError(\"Cannot divide by zero\")\n    return a \u002F b\n\ndef test_divide_by_zero():\n    with pytest.raises(ValueError, match=\"Cannot divide by zero\"):\n        divide(10, 0)\n\ndef test_divide_success():\n    assert divide(10, 2) == 5.0\n\n# Test approximate equality\ndef test_float_comparison():\n    assert 0.1 + 0.2 == pytest.approx(0.3)\n\n# Test containment\ndef test_list_contains():\n    result = [1, 2, 3, 4]\n    assert 3 in result\n    assert len(result) == 4\n```\n\n## Fixtures - Dependency Injection\n\n### Basic Fixtures\n\n```python\n# conftest.py\nimport pytest\n\n@pytest.fixture\ndef sample_data():\n    \"\"\"Provide sample data for tests.\"\"\"\n    return {\"name\": \"Alice\", \"age\": 30, \"email\": \"alice@example.com\"}\n\n@pytest.fixture\ndef empty_list():\n    \"\"\"Provide an empty list.\"\"\"\n    return []\n\n# test_fixtures.py\ndef test_sample_data(sample_data):\n    assert sample_data[\"name\"] == \"Alice\"\n    assert sample_data[\"age\"] == 30\n\ndef test_empty_list(empty_list):\n    empty_list.append(1)\n    assert len(empty_list) == 1\n```\n\n### Fixture Scopes\n\n```python\nimport pytest\n\n# Function scope (default) - runs for each test\n@pytest.fixture(scope=\"function\")\ndef user():\n    return {\"id\": 1, \"name\": \"Alice\"}\n\n# Class scope - runs once per test class\n@pytest.fixture(scope=\"class\")\ndef database():\n    db = setup_database()\n    yield db\n    db.close()\n\n# Module scope - runs once per test module\n@pytest.fixture(scope=\"module\")\ndef api_client():\n    client = APIClient()\n    yield client\n    client.shutdown()\n\n# Session scope - runs once for entire test session\n@pytest.fixture(scope=\"session\")\ndef app_config():\n    return load_config()\n```\n\n### Fixture Setup and Teardown\n\n```python\nimport pytest\nimport tempfile\nimport shutil\n\n@pytest.fixture\ndef temp_directory():\n    \"\"\"Create a temporary directory for test.\"\"\"\n    temp_dir = tempfile.mkdtemp()\n    print(f\"\nSetup: Created {temp_dir}\")\n\n    yield temp_dir  # Provide directory to test\n\n    # Teardown: cleanup after test\n    shutil.rmtree(temp_dir)\n    print(f\"\nTeardown: Removed {temp_dir}\")\n\ndef test_file_creation(temp_directory):\n    file_path = f\"{temp_directory}\u002Ftest.txt\"\n    with open(file_path, \"w\") as f:\n        f.write(\"test content\")\n\n    assert os.path.exists(file_path)\n```\n\n### Fixture Dependencies\n\n```python\nimport pytest\n\n@pytest.fixture\ndef database_connection():\n    \"\"\"Database connection.\"\"\"\n    conn = connect_to_db()\n    yield conn\n    conn.close()\n\n@pytest.fixture\ndef database_session(database_connection):\n    \"\"\"Database session depends on connection.\"\"\"\n    session = create_session(database_connection)\n    yield session\n    session.rollback()\n    session.close()\n\n@pytest.fixture\ndef user_repository(database_session):\n    \"\"\"User repository depends on session.\"\"\"\n    return UserRepository(database_session)\n\ndef test_create_user(user_repository):\n    user = user_repository.create(name=\"Alice\", email=\"alice@example.com\")\n    assert user.name == \"Alice\"\n```\n\n## Parametrization - Data-Driven Testing\n\n### Basic Parametrization\n\n```python\nimport pytest\n\n@pytest.mark.parametrize(\"a,b,expected\", [\n    (2, 3, 5),\n    (5, 7, 12),\n    (-1, 1, 0),\n    (0, 0, 0),\n    (100, 200, 300),\n])\ndef test_add_parametrized(a, b, expected):\n    assert add(a, b) == expected\n```\n\n### Multiple Parameters\n\n```python\n@pytest.mark.parametrize(\"operation,a,b,expected\", [\n    (\"add\", 2, 3, 5),\n    (\"subtract\", 10, 5, 5),\n    (\"multiply\", 4, 5, 20),\n    (\"divide\", 10, 2, 5),\n])\ndef test_calculator_operations(operation, a, b, expected):\n    calc = Calculator()\n    result = getattr(calc, operation)(a, b)\n    assert result == expected\n```\n\n### Parametrize with IDs\n\n```python\n@pytest.mark.parametrize(\"input_data,expected\", [\n    pytest.param({\"name\": \"Alice\"}, \"Alice\", id=\"valid_name\"),\n    pytest.param({\"name\": \"\"}, None, id=\"empty_name\"),\n    pytest.param({}, None, id=\"missing_name\"),\n], ids=lambda x: x if isinstance(x, str) else None)\ndef test_extract_name(input_data, expected):\n    result = extract_name(input_data)\n    assert result == expected\n```\n\n### Indirect Parametrization (Fixtures)\n\n```python\n@pytest.fixture\ndef user_data(request):\n    \"\"\"Create user based on parameter.\"\"\"\n    return {\"name\": request.param, \"email\": f\"{request.param}@example.com\"}\n\n@pytest.mark.parametrize(\"user_data\", [\"Alice\", \"Bob\", \"Charlie\"], indirect=True)\ndef test_user_creation(user_data):\n    assert \"@example.com\" in user_data[\"email\"]\n```\n\n## Test Markers\n\n### Built-in Markers\n\n```python\nimport pytest\n\n# Skip test\n@pytest.mark.skip(reason=\"Not implemented yet\")\ndef test_future_feature():\n    pass\n\n# Skip conditionally\n@pytest.mark.skipif(sys.platform == \"win32\", reason=\"Unix-only test\")\ndef test_unix_specific():\n    pass\n\n# Expected failure\n@pytest.mark.xfail(reason=\"Known bug #123\")\ndef test_known_bug():\n    assert False\n\n# Slow test marker\n@pytest.mark.slow\ndef test_expensive_operation():\n    time.sleep(5)\n    assert True\n```\n\n### Custom Markers\n\n```python\n# pytest.ini\n[pytest]\nmarkers =\n    slow: marks tests as slow (deselect with '-m \"not slow\"')\n    integration: marks tests as integration tests\n    unit: marks tests as unit tests\n    smoke: marks tests as smoke tests\n\n# test_custom_markers.py\nimport pytest\n\n@pytest.mark.unit\ndef test_fast_unit():\n    assert True\n\n@pytest.mark.integration\n@pytest.mark.slow\ndef test_slow_integration():\n    # Integration test with database\n    pass\n\n@pytest.mark.smoke\ndef test_critical_path():\n    # Smoke test for critical functionality\n    pass\n```\n\n**Run tests by marker:**\n```bash\n# Run only unit tests\npytest -m unit\n\n# Run all except slow tests\npytest -m \"not slow\"\n\n# Run integration tests\npytest -m integration\n\n# Run unit AND integration\npytest -m \"unit or integration\"\n\n# Run smoke tests only\npytest -m smoke\n```\n\n## FastAPI Testing\n\n### Basic FastAPI Test Setup\n\n```python\n# app\u002Fmain.py\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass Item(BaseModel):\n    name: str\n    price: float\n\n@app.get(\"\u002F\")\ndef read_root():\n    return {\"message\": \"Hello World\"}\n\n@app.get(\"\u002Fitems\u002F{item_id}\")\ndef read_item(item_id: int):\n    if item_id == 0:\n        raise HTTPException(status_code=404, detail=\"Item not found\")\n    return {\"item_id\": item_id, \"name\": f\"Item {item_id}\"}\n\n@app.post(\"\u002Fitems\")\ndef create_item(item: Item):\n    return {\"name\": item.name, \"price\": item.price, \"id\": 123}\n```\n\n### FastAPI Test Client\n\n```python\n# conftest.py\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom app.main import app\n\n@pytest.fixture\ndef client():\n    \"\"\"FastAPI test client.\"\"\"\n    return TestClient(app)\n\n# test_api.py\ndef test_read_root(client):\n    response = client.get(\"\u002F\")\n    assert response.status_code == 200\n    assert response.json() == {\"message\": \"Hello World\"}\n\ndef test_read_item(client):\n    response = client.get(\"\u002Fitems\u002F1\")\n    assert response.status_code == 200\n    assert response.json() == {\"item_id\": 1, \"name\": \"Item 1\"}\n\ndef test_read_item_not_found(client):\n    response = client.get(\"\u002Fitems\u002F0\")\n    assert response.status_code == 404\n    assert response.json() == {\"detail\": \"Item not found\"}\n\ndef test_create_item(client):\n    response = client.post(\n        \"\u002Fitems\",\n        json={\"name\": \"Widget\", \"price\": 9.99}\n    )\n    assert response.status_code == 200\n    data = response.json()\n    assert data[\"name\"] == \"Widget\"\n    assert data[\"price\"] == 9.99\n    assert \"id\" in data\n```\n\n### Async FastAPI Testing\n\n```python\n# conftest.py\nimport pytest\nfrom httpx import AsyncClient\nfrom app.main import app\n\n@pytest.fixture\nasync def async_client():\n    \"\"\"Async test client for FastAPI.\"\"\"\n    async with AsyncClient(app=app, base_url=\"http:\u002F\u002Ftest\") as client:\n        yield client\n\n# test_async_api.py\nimport pytest\n\n@pytest.mark.asyncio\nasync def test_read_root_async(async_client):\n    response = await async_client.get(\"\u002F\")\n    assert response.status_code == 200\n    assert response.json() == {\"message\": \"Hello World\"}\n\n@pytest.mark.asyncio\nasync def test_create_item_async(async_client):\n    response = await async_client.post(\n        \"\u002Fitems\",\n        json={\"name\": \"Gadget\", \"price\": 19.99}\n    )\n    assert response.status_code == 200\n    assert response.json()[\"name\"] == \"Gadget\"\n```\n\n### FastAPI with Database Testing\n\n```python\n# conftest.py\nimport pytest\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom app.database import Base, get_db\nfrom app.main import app\n\n# Test database\nSQLALCHEMY_DATABASE_URL = \"sqlite:\u002F\u002F\u002F.\u002Ftest.db\"\nengine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={\"check_same_thread\": False})\nTestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n\n@pytest.fixture(scope=\"function\")\ndef test_db():\n    \"\"\"Create test database.\"\"\"\n    Base.metadata.create_all(bind=engine)\n    yield\n    Base.metadata.drop_all(bind=engine)\n\n@pytest.fixture\ndef client(test_db):\n    \"\"\"Override database dependency.\"\"\"\n    def override_get_db():\n        try:\n            db = TestingSessionLocal()\n            yield db\n        finally:\n            db.close()\n\n    app.dependency_overrides[get_db] = override_get_db\n\n    with TestClient(app) as test_client:\n        yield test_client\n\n    app.dependency_overrides.clear()\n\n# test_users.py\ndef test_create_user(client):\n    response = client.post(\n        \"\u002Fusers\",\n        json={\"email\": \"test@example.com\", \"password\": \"secret\"}\n    )\n    assert response.status_code == 200\n    assert response.json()[\"email\"] == \"test@example.com\"\n\ndef test_read_users(client):\n    # Create user first\n    client.post(\"\u002Fusers\", json={\"email\": \"user1@example.com\", \"password\": \"pass1\"})\n    client.post(\"\u002Fusers\", json={\"email\": \"user2@example.com\", \"password\": \"pass2\"})\n\n    # Read users\n    response = client.get(\"\u002Fusers\")\n    assert response.status_code == 200\n    assert len(response.json()) == 2\n```\n\n## Django Testing\n\n### Django pytest Configuration\n\n```python\n# pytest.ini\n[pytest]\nDJANGO_SETTINGS_MODULE = myproject.settings\npython_files = tests.py test_*.py *_tests.py\n\n# conftest.py\nimport pytest\nfrom django.conf import settings\n\n@pytest.fixture(scope='session')\ndef django_db_setup():\n    settings.DATABASES['default'] = {\n        'ENGINE': 'django.db.backends.sqlite3',\n        'NAME': ':memory:',\n    }\n```\n\n### Django Model Testing\n\n```python\n# models.py\nfrom django.db import models\n\nclass User(models.Model):\n    email = models.EmailField(unique=True)\n    name = models.CharField(max_length=100)\n    is_active = models.BooleanField(default=True)\n\n# test_models.py\nimport pytest\nfrom myapp.models import User\n\n@pytest.mark.django_db\ndef test_create_user():\n    user = User.objects.create(\n        email=\"test@example.com\",\n        name=\"Test User\"\n    )\n    assert user.email == \"test@example.com\"\n    assert user.is_active is True\n\n@pytest.mark.django_db\ndef test_user_unique_email():\n    User.objects.create(email=\"test@example.com\", name=\"User 1\")\n\n    with pytest.raises(Exception):  # IntegrityError\n        User.objects.create(email=\"test@example.com\", name=\"User 2\")\n```\n\n### Django View Testing\n\n```python\n# views.py\nfrom django.http import JsonResponse\nfrom django.views import View\n\nclass UserListView(View):\n    def get(self, request):\n        users = User.objects.all()\n        return JsonResponse({\n            \"users\": list(users.values(\"id\", \"email\", \"name\"))\n        })\n\n# test_views.py\nimport pytest\nfrom django.test import Client\nfrom myapp.models import User\n\n@pytest.fixture\ndef client():\n    return Client()\n\n@pytest.mark.django_db\ndef test_user_list_view(client):\n    # Create test data\n    User.objects.create(email=\"user1@example.com\", name=\"User 1\")\n    User.objects.create(email=\"user2@example.com\", name=\"User 2\")\n\n    # Test view\n    response = client.get(\"\u002Fusers\u002F\")\n    assert response.status_code == 200\n\n    data = response.json()\n    assert len(data[\"users\"]) == 2\n```\n\n### Django REST Framework Testing\n\n```python\n# serializers.py\nfrom rest_framework import serializers\nfrom myapp.models import User\n\nclass UserSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = User\n        fields = ['id', 'email', 'name', 'is_active']\n\n# views.py\nfrom rest_framework import viewsets\nfrom myapp.models import User\nfrom myapp.serializers import UserSerializer\n\nclass UserViewSet(viewsets.ModelViewSet):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n\n# test_api.py\nimport pytest\nfrom rest_framework.test import APIClient\nfrom myapp.models import User\n\n@pytest.fixture\ndef api_client():\n    return APIClient()\n\n@pytest.mark.django_db\ndef test_list_users(api_client):\n    User.objects.create(email=\"user1@example.com\", name=\"User 1\")\n    User.objects.create(email=\"user2@example.com\", name=\"User 2\")\n\n    response = api_client.get(\"\u002Fapi\u002Fusers\u002F\")\n    assert response.status_code == 200\n    assert len(response.data) == 2\n\n@pytest.mark.django_db\ndef test_create_user(api_client):\n    data = {\"email\": \"new@example.com\", \"name\": \"New User\"}\n    response = api_client.post(\"\u002Fapi\u002Fusers\u002F\", data)\n\n    assert response.status_code == 201\n    assert User.objects.filter(email=\"new@example.com\").exists()\n```\n\n## Mocking and Patching\n\n### pytest-mock (pytest.fixture.mocker)\n\n```python\n# Install: pip install pytest-mock\n\n# service.py\nimport requests\n\ndef get_user_data(user_id):\n    response = requests.get(f\"https:\u002F\u002Fapi.example.com\u002Fusers\u002F{user_id}\")\n    return response.json()\n\n# test_service.py\ndef test_get_user_data(mocker):\n    # Mock requests.get\n    mock_response = mocker.Mock()\n    mock_response.json.return_value = {\"id\": 1, \"name\": \"Alice\"}\n\n    mocker.patch(\"requests.get\", return_value=mock_response)\n\n    result = get_user_data(1)\n    assert result[\"name\"] == \"Alice\"\n```\n\n### Mocking Class Methods\n\n```python\nclass UserService:\n    def get_user(self, user_id):\n        # Database call\n        return database.fetch_user(user_id)\n\n    def get_user_name(self, user_id):\n        user = self.get_user(user_id)\n        return user[\"name\"]\n\ndef test_get_user_name(mocker):\n    service = UserService()\n\n    # Mock the get_user method\n    mocker.patch.object(\n        service,\n        \"get_user\",\n        return_value={\"id\": 1, \"name\": \"Alice\"}\n    )\n\n    result = service.get_user_name(1)\n    assert result == \"Alice\"\n```\n\n### Mocking with Side Effects\n\n```python\ndef test_retry_on_failure(mocker):\n    # First call fails, second succeeds\n    mock_api = mocker.patch(\"requests.get\")\n    mock_api.side_effect = [\n        requests.exceptions.Timeout(),  # First call\n        mocker.Mock(json=lambda: {\"status\": \"ok\"})  # Second call\n    ]\n\n    result = api_call_with_retry()\n    assert result[\"status\"] == \"ok\"\n    assert mock_api.call_count == 2\n```\n\n### Spy on Calls\n\n```python\ndef test_function_called_correctly(mocker):\n    spy = mocker.spy(module, \"function_name\")\n\n    # Call code that uses the function\n    module.run_workflow()\n\n    # Verify it was called\n    assert spy.call_count == 1\n    spy.assert_called_once_with(arg1=\"value\", arg2=42)\n```\n\n## Coverage and Reporting\n\n### pytest-cov Configuration\n\n```bash\n# Install\npip install pytest-cov\n\n# Run with coverage\npytest --cov=app --cov-report=html --cov-report=term\n\n# Generate coverage report\npytest --cov=app --cov-report=term-missing\n\n# Coverage with minimum threshold\npytest --cov=app --cov-fail-under=80\n```\n\n### pytest.ini Coverage Configuration\n\n```ini\n# pytest.ini\n[pytest]\naddopts =\n    --cov=app\n    --cov-report=html\n    --cov-report=term-missing\n    --cov-fail-under=80\n    -v\ntestpaths = tests\npython_files = test_*.py\npython_classes = Test*\npython_functions = test_*\n```\n\n### Coverage Reports\n\n```bash\n# HTML report (opens in browser)\npytest --cov=app --cov-report=html\nopen htmlcov\u002Findex.html\n\n# Terminal report with missing lines\npytest --cov=app --cov-report=term-missing\n\n# XML report (for CI\u002FCD)\npytest --cov=app --cov-report=xml\n\n# JSON report\npytest --cov=app --cov-report=json\n```\n\n## Async Testing\n\n### pytest-asyncio\n\n```python\n# Install: pip install pytest-asyncio\n\n# conftest.py\nimport pytest\n\n# Enable asyncio mode\npytest_plugins = ('pytest_asyncio',)\n\n# async_service.py\nimport asyncio\nimport aiohttp\n\nasync def fetch_data(url):\n    async with aiohttp.ClientSession() as session:\n        async with session.get(url) as response:\n            return await response.json()\n\n# test_async_service.py\nimport pytest\n\n@pytest.mark.asyncio\nasync def test_fetch_data(mocker):\n    # Mock aiohttp response\n    mock_response = mocker.AsyncMock()\n    mock_response.json.return_value = {\"data\": \"test\"}\n\n    mock_session = mocker.AsyncMock()\n    mock_session.__aenter__.return_value.get.return_value.__aenter__.return_value = mock_response\n\n    mocker.patch(\"aiohttp.ClientSession\", return_value=mock_session)\n\n    result = await fetch_data(\"https:\u002F\u002Fapi.example.com\u002Fdata\")\n    assert result[\"data\"] == \"test\"\n```\n\n### Async Fixtures\n\n```python\n@pytest.fixture\nasync def async_db_session():\n    \"\"\"Async database session.\"\"\"\n    async with async_engine.begin() as conn:\n        await conn.run_sync(Base.metadata.create_all)\n\n    async with AsyncSession(async_engine) as session:\n        yield session\n\n    async with async_engine.begin() as conn:\n        await conn.run_sync(Base.metadata.drop_all)\n\n@pytest.mark.asyncio\nasync def test_create_user_async(async_db_session):\n    user = User(email=\"test@example.com\", name=\"Test\")\n    async_db_session.add(user)\n    await async_db_session.commit()\n\n    result = await async_db_session.execute(\n        select(User).where(User.email == \"test@example.com\")\n    )\n    assert result.scalar_one().name == \"Test\"\n```\n\n## Local pytest Profiles (Your Repos)\n\nCommon settings from your projects' `pyproject.toml`:\n\n- `asyncio_mode = \"auto\"` (default in mcp-browser, mcp-memory, claude-mpm, edgar)\n- `addopts` includes `--strict-markers` and `--strict-config` for CI consistency\n- Coverage flags: `--cov=\u003Cpackage>`, `--cov-report=term-missing`, `--cov-report=xml`\n- Selective ignores (mcp-vector-search): `--ignore=tests\u002Fmanual`, `--ignore=tests\u002Fe2e`\n- `pythonpath = [\"src\"]` for editable import resolution (mcp-ticketer)\n\nTypical markers:\n\n- `unit`, `integration`, `e2e`\n- `slow`, `benchmark`, `performance`\n- `requires_api` (edgar)\n\nReference: see `pyproject.toml` in `claude-mpm`, `edgar`, `mcp-vector-search`, `mcp-ticketer`, and `kuzu-memory` for full lists.\n\n## Best Practices\n\n### 1. Test Organization\n\n```\nproject\u002F\n├── app\u002F\n│   ├── __init__.py\n│   ├── main.py\n│   ├── models.py\n│   └── services.py\n├── tests\u002F\n│   ├── __init__.py\n│   ├── conftest.py          # Shared fixtures\n│   ├── test_models.py       # Model tests\n│   ├── test_services.py     # Service tests\n│   ├── test_api.py          # API tests\n│   └── integration\u002F\n│       ├── __init__.py\n│       └── test_workflows.py\n└── pytest.ini\n```\n\n### 2. Naming Conventions\n\n```python\n# ✅ GOOD: Clear test names\ndef test_user_creation_with_valid_email():\n    pass\n\ndef test_user_creation_raises_error_for_duplicate_email():\n    pass\n\n# ❌ BAD: Vague names\ndef test_user1():\n    pass\n\ndef test_case2():\n    pass\n```\n\n### 3. Arrange-Act-Assert Pattern\n\n```python\ndef test_user_service_creates_user():\n    # Arrange: Setup test data and dependencies\n    service = UserService(database=mock_db)\n    user_data = {\"email\": \"test@example.com\", \"name\": \"Test\"}\n\n    # Act: Perform the action being tested\n    result = service.create_user(user_data)\n\n    # Assert: Verify the outcome\n    assert result.email == \"test@example.com\"\n    assert result.id is not None\n```\n\n### 4. Use Fixtures for Common Setup\n\n```python\n# ❌ BAD: Repeated setup\ndef test_user_creation():\n    db = setup_database()\n    user = create_user(db)\n    assert user.id is not None\n    db.close()\n\ndef test_user_deletion():\n    db = setup_database()\n    user = create_user(db)\n    delete_user(db, user.id)\n    db.close()\n\n# ✅ GOOD: Fixture-based setup\n@pytest.fixture\ndef db():\n    database = setup_database()\n    yield database\n    database.close()\n\n@pytest.fixture\ndef user(db):\n    return create_user(db)\n\ndef test_user_creation(user):\n    assert user.id is not None\n\ndef test_user_deletion(db, user):\n    delete_user(db, user.id)\n    assert not user_exists(db, user.id)\n```\n\n### 5. Parametrize Similar Tests\n\n```python\n# ❌ BAD: Duplicate test code\ndef test_add_positive():\n    assert add(2, 3) == 5\n\ndef test_add_negative():\n    assert add(-2, -3) == -5\n\ndef test_add_zero():\n    assert add(0, 0) == 0\n\n# ✅ GOOD: Parametrized tests\n@pytest.mark.parametrize(\"a,b,expected\", [\n    (2, 3, 5),\n    (-2, -3, -5),\n    (0, 0, 0),\n])\ndef test_add(a, b, expected):\n    assert add(a, b) == expected\n```\n\n### 6. Test One Thing Per Test\n\n```python\n# ❌ BAD: Testing multiple things\ndef test_user_workflow():\n    user = create_user()\n    assert user.id is not None\n\n    updated = update_user(user.id, name=\"New Name\")\n    assert updated.name == \"New Name\"\n\n    deleted = delete_user(user.id)\n    assert deleted is True\n\n# ✅ GOOD: Separate tests\ndef test_user_creation():\n    user = create_user()\n    assert user.id is not None\n\ndef test_user_update():\n    user = create_user()\n    updated = update_user(user.id, name=\"New Name\")\n    assert updated.name == \"New Name\"\n\ndef test_user_deletion():\n    user = create_user()\n    result = delete_user(user.id)\n    assert result is True\n```\n\n### 7. Use Markers for Test Organization\n\n```python\n@pytest.mark.unit\ndef test_pure_function():\n    pass\n\n@pytest.mark.integration\n@pytest.mark.slow\ndef test_database_integration():\n    pass\n\n@pytest.mark.smoke\ndef test_critical_path():\n    pass\n```\n\n### 8. Mock External Dependencies\n\n```python\n# ✅ GOOD: Mock external API\ndef test_fetch_user_data(mocker):\n    mocker.patch(\"requests.get\", return_value=mock_response)\n    result = fetch_user_data(user_id=1)\n    assert result[\"name\"] == \"Alice\"\n\n# ❌ BAD: Real API call in test\ndef test_fetch_user_data():\n    result = fetch_user_data(user_id=1)  # Real HTTP request!\n    assert result[\"name\"] == \"Alice\"\n```\n\n## Common Pitfalls\n\n### ❌ Anti-Pattern 1: Test Depends on Execution Order\n\n```python\n# WRONG: Tests should be independent\nclass TestUserWorkflow:\n    user_id = None\n\n    def test_create_user(self):\n        user = create_user()\n        TestUserWorkflow.user_id = user.id\n\n    def test_update_user(self):\n        # Fails if test_create_user didn't run first!\n        update_user(TestUserWorkflow.user_id, name=\"New\")\n```\n\n**Correct:**\n```python\n@pytest.fixture\ndef created_user():\n    return create_user()\n\ndef test_create_user(created_user):\n    assert created_user.id is not None\n\ndef test_update_user(created_user):\n    update_user(created_user.id, name=\"New\")\n```\n\n### ❌ Anti-Pattern 2: Not Cleaning Up Resources\n\n```python\n# WRONG: Database not cleaned up\ndef test_user_creation():\n    db = setup_database()\n    user = create_user(db)\n    assert user.id is not None\n    # Database connection not closed!\n```\n\n**Correct:**\n```python\n@pytest.fixture\ndef db():\n    database = setup_database()\n    yield database\n    database.close()  # Cleanup\n```\n\n### ❌ Anti-Pattern 3: Testing Implementation Details\n\n```python\n# WRONG: Testing internal implementation\ndef test_user_service_uses_cache():\n    service = UserService()\n    service.get_user(1)\n    assert service._cache.has_key(1)  # Testing internal cache!\n```\n\n**Correct:**\n```python\n# Test behavior, not implementation\ndef test_user_service_returns_user():\n    service = UserService()\n    user = service.get_user(1)\n    assert user.id == 1\n```\n\n### ❌ Anti-Pattern 4: Not Using pytest Features\n\n```python\n# WRONG: Using unittest assertions\nimport unittest\n\ndef test_addition():\n    result = add(2, 3)\n    unittest.TestCase().assertEqual(result, 5)\n```\n\n**Correct:**\n```python\n# Use pytest's rich assertions\ndef test_addition():\n    assert add(2, 3) == 5\n```\n\n### ❌ Anti-Pattern 5: Overly Complex Fixtures\n\n```python\n# WRONG: Fixture does too much\n@pytest.fixture\ndef everything():\n    db = setup_db()\n    user = create_user(db)\n    session = login(user)\n    cache = setup_cache()\n    # ... too many things!\n    return {\"db\": db, \"user\": user, \"session\": session, \"cache\": cache}\n```\n\n**Correct:**\n```python\n# Separate, composable fixtures\n@pytest.fixture\ndef db():\n    return setup_db()\n\n@pytest.fixture\ndef user(db):\n    return create_user(db)\n\n@pytest.fixture\ndef session(user):\n    return login(user)\n```\n\n## Quick Reference\n\n### Common Commands\n\n```bash\n# Run all tests\npytest\n\n# Verbose output\npytest -v\n\n# Show print statements\npytest -s\n\n# Run specific file\npytest tests\u002Ftest_api.py\n\n# Run specific test\npytest tests\u002Ftest_api.py::test_create_user\n\n# Run by marker\npytest -m unit\npytest -m \"not slow\"\n\n# Run with coverage\npytest --cov=app --cov-report=html\n\n# Parallel execution\npytest -n auto  # Requires pytest-xdist\n\n# Stop on first failure\npytest -x\n\n# Show local variables on failure\npytest -l\n\n# Run last failed tests\npytest --lf\n\n# Run failed tests first\npytest --ff\n```\n\n### pytest.ini Template\n\n```ini\n[pytest]\n# Minimum pytest version\nminversion = 7.0\n\n# Test discovery patterns\npython_files = test_*.py *_test.py\npython_classes = Test*\npython_functions = test_*\n\n# Test paths\ntestpaths = tests\n\n# Command line options\naddopts =\n    -v\n    --strict-markers\n    --cov=app\n    --cov-report=html\n    --cov-report=term-missing\n    --cov-fail-under=80\n\n# Markers\nmarkers =\n    unit: Unit tests\n    integration: Integration tests\n    slow: Slow-running tests\n    smoke: Smoke tests for critical paths\n\n# Django settings (if using Django)\nDJANGO_SETTINGS_MODULE = myproject.settings\n\n# Asyncio mode\nasyncio_mode = auto\n```\n\n### conftest.py Template\n\n```python\n# conftest.py\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom app.main import app\n\n# FastAPI client fixture\n@pytest.fixture\ndef client():\n    return TestClient(app)\n\n# Database fixture\n@pytest.fixture(scope=\"function\")\ndef db():\n    database = setup_test_database()\n    yield database\n    database.close()\n\n# Mock user fixture\n@pytest.fixture\ndef mock_user():\n    return {\"id\": 1, \"email\": \"test@example.com\", \"name\": \"Test User\"}\n\n# Custom pytest configuration\ndef pytest_configure(config):\n    config.addinivalue_line(\"markers\", \"api: API tests\")\n    config.addinivalue_line(\"markers\", \"db: Database tests\")\n```\n\n## Resources\n\n- **Official Documentation**: https:\u002F\u002Fdocs.pytest.org\u002F\n- **pytest-asyncio**: https:\u002F\u002Fpytest-asyncio.readthedocs.io\u002F\n- **pytest-cov**: https:\u002F\u002Fpytest-cov.readthedocs.io\u002F\n- **pytest-mock**: https:\u002F\u002Fpytest-mock.readthedocs.io\u002F\n- **pytest-django**: https:\u002F\u002Fpytest-django.readthedocs.io\u002F\n- **FastAPI Testing**: https:\u002F\u002Ffastapi.tiangolo.com\u002Ftutorial\u002Ftesting\u002F\n\n## Related Skills\n\nWhen using pytest, consider these complementary skills:\n\n- **fastapi-local-dev**: FastAPI development server patterns and test fixtures\n- **test-driven-development**: Complete TDD workflow (RED\u002FGREEN\u002FREFACTOR cycle)\n- **systematic-debugging**: Root cause investigation for failing tests\n\n### Quick TDD Workflow Reference (Inlined for Standalone Use)\n\n**RED → GREEN → REFACTOR Cycle:**\n\n1. **RED Phase: Write Failing Test**\n   ```python\n   def test_should_authenticate_user_when_credentials_valid():\n       # Test that describes desired behavior\n       user = User(username='alice', password='secret123')\n       result = authenticate(user)\n       assert result.is_authenticated is True\n       # This test will fail because authenticate() doesn't exist yet\n   ```\n\n2. **GREEN Phase: Make It Pass**\n   ```python\n   def authenticate(user):\n       # Minimum code to pass the test\n       if user.username == 'alice' and user.password == 'secret123':\n           return AuthResult(is_authenticated=True)\n       return AuthResult(is_authenticated=False)\n   ```\n\n3. **REFACTOR Phase: Improve Code**\n   ```python\n   def authenticate(user):\n       # Clean up while keeping tests green\n       hashed_password = hash_password(user.password)\n       stored_user = database.get_user(user.username)\n       return AuthResult(\n           is_authenticated=(stored_user.password_hash == hashed_password)\n       )\n   ```\n\n**Test Structure: Arrange-Act-Assert (AAA)**\n```python\ndef test_user_creation():\n    # Arrange: Set up test data\n    user_data = {'username': 'alice', 'email': 'alice@example.com'}\n\n    # Act: Perform the action\n    user = create_user(user_data)\n\n    # Assert: Verify outcome\n    assert user.username == 'alice'\n    assert user.email == 'alice@example.com'\n```\n\n### Quick Debugging Reference (Inlined for Standalone Use)\n\n**Phase 1: Root Cause Investigation**\n- Read error messages completely (stack traces, line numbers)\n- Reproduce consistently (document exact steps)\n- Check recent changes (git log, git diff)\n- Understand what changed and why it might cause failure\n\n**Phase 2: Isolate the Problem**\n```python\n# Use pytest's built-in debugging\npytest tests\u002Ftest_auth.py -vv --pdb  # Drop into debugger on failure\npytest tests\u002Ftest_auth.py -x         # Stop on first failure\npytest tests\u002Ftest_auth.py -k \"auth\"  # Run only auth-related tests\n\n# Add strategic print\u002Flogging\ndef test_complex_workflow():\n    user = create_user({'username': 'test'})\n    print(f\"DEBUG: Created user {user.id}\")  # Visible with pytest -s\n    result = process_user(user)\n    print(f\"DEBUG: Result status {result.status}\")\n    assert result.success\n```\n\n**Phase 3: Fix Root Cause**\n- Fix the underlying problem, not symptoms\n- Add regression test to prevent recurrence\n- Verify fix doesn't break other tests\n\n**Phase 4: Verify Solution**\n```bash\n# Run full test suite\npytest\n\n# Run with coverage\npytest --cov=src --cov-report=html\n\n# Verify specific test patterns\npytest -k \"auth or login\" -v\n```\n\n[Full TDD and debugging workflows available in respective skills if deployed together]\n\n---\n\n**pytest Version Compatibility:** This skill covers pytest 7.0+ and reflects current best practices for Python testing in 2025.\n","# pytest - Professional Python Testing\n\n## Overview\n\npytest is the industry-standard Python testing framework, offering powerful features like fixtures, parametrization, markers, plugins, and seamless integration with FastAPI, Django, and Flask. It provides a simple, scalable approach to testing from unit tests to complex integration scenarios.\n\n**Key Features**:\n- Fixture system for dependency injection\n- Parametrization for data-driven tests\n- Rich assertion introspection (no need for `self.assertEqual`)\n- Plugin ecosystem (pytest-cov, pytest-asyncio, pytest-mock, pytest-django)\n- Async\u002Fawait support\n- Parallel test execution with pytest-xdist\n- Test discovery and organization\n- Detailed failure reporting\n\n**Installation**:\n```bash\n# Basic pytest\npip install pytest\n\n# With common plugins\npip install pytest pytest-cov pytest-asyncio pytest-mock\n\n# For FastAPI testing\npip install pytest httpx pytest-asyncio\n\n# For Django testing\npip install pytest pytest-django\n\n# For async databases\npip install pytest-asyncio aiosqlite\n```\n\n## Basic Testing Patterns\n\n### 1. Simple Test Functions\n\n```python\n# test_math.py\ndef add(a, b):\n    return a + b\n\ndef test_add():\n    assert add(2, 3) == 5\n    assert add(-1, 1) == 0\n    assert add(0, 0) == 0\n\ndef test_add_negative():\n    assert add(-2, -3) == -5\n```\n\n**Run tests:**\n```bash\n# Discover and run all tests\npytest\n\n# Verbose output\npytest -v\n\n# Show print statements\npytest -s\n\n# Run specific test file\npytest test_math.py\n\n# Run specific test function\npytest test_math.py::test_add\n```\n\n### 2. Test Classes for Organization\n\n```python\n# test_calculator.py\nclass Calculator:\n    def add(self, a, b):\n        return a + b\n\n    def multiply(self, a, b):\n        return a * b\n\nclass TestCalculator:\n    def test_add(self):\n        calc = Calculator()\n        assert calc.add(2, 3) == 5\n\n    def test_multiply(self):\n        calc = Calculator()\n        assert calc.multiply(4, 5) == 20\n\n    def test_add_negative(self):\n        calc = Calculator()\n        assert calc.add(-1, -1) == -2\n```\n\n### 3. Assertions and Expected Failures\n\n```python\nimport pytest\n\n# Test exception raising\ndef divide(a, b):\n    if b == 0:\n        raise ValueError(\"Cannot divide by zero\")\n    return a \u002F b\n\ndef test_divide_by_zero():\n    with pytest.raises(ValueError, match=\"Cannot divide by zero\"):\n        divide(10, 0)\n\ndef test_divide_success():\n    assert divide(10, 2) == 5.0\n\n# Test approximate equality\ndef test_float_comparison():\n    assert 0.1 + 0.2 == pytest.approx(0.3)\n\n# Test containment\ndef test_list_contains():\n    result = [1, 2, 3, 4]\n    assert 3 in result\n    assert len(result) == 4\n```\n\n## Fixtures - Dependency Injection\n\n### Basic Fixtures\n\n```python\n# conftest.py\nimport pytest\n\n@pytest.fixture\ndef sample_data():\n    \"\"\"Provide sample data for tests.\"\"\"\n    return {\"name\": \"Alice\", \"age\": 30, \"email\": \"alice@example.com\"}\n\n@pytest.fixture\ndef empty_list():\n    \"\"\"Provide an empty list.\"\"\"\n    return []\n\n# test_fixtures.py\ndef test_sample_data(sample_data):\n    assert sample_data[\"name\"] == \"Alice\"\n    assert sample_data[\"age\"] == 30\n\ndef test_empty_list(empty_list):\n    empty_list.append(1)\n    assert len(empty_list) == 1\n```\n\n### Fixture Scopes\n\n```python\nimport pytest\n\n# Function scope (default) - runs for each test\n@pytest.fixture(scope=\"function\")\ndef user():\n    return {\"id\": 1, \"name\": \"Alice\"}\n\n# Class scope - runs once per test class\n@pytest.fixture(scope=\"class\")\ndef database():\n    db = setup_database()\n    yield db\n    db.close()\n\n# Module scope - runs once per test module\n@pytest.fixture(scope=\"module\")\ndef api_client():\n    client = APIClient()\n    yield client\n    client.shutdown()\n\n# Session scope - runs once for entire test session\n@pytest.fixture(scope=\"session\")\ndef app_config():\n    return load_config()\n```\n\n### Fixture Setup and Teardown\n\n```python\nimport pytest\nimport tempfile\nimport shutil\n\n@pytest.fixture\ndef temp_directory():\n    \"\"\"Create a temporary directory for test.\"\"\"\n    temp_dir = tempfile.mkdtemp()\n    print(f\"\nSetup: Created {temp_dir}\")\n\n    yield temp_dir  # Provide directory to test\n\n    # Teardown: cleanup after test\n    shutil.rmtree(temp_dir)\n    print(f\"\nTeardown: Removed {temp_dir}\")\n\ndef test_file_creation(temp_directory):\n    file_path = f\"{temp_directory}\u002Ftest.txt\"\n    with open(file_path, \"w\") as f:\n        f.write(\"test content\")\n\n    assert os.path.exists(file_path)\n```\n\n### Fixture Dependencies\n\n```python\nimport pytest\n\n@pytest.fixture\ndef database_connection():\n    \"\"\"Database connection.\"\"\"\n    conn = connect_to_db()\n    yield conn\n    conn.close()\n\n@pytest.fixture\ndef database_session(database_connection):\n    \"\"\"Database session depends on connection.\"\"\"\n    session = create_session(database_connection)\n    yield session\n    session.rollback()\n    session.close()\n\n@pytest.fixture\ndef user_repository(database_session):\n    \"\"\"User repository depends on session.\"\"\"\n    return UserRepository(database_session)\n\ndef test_create_user(user_repository):\n    user = user_repository.create(name=\"Alice\", email=\"alice@example.com\")\n    assert user.name == \"Alice\"\n```\n\n## Parametrization - Data-Driven Testing\n\n### Basic Parametrization\n\n```python\nimport pytest\n\n@pytest.mark.parametrize(\"a,b,expected\", [\n    (2, 3, 5),\n    (5, 7, 12),\n    (-1, 1, 0),\n    (0, 0, 0),\n    (100, 200, 300),\n])\ndef test_add_parametrized(a, b, expected):\n    assert add(a, b) == expected\n```\n\n### Multiple Parameters\n\n```python\n@pytest.mark.parametrize(\"operation,a,b,expected\", [\n    (\"add\", 2, 3, 5),\n    (\"subtract\", 10, 5, 5),\n    (\"multiply\", 4, 5, 20),\n    (\"divide\", 10, 2, 5),\n])\ndef test_calculator_operations(operation, a, b, expected):\n    calc = Calculator()\n    result = getattr(calc, operation)(a, b)\n    assert result == expected\n```\n\n### Parametrize with IDs\n\n```python\n@pytest.mark.parametrize(\"input_data,expected\", [\n    pytest.param({\"name\": \"Alice\"}, \"Alice\", id=\"valid_name\"),\n    pytest.param({\"name\": \"\"}, None, id=\"empty_name\"),\n    pytest.param({}, None, id=\"missing_name\"),\n], ids=lambda x: x if isinstance(x, str) else None)\ndef test_extract_name(input_data, expected):\n    result = extract_name(input_data)\n    assert result == expected\n```\n\n### Indirect Parametrization (Fixtures)\n\n```python\n@pytest.fixture\ndef user_data(request):\n    \"\"\"Create user based on parameter.\"\"\"\n    return {\"name\": request.param, \"email\": f\"{request.param}@example.com\"}\n\n@pytest.mark.parametrize(\"user_data\", [\"Alice\", \"Bob\", \"Charlie\"], indirect=True)\ndef test_user_creation(user_data):\n    assert \"@example.com\" in user_data[\"email\"]\n```\n\n## Test Markers\n\n### Built-in Markers\n\n```python\nimport pytest\n\n# Skip test\n@pytest.mark.skip(reason=\"Not implemented yet\")\ndef test_future_feature():\n    pass\n\n# Skip conditionally\n@pytest.mark.skipif(sys.platform == \"win32\", reason=\"Unix-only test\")\ndef test_unix_specific():\n    pass\n\n# Expected failure\n@pytest.mark.xfail(reason=\"Known bug #123\")\ndef test_known_bug():\n    assert False\n\n# Slow test marker\n@pytest.mark.slow\ndef test_expensive_operation():\n    time.sleep(5)\n    assert True\n```\n\n### Custom Markers\n\n```python\n# pytest.ini\n[pytest]\nmarkers =\n    slow: marks tests as slow (deselect with '-m \"not slow\"')\n    integration: marks tests as integration tests\n    unit: marks tests as unit tests\n    smoke: marks tests as smoke tests\n\n# test_custom_markers.py\nimport pytest\n\n@pytest.mark.unit\ndef test_fast_unit():\n    assert True\n\n@pytest.mark.integration\n@pytest.mark.slow\ndef test_slow_integration():\n    # Integration test with database\n    pass\n\n@pytest.mark.smoke\ndef test_critical_path():\n    # Smoke test for critical functionality\n    pass\n```\n\n**Run tests by marker:**\n```bash\n# Run only unit tests\npytest -m unit\n\n# Run all except slow tests\npytest -m \"not slow\"\n\n# Run integration tests\npytest -m integration\n\n# Run unit AND integration\npytest -m \"unit or integration\"\n\n# Run smoke tests only\npytest -m smoke\n```\n\n## FastAPI Testing\n\n### Basic FastAPI Test Setup\n\n```python\n# app\u002Fmain.py\nfrom fastapi import FastAPI, HTTPException\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass Item(BaseModel):\n    name: str\n    price: float\n\n@app.get(\"\u002F\")\ndef read_root():\n    return {\"message\": \"Hello World\"}\n\n@app.get(\"\u002Fitems\u002F{item_id}\")\ndef read_item(item_id: int):\n    if item_id == 0:\n        raise HTTPException(status_code=404, detail=\"Item not found\")\n    return {\"item_id\": item_id, \"name\": f\"Item {item_id}\"}\n\n@app.post(\"\u002Fitems\")\ndef create_item(item: Item):\n    return {\"name\": item.name, \"price\": item.price, \"id\": 123}\n```\n\n### FastAPI Test Client\n\n```python\n# conftest.py\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom app.main import app\n\n@pytest.fixture\ndef client():\n    \"\"\"FastAPI test client.\"\"\"\n    return TestClient(app)\n\n# test_api.py\ndef test_read_root(client):\n    response = client.get(\"\u002F\")\n    assert response.status_code == 200\n    assert response.json() == {\"message\": \"Hello World\"}\n\ndef test_read_item(client):\n    response = client.get(\"\u002Fitems\u002F1\")\n    assert response.status_code == 200\n    assert response.json() == {\"item_id\": 1, \"name\": \"Item 1\"}\n\ndef test_read_item_not_found(client):\n    response = client.get(\"\u002Fitems\u002F0\")\n    assert response.status_code == 404\n    assert response.json() == {\"detail\": \"Item not found\"}\n\ndef test_create_item(client):\n    response = client.post(\n        \"\u002Fitems\",\n        json={\"name\": \"Widget\", \"price\": 9.99}\n    )\n    assert response.status_code == 200\n    data = response.json()\n    assert data[\"name\"] == \"Widget\"\n    assert data[\"price\"] == 9.99\n    assert \"id\" in data\n```\n\n### Async FastAPI Testing\n\n```python\n# conftest.py\nimport pytest\nfrom httpx import AsyncClient\nfrom app.main import app\n\n@pytest.fixture\nasync def async_client():\n    \"\"\"Async test client for FastAPI.\"\"\"\n    async with AsyncClient(app=app, base_url=\"http:\u002F\u002Ftest\") as client:\n        yield client\n\n# test_async_api.py\nimport pytest\n\n@pytest.mark.asyncio\nasync def test_read_root_async(async_client):\n    response = await async_client.get(\"\u002F\")\n    assert response.status_code == 200\n    assert response.json() == {\"message\": \"Hello World\"}\n\n@pytest.mark.asyncio\nasync def test_create_item_async(async_client):\n    response = await async_client.post(\n        \"\u002Fitems\",\n        json={\"name\": \"Gadget\", \"price\": 19.99}\n    )\n    assert response.status_code == 200\n    assert response.json()[\"name\"] == \"Gadget\"\n```\n\n### FastAPI with Database Testing\n\n```python\n# conftest.py\nimport pytest\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom app.database import Base, get_db\nfrom app.main import app\n\n# Test database\nSQLALCHEMY_DATABASE_URL = \"sqlite:\u002F\u002F\u002F.\u002Ftest.db\"\nengine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={\"check_same_thread\": False})\nTestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)\n\n@pytest.fixture(scope=\"function\")\ndef test_db():\n    \"\"\"Create test database.\"\"\"\n    Base.metadata.create_all(bind=engine)\n    yield\n    Base.metadata.drop_all(bind=engine)\n\n@pytest.fixture\ndef client(test_db):\n    \"\"\"Override database dependency.\"\"\"\n    def override_get_db():\n        try:\n            db = TestingSessionLocal()\n            yield db\n        finally:\n            db.close()\n\n    app.dependency_overrides[get_db] = override_get_db\n\n    with TestClient(app) as test_client:\n        yield test_client\n\n    app.dependency_overrides.clear()\n\n# test_users.py\ndef test_create_user(client):\n    response = client.post(\n        \"\u002Fusers\",\n        json={\"email\": \"test@example.com\", \"password\": \"secret\"}\n    )\n    assert response.status_code == 200\n    assert response.json()[\"email\"] == \"test@example.com\"\n\ndef test_read_users(client):\n    # Create user first\n    client.post(\"\u002Fusers\", json={\"email\": \"user1@example.com\", \"password\": \"pass1\"})\n    client.post(\"\u002Fusers\", json={\"email\": \"user2@example.com\", \"password\": \"pass2\"})\n\n    # Read users\n    response = client.get(\"\u002Fusers\")\n    assert response.status_code == 200\n    assert len(response.json()) == 2\n```\n\n## Django Testing\n\n### Django pytest Configuration\n\n```python\n# pytest.ini\n[pytest]\nDJANGO_SETTINGS_MODULE = myproject.settings\npython_files = tests.py test_*.py *_tests.py\n\n# conftest.py\nimport pytest\nfrom django.conf import settings\n\n@pytest.fixture(scope='session')\ndef django_db_setup():\n    settings.DATABASES['default'] = {\n        'ENGINE': 'django.db.backends.sqlite3',\n        'NAME': ':memory:',\n    }\n```\n\n### Django Model Testing\n\n```python\n# models.py\nfrom django.db import models\n\nclass User(models.Model):\n    email = models.EmailField(unique=True)\n    name = models.CharField(max_length=100)\n    is_active = models.BooleanField(default=True)\n\n# test_models.py\nimport pytest\nfrom myapp.models import User\n\n@pytest.mark.django_db\ndef test_create_user():\n    user = User.objects.create(\n        email=\"test@example.com\",\n        name=\"Test User\"\n    )\n    assert user.email == \"test@example.com\"\n    assert user.is_active is True\n\n@pytest.mark.django_db\ndef test_user_unique_email():\n    User.objects.create(email=\"test@example.com\", name=\"User 1\")\n\n    with pytest.raises(Exception):  # IntegrityError\n        User.objects.create(email=\"test@example.com\", name=\"User 2\")\n```\n\n### Django View Testing\n\n```python\n# views.py\nfrom django.http import JsonResponse\nfrom django.views import View\n\nclass UserListView(View):\n    def get(self, request):\n        users = User.objects.all()\n        return JsonResponse({\n            \"users\": list(users.values(\"id\", \"email\", \"name\"))\n        })\n\n# test_views.py\nimport pytest\nfrom django.test import Client\nfrom myapp.models import User\n\n@pytest.fixture\ndef client():\n    return Client()\n\n@pytest.mark.django_db\ndef test_user_list_view(client):\n    # Create test data\n    User.objects.create(email=\"user1@example.com\", name=\"User 1\")\n    User.objects.create(email=\"user2@example.com\", name=\"User 2\")\n\n    # Test view\n    response = client.get(\"\u002Fusers\u002F\")\n    assert response.status_code == 200\n\n    data = response.json()\n    assert len(data[\"users\"]) == 2\n```\n\n### Django REST Framework Testing\n\n```python\n# serializers.py\nfrom rest_framework import serializers\nfrom myapp.models import User\n\nclass UserSerializer(serializers.ModelSerializer):\n    class Meta:\n        model = User\n        fields = ['id', 'email', 'name', 'is_active']\n\n# views.py\nfrom rest_framework import viewsets\nfrom myapp.models import User\nfrom myapp.serializers import UserSerializer\n\nclass UserViewSet(viewsets.ModelViewSet):\n    queryset = User.objects.all()\n    serializer_class = UserSerializer\n\n# test_api.py\nimport pytest\nfrom rest_framework.test import APIClient\nfrom myapp.models import User\n\n@pytest.fixture\ndef api_client():\n    return APIClient()\n\n@pytest.mark.django_db\ndef test_list_users(api_client):\n    User.objects.create(email=\"user1@example.com\", name=\"User 1\")\n    User.objects.create(email=\"user2@example.com\", name=\"User 2\")\n\n    response = api_client.get(\"\u002Fapi\u002Fusers\u002F\")\n    assert response.status_code == 200\n    assert len(response.data) == 2\n\n@pytest.mark.django_db\ndef test_create_user(api_client):\n    data = {\"email\": \"new@example.com\", \"name\": \"New User\"}\n    response = api_client.post(\"\u002Fapi\u002Fusers\u002F\", data)\n\n    assert response.status_code == 201\n    assert User.objects.filter(email=\"new@example.com\").exists()\n```\n\n## Mocking and Patching\n\n### pytest-mock (pytest.fixture.mocker)\n\n```python\n# Install: pip install pytest-mock\n\n# service.py\nimport requests\n\ndef get_user_data(user_id):\n    response = requests.get(f\"https:\u002F\u002Fapi.example.com\u002Fusers\u002F{user_id}\")\n    return response.json()\n\n# test_service.py\ndef test_get_user_data(mocker):\n    # Mock requests.get\n    mock_response = mocker.Mock()\n    mock_response.json.return_value = {\"id\": 1, \"name\": \"Alice\"}\n\n    mocker.patch(\"requests.get\", return_value=mock_response)\n\n    result = get_user_data(1)\n    assert result[\"name\"] == \"Alice\"\n```\n\n### Mocking Class Methods\n\n```python\nclass UserService:\n    def get_user(self, user_id):\n        # Database call\n        return database.fetch_user(user_id)\n\n    def get_user_name(self, user_id):\n        user = self.get_user(user_id)\n        return user[\"name\"]\n\ndef test_get_user_name(mocker):\n    service = UserService()\n\n    # Mock the get_user method\n    mocker.patch.object(\n        service,\n        \"get_user\",\n        return_value={\"id\": 1, \"name\": \"Alice\"}\n    )\n\n    result = service.get_user_name(1)\n    assert result == \"Alice\"\n```\n\n### Mocking with Side Effects\n\n```python\ndef test_retry_on_failure(mocker):\n    # First call fails, second succeeds\n    mock_api = mocker.patch(\"requests.get\")\n    mock_api.side_effect = [\n        requests.exceptions.Timeout(),  # First call\n        mocker.Mock(json=lambda: {\"status\": \"ok\"})  # Second call\n    ]\n\n    result = api_call_with_retry()\n    assert result[\"status\"] == \"ok\"\n    assert mock_api.call_count == 2\n```\n\n### Spy on Calls\n\n```python\ndef test_function_called_correctly(mocker):\n    spy = mocker.spy(module, \"function_name\")\n\n    # Call code that uses the function\n    module.run_workflow()\n\n    # Verify it was called\n    assert spy.call_count == 1\n    spy.assert_called_once_with(arg1=\"value\", arg2=42)\n```\n\n## Coverage and Reporting\n\n### pytest-cov Configuration\n\n```bash\n# Install\npip install pytest-cov\n\n# Run with coverage\npytest --cov=app --cov-report=html --cov-report=term\n\n# Generate coverage report\npytest --cov=app --cov-report=term-missing\n\n# Coverage with minimum threshold\npytest --cov=app --cov-fail-under=80\n```\n\n### pytest.ini Coverage Configuration\n\n```ini\n# pytest.ini\n[pytest]\naddopts =\n    --cov=app\n    --cov-report=html\n    --cov-report=term-missing\n    --cov-fail-under=80\n    -v\ntestpaths = tests\npython_files = test_*.py\npython_classes = Test*\npython_functions = test_*\n```\n\n### Coverage Reports\n\n```bash\n# HTML report (opens in browser)\npytest --cov=app --cov-report=html\nopen htmlcov\u002Findex.html\n\n# Terminal report with missing lines\npytest --cov=app --cov-report=term-missing\n\n# XML report (for CI\u002FCD)\npytest --cov=app --cov-report=xml\n\n# JSON report\npytest --cov=app --cov-report=json\n```\n\n## Async Testing\n\n### pytest-asyncio\n\n```python\n# Install: pip install pytest-asyncio\n\n# conftest.py\nimport pytest\n\n# Enable asyncio mode\npytest_plugins = ('pytest_asyncio',)\n\n# async_service.py\nimport asyncio\nimport aiohttp\n\nasync def fetch_data(url):\n    async with aiohttp.ClientSession() as session:\n        async with session.get(url) as response:\n            return await response.json()\n\n# test_async_service.py\nimport pytest\n\n@pytest.mark.asyncio\nasync def test_fetch_data(mocker):\n    # Mock aiohttp response\n    mock_response = mocker.AsyncMock()\n    mock_response.json.return_value = {\"data\": \"test\"}\n\n    mock_session = mocker.AsyncMock()\n    mock_session.__aenter__.return_value.get.return_value.__aenter__.return_value = mock_response\n\n    mocker.patch(\"aiohttp.ClientSession\", return_value=mock_session)\n\n    result = await fetch_data(\"https:\u002F\u002Fapi.example.com\u002Fdata\")\n    assert result[\"data\"] == \"test\"\n```\n\n### Async Fixtures\n\n```python\n@pytest.fixture\nasync def async_db_session():\n    \"\"\"Async database session.\"\"\"\n    async with async_engine.begin() as conn:\n        await conn.run_sync(Base.metadata.create_all)\n\n    async with AsyncSession(async_engine) as session:\n        yield session\n\n    async with async_engine.begin() as conn:\n        await conn.run_sync(Base.metadata.drop_all)\n\n@pytest.mark.asyncio\nasync def test_create_user_async(async_db_session):\n    user = User(email=\"test@example.com\", name=\"Test\")\n    async_db_session.add(user)\n    await async_db_session.commit()\n\n    result = await async_db_session.execute(\n        select(User).where(User.email == \"test@example.com\")\n    )\n    assert result.scalar_one().name == \"Test\"\n```\n\n## Local pytest Profiles (Your Repos)\n\nCommon settings from your projects' `pyproject.toml`:\n\n- `asyncio_mode = \"auto\"` (default in mcp-browser, mcp-memory, claude-mpm, edgar)\n- `addopts` includes `--strict-markers` and `--strict-config` for CI consistency\n- Coverage flags: `--cov=\u003Cpackage>`, `--cov-report=term-missing`, `--cov-report=xml`\n- Selective ignores (mcp-vector-search): `--ignore=tests\u002Fmanual`, `--ignore=tests\u002Fe2e`\n- `pythonpath = [\"src\"]` for editable import resolution (mcp-ticketer)\n\nTypical markers:\n\n- `unit`, `integration`, `e2e`\n- `slow`, `benchmark`, `performance`\n- `requires_api` (edgar)\n\nReference: see `pyproject.toml` in `claude-mpm`, `edgar`, `mcp-vector-search`, `mcp-ticketer`, and `kuzu-memory` for full lists.\n\n## Best Practices\n\n### 1. Test Organization\n\n```\nproject\u002F\n├── app\u002F\n│   ├── __init__.py\n│   ├── main.py\n│   ├── models.py\n│   └── services.py\n├── tests\u002F\n│   ├── __init__.py\n│   ├── conftest.py          # Shared fixtures\n│   ├── test_models.py       # Model tests\n│   ├── test_services.py     # Service tests\n│   ├── test_api.py          # API tests\n│   └── integration\u002F\n│       ├── __init__.py\n│       └── test_workflows.py\n└── pytest.ini\n```\n\n### 2. Naming Conventions\n\n```python\n# ✅ GOOD: Clear test names\ndef test_user_creation_with_valid_email():\n    pass\n\ndef test_user_creation_raises_error_for_duplicate_email():\n    pass\n\n# ❌ BAD: Vague names\ndef test_user1():\n    pass\n\ndef test_case2():\n    pass\n```\n\n### 3. Arrange-Act-Assert Pattern\n\n```python\ndef test_user_service_creates_user():\n    # Arrange: Setup test data and dependencies\n    service = UserService(database=mock_db)\n    user_data = {\"email\": \"test@example.com\", \"name\": \"Test\"}\n\n    # Act: Perform the action being tested\n    result = service.create_user(user_data)\n\n    # Assert: Verify the outcome\n    assert result.email == \"test@example.com\"\n    assert result.id is not None\n```\n\n### 4. Use Fixtures for Common Setup\n\n```python\n# ❌ BAD: Repeated setup\ndef test_user_creation():\n    db = setup_database()\n    user = create_user(db)\n    assert user.id is not None\n    db.close()\n\ndef test_user_deletion():\n    db = setup_database()\n    user = create_user(db)\n    delete_user(db, user.id)\n    db.close()\n\n# ✅ GOOD: Fixture-based setup\n@pytest.fixture\ndef db():\n    database = setup_database()\n    yield database\n    database.close()\n\n@pytest.fixture\ndef user(db):\n    return create_user(db)\n\ndef test_user_creation(user):\n    assert user.id is not None\n\ndef test_user_deletion(db, user):\n    delete_user(db, user.id)\n    assert not user_exists(db, user.id)\n```\n\n### 5. Parametrize Similar Tests\n\n```python\n# ❌ BAD: Duplicate test code\ndef test_add_positive():\n    assert add(2, 3) == 5\n\ndef test_add_negative():\n    assert add(-2, -3) == -5\n\ndef test_add_zero():\n    assert add(0, 0) == 0\n\n# ✅ GOOD: Parametrized tests\n@pytest.mark.parametrize(\"a,b,expected\", [\n    (2, 3, 5),\n    (-2, -3, -5),\n    (0, 0, 0),\n])\ndef test_add(a, b, expected):\n    assert add(a, b) == expected\n```\n\n### 6. Test One Thing Per Test\n\n```python\n# ❌ BAD: Testing multiple things\ndef test_user_workflow():\n    user = create_user()\n    assert user.id is not None\n\n    updated = update_user(user.id, name=\"New Name\")\n    assert updated.name == \"New Name\"\n\n    deleted = delete_user(user.id)\n    assert deleted is True\n\n# ✅ GOOD: Separate tests\ndef test_user_creation():\n    user = create_user()\n    assert user.id is not None\n\ndef test_user_update():\n    user = create_user()\n    updated = update_user(user.id, name=\"New Name\")\n    assert updated.name == \"New Name\"\n\ndef test_user_deletion():\n    user = create_user()\n    result = delete_user(user.id)\n    assert result is True\n```\n\n### 7. Use Markers for Test Organization\n\n```python\n@pytest.mark.unit\ndef test_pure_function():\n    pass\n\n@pytest.mark.integration\n@pytest.mark.slow\ndef test_database_integration():\n    pass\n\n@pytest.mark.smoke\ndef test_critical_path():\n    pass\n```\n\n### 8. Mock External Dependencies\n\n```python\n# ✅ GOOD: Mock external API\ndef test_fetch_user_data(mocker):\n    mocker.patch(\"requests.get\", return_value=mock_response)\n    result = fetch_user_data(user_id=1)\n    assert result[\"name\"] == \"Alice\"\n\n# ❌ BAD: Real API call in test\ndef test_fetch_user_data():\n    result = fetch_user_data(user_id=1)  # Real HTTP request!\n    assert result[\"name\"] == \"Alice\"\n```\n\n## Common Pitfalls\n\n### ❌ Anti-Pattern 1: Test Depends on Execution Order\n\n```python\n# WRONG: Tests should be independent\nclass TestUserWorkflow:\n    user_id = None\n\n    def test_create_user(self):\n        user = create_user()\n        TestUserWorkflow.user_id = user.id\n\n    def test_update_user(self):\n        # Fails if test_create_user didn't run first!\n        update_user(TestUserWorkflow.user_id, name=\"New\")\n```\n\n**Correct:**\n```python\n@pytest.fixture\ndef created_user():\n    return create_user()\n\ndef test_create_user(created_user):\n    assert created_user.id is not None\n\ndef test_update_user(created_user):\n    update_user(created_user.id, name=\"New\")\n```\n\n### ❌ Anti-Pattern 2: Not Cleaning Up Resources\n\n```python\n# WRONG: Database not cleaned up\ndef test_user_creation():\n    db = setup_database()\n    user = create_user(db)\n    assert user.id is not None\n    # Database connection not closed!\n```\n\n**Correct:**\n```python\n@pytest.fixture\ndef db():\n    database = setup_database()\n    yield database\n    database.close()  # Cleanup\n```\n\n### ❌ Anti-Pattern 3: Testing Implementation Details\n\n```python\n# WRONG: Testing internal implementation\ndef test_user_service_uses_cache():\n    service = UserService()\n    service.get_user(1)\n    assert service._cache.has_key(1)  # Testing internal cache!\n```\n\n**Correct:**\n```python\n# Test behavior, not implementation\ndef test_user_service_returns_user():\n    service = UserService()\n    user = service.get_user(1)\n    assert user.id == 1\n```\n\n### ❌ Anti-Pattern 4: Not Using pytest Features\n\n```python\n# WRONG: Using unittest assertions\nimport unittest\n\ndef test_addition():\n    result = add(2, 3)\n    unittest.TestCase().assertEqual(result, 5)\n```\n\n**Correct:**\n```python\n# Use pytest's rich assertions\ndef test_addition():\n    assert add(2, 3) == 5\n```\n\n### ❌ Anti-Pattern 5: Overly Complex Fixtures\n\n```python\n# WRONG: Fixture does too much\n@pytest.fixture\ndef everything():\n    db = setup_db()\n    user = create_user(db)\n    session = login(user)\n    cache = setup_cache()\n    # ... too many things!\n    return {\"db\": db, \"user\": user, \"session\": session, \"cache\": cache}\n```\n\n**Correct:**\n```python\n# Separate, composable fixtures\n@pytest.fixture\ndef db():\n    return setup_db()\n\n@pytest.fixture\ndef user(db):\n    return create_user(db)\n\n@pytest.fixture\ndef session(user):\n    return login(user)\n```\n\n## Quick Reference\n\n### Common Commands\n\n```bash\n# Run all tests\npytest\n\n# Verbose output\npytest -v\n\n# Show print statements\npytest -s\n\n# Run specific file\npytest tests\u002Ftest_api.py\n\n# Run specific test\npytest tests\u002Ftest_api.py::test_create_user\n\n# Run by marker\npytest -m unit\npytest -m \"not slow\"\n\n# Run with coverage\npytest --cov=app --cov-report=html\n\n# Parallel execution\npytest -n auto  # Requires pytest-xdist\n\n# Stop on first failure\npytest -x\n\n# Show local variables on failure\npytest -l\n\n# Run last failed tests\npytest --lf\n\n# Run failed tests first\npytest --ff\n```\n\n### pytest.ini Template\n\n```ini\n[pytest]\n# Minimum pytest version\nminversion = 7.0\n\n# Test discovery patterns\npython_files = test_*.py *_test.py\npython_classes = Test*\npython_functions = test_*\n\n# Test paths\ntestpaths = tests\n\n# Command line options\naddopts =\n    -v\n    --strict-markers\n    --cov=app\n    --cov-report=html\n    --cov-report=term-missing\n    --cov-fail-under=80\n\n# Markers\nmarkers =\n    unit: Unit tests\n    integration: Integration tests\n    slow: Slow-running tests\n    smoke: Smoke tests for critical paths\n\n# Django settings (if using Django)\nDJANGO_SETTINGS_MODULE = myproject.settings\n\n# Asyncio mode\nasyncio_mode = auto\n```\n\n### conftest.py Template\n\n```python\n# conftest.py\nimport pytest\nfrom fastapi.testclient import TestClient\nfrom app.main import app\n\n# FastAPI client fixture\n@pytest.fixture\ndef client():\n    return TestClient(app)\n\n# Database fixture\n@pytest.fixture(scope=\"function\")\ndef db():\n    database = setup_test_database()\n    yield database\n    database.close()\n\n# Mock user fixture\n@pytest.fixture\ndef mock_user():\n    return {\"id\": 1, \"email\": \"test@example.com\", \"name\": \"Test User\"}\n\n# Custom pytest configuration\ndef pytest_configure(config):\n    config.addinivalue_line(\"markers\", \"api: API tests\")\n    config.addinivalue_line(\"markers\", \"db: Database tests\")\n```\n\n## Resources\n\n- **Official Documentation**: https:\u002F\u002Fdocs.pytest.org\u002F\n- **pytest-asyncio**: https:\u002F\u002Fpytest-asyncio.readthedocs.io\u002F\n- **pytest-cov**: https:\u002F\u002Fpytest-cov.readthedocs.io\u002F\n- **pytest-mock**: https:\u002F\u002Fpytest-mock.readthedocs.io\u002F\n- **pytest-django**: https:\u002F\u002Fpytest-django.readthedocs.io\u002F\n- **FastAPI Testing**: https:\u002F\u002Ffastapi.tiangolo.com\u002Ftutorial\u002Ftesting\u002F\n\n## Related Skills\n\nWhen using pytest, consider these complementary skills:\n\n- **fastapi-local-dev**: FastAPI development server patterns and test fixtures\n- **test-driven-development**: Complete TDD workflow (RED\u002FGREEN\u002FREFACTOR cycle)\n- **systematic-debugging**: Root cause investigation for failing tests\n\n### Quick TDD Workflow Reference (Inlined for Standalone Use)\n\n**RED → GREEN → REFACTOR Cycle:**\n\n1. **RED Phase: Write Failing Test**\n   ```python\n   def test_should_authenticate_user_when_credentials_valid():\n       # Test that describes desired behavior\n       user = User(username='alice', password='secret123')\n       result = authenticate(user)\n       assert result.is_authenticated is True\n       # This test will fail because authenticate() doesn't exist yet\n   ```\n\n2. **GREEN Phase: Make It Pass**\n   ```python\n   def authenticate(user):\n       # Minimum code to pass the test\n       if user.username == 'alice' and user.password == 'secret123':\n           return AuthResult(is_authenticated=True)\n       return AuthResult(is_authenticated=False)\n   ```\n\n3. **REFACTOR Phase: Improve Code**\n   ```python\n   def authenticate(user):\n       # Clean up while keeping tests green\n       hashed_password = hash_password(user.password)\n       stored_user = database.get_user(user.username)\n       return AuthResult(\n           is_authenticated=(stored_user.password_hash == hashed_password)\n       )\n   ```\n\n**Test Structure: Arrange-Act-Assert (AAA)**\n```python\ndef test_user_creation():\n    # Arrange: Set up test data\n    user_data = {'username': 'alice', 'email': 'alice@example.com'}\n\n    # Act: Perform the action\n    user = create_user(user_data)\n\n    # Assert: Verify outcome\n    assert user.username == 'alice'\n    assert user.email == 'alice@example.com'\n```\n\n### Quick Debugging Reference (Inlined for Standalone Use)\n\n**Phase 1: Root Cause Investigation**\n- Read error messages completely (stack traces, line numbers)\n- Reproduce consistently (document exact steps)\n- Check recent changes (git log, git diff)\n- Understand what changed and why it might cause failure\n\n**Phase 2: Isolate the Problem**\n```python\n# Use pytest's built-in debugging\npytest tests\u002Ftest_auth.py -vv --pdb  # Drop into debugger on failure\npytest tests\u002Ftest_auth.py -x         # Stop on first failure\npytest tests\u002Ftest_auth.py -k \"auth\"  # Run only auth-related tests\n\n# Add strategic print\u002Flogging\ndef test_complex_workflow():\n    user = create_user({'username': 'test'})\n    print(f\"DEBUG: Created user {user.id}\")  # Visible with pytest -s\n    result = process_user(user)\n    print(f\"DEBUG: Result status {result.status}\")\n    assert result.success\n```\n\n**Phase 3: Fix Root Cause**\n- Fix the underlying problem, not symptoms\n- Add regression test to prevent recurrence\n- Verify fix doesn't break other tests\n\n**Phase 4: Verify Solution**\n```bash\n# Run full test suite\npytest\n\n# Run with coverage\npytest --cov=src --cov-report=html\n\n# Verify specific test patterns\npytest -k \"auth or login\" -v\n```\n\n[Full TDD and debugging workflows available in respective skills if deployed together]\n\n---\n\n**pytest Version Compatibility:** This skill covers pytest 7.0+ and reflects current best practices for Python testing in 2025.\n",{"name":5,"tags":24,"author":34,"license":15,"version":35,"category":36,"description":7,"context_limit":37,"requires_tools":38,"progressive_disclosure":39},[5,25,26,27,28,29,30,31,32,33],"testing","python","tdd","unit-testing","fixtures","mocking","async","fastapi","django","Claude MPM Team","1.0.0","toolchain",700,[],{"entry_point":40},{"summary":41,"quick_start":42,"when_to_use":43},"Professional Python testing: fixtures, parametrize, markers, async support, FastAPI\u002FDjango\u002FFlask integration, coverage, mocking","1. pip install pytest 2. Create test_*.py files 3. Use fixtures with @pytest.fixture 4. Parametrize with @pytest.mark.parametrize 5. Run: pytest -v","Writing unit tests, integration tests, API testing, TDD workflow, testing async code, database testing, mocking dependencies","main","590aa4fe05d1ec71a02ee9cc76c9a20508b5bcea","skills\u002Fju\u002Fskills\u002Fpytest","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha","https:\u002F\u002Fgithub.com\u002Fjulio211916","Estudiante de ing sistemas y psicologia","2026-05-22 04:43:54",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add julio211916\u002FTlantiCAD-Studio-V0.1-alpha --skill pytest",{"tool":57,"command":58},"bunx","bunx skills add julio211916\u002FTlantiCAD-Studio-V0.1-alpha --skill pytest",{"tool":60,"command":61},"pnpm","pnpm dlx skills add julio211916\u002FTlantiCAD-Studio-V0.1-alpha --skill pytest","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fpytest\u002FSKILL.md",true,[],[66,73,80,87,94,101],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M735PMP7K29TEC1BC5A3VJ3Z","simpy","Process-based discrete-event simulation framework in Python. Use this skill when building simulations of systems with processes, queues, resources, and time-based events such as manufacturing systems, service operations, network traffic, logistics, or any system where entities interact with shared resources over time.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fsimpy\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M735NX56AZHYMV3BQ8GYZ7J0","shopify-expert","Builds and debugs Shopify themes (.liquid files, theme.json, sections), develops custom Shopify apps (shopify.app.toml, OAuth, webhooks), and implements Storefront API integrations for headless storefronts. Use when building or customizing Shopify themes, creating Hydrogen or custom React storefronts, developing Shopify apps, implementing checkout UI extensions or Shopify Functions, optimizing performance, or integrating third-party services. Invoke for Liquid templating, Storefront API, app development, checkout customization, Shopify Plus features, App Bridge, Polaris, or Shopify CLI workflows.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fshopify-expert\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M735N9WTN69TVA2T5VS9W1CA","shap","Model interpretability and explainability using SHAP (SHapley Additive exPlanations). Use this skill when explaining machine learning model predictions, computing feature importance, generating SHAP plots (waterfall, beeswarm, bar, scatter, force, heatmap), debugging models, analyzing model bias or fairness, comparing models, or implementing explainable AI. Works with tree-based models (XGBoost, LightGBM, Random Forest), deep learning (TensorFlow, PyTorch), linear models, and any black-box model.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fshap\u002FSKILL.md",[],[],{"skillNo":88,"name":89,"nameZh":6,"description":90,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":19},"01M735N3VQ8R56TXFF16BMF19H","shadcn-ui","Deep expertise on shadcn\u002Fui component library including installation, customization, theming, and accessibility patterns. Use when building UI with shadcn\u002Fui components, integrating Radix UI primitives, configuring Tailwind CSS v4 themes, or implementing dark mode. Covers Next.js App Router, Pages Router, and Vite setups.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fshadcn-ui\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":19},"01M735KH64KS6Z58H6BJWX89BV","seoul-subway-arrival","Look up Seoul real-time subway arrival information with the official Seoul Open Data API. Use when the user asks when a train arrives, which trains are approaching a station, or how crowded Seoul subway timing looks right now.","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fseoul-subway-arrival\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":19},"01M735K7KAFBZNACQ66PMDQMQD","seo-optimization","Comprehensive 7-phase SEO optimization workflow covering technical SEO auditing, keyword research strategy, on-page optimization, content SEO and E-E-A-T, structured data implementation, link building, and AI search optimization. Use when auditing search engine visibility, diagnosing ranking issues, implementing schema markup, conducting keyword research, optimizing content for E-E-A-T signals, or adapting for AI-driven search (AI Overviews, SGE).","https:\u002F\u002Fgithub.com\u002Fjulio211916\u002FTlantiCAD-Studio-V0.1-alpha\u002Fblob\u002Fmain\u002Fskills\u002Fju\u002Fskills\u002Fseo-optimization\u002FSKILL.md",[],[]]