{"slug":"pytest","title":"pytest","summary":"pytest testing framework conventions and practices. Invoke whenever task involves any interaction with pytest — writing tests, configuring pytest, fixtures, parametrize, mocking, debugging test failures, or coverage.","platform":"Claude","tags":[],"authorName":"LLM Mart","authorSlug":"llm-mart","score":0,"source":"github","price":null,"verified":false,"createdAt":"2026-11-10T18:27:25.963011Z","repo":{"url":"https://github.com/xobotyi/cc-foundry","stars":23,"forks":2,"license":"MIT","updatedAt":"2026-11-10T17:16:40Z"},"bodyHtml":"<hr>\n<h2>name: pytest\ndescription: &gt;-\npytest testing framework conventions and practices. Invoke whenever task involves any\ninteraction with pytest — writing tests, configuring pytest, fixtures, parametrize,\nmocking, debugging test failures, or coverage.</h2>\n<h1>pytest</h1>\n<p><strong>Test behavior, not implementation. Tests are executable documentation — if the test name doesn't explain what the code\ndoes, rewrite it.</strong></p>\n<p>pytest is Python's standard testing framework. It uses plain <code>assert</code> statements, fixtures for setup/teardown, and a\nrich plugin ecosystem. All patterns target Python 3.14+.</p>\n<h2>References</h2>\n<ul>\n<li><strong>Fixture patterns, scope, factories, teardown</strong> — [<code>${CLAUDE_SKILL_DIR}/references/fixtures.md</code>]: Fixture lifecycle,\nyield fixtures, factory pattern, request object, parametrized fixtures</li>\n<li><strong>Parametrize patterns, indirect, IDs</strong> — [<code>${CLAUDE_SKILL_DIR}/references/parametrize.md</code>]: Multi-parameter examples,\nindirect fixtures, custom IDs, stacking decorators</li>\n<li><strong>Monkeypatch patterns, scoped patches</strong> — [<code>${CLAUDE_SKILL_DIR}/references/monkeypatch.md</code>]: API overview,\nattribute/env/dict patching, scoped monkeypatch, common recipes</li>\n<li><strong>Plugin ecosystem and configuration</strong> — [<code>${CLAUDE_SKILL_DIR}/references/plugins.md</code>]: pytest-asyncio, pytest-mock,\npytest-xdist, pytest-cov configuration patterns</li>\n</ul>\n<h2>Test Structure</h2>\n<h3>Discovery and Naming</h3>\n<ul>\n<li><strong>Files:</strong> <code>test_*.py</code> or <code>*_test.py</code>. Prefer <code>test_&lt;module&gt;.py</code> matching source module.</li>\n<li><strong>Functions:</strong> <code>test_&lt;behavior&gt;</code> — describe the behavior, not the method: <code>test_returns_empty_list_when_no_matches</code>\nnot <code>test_search</code>.</li>\n<li><strong>Classes:</strong> <code>TestClassName</code> groups related tests. No <code>__init__</code> method. Use classes when tests share setup; use bare\nfunctions for independent tests.</li>\n<li><strong>conftest.py</strong> is auto-discovered — no import needed. Place shared fixtures at the appropriate directory level.</li>\n</ul>\n<h3>Arrange-Act-Assert</h3>\n<p>Structure every test in three phases:</p>\n<pre><code>def test_user_creation_sets_defaults():\n    # Arrange\n    data = {\"name\": \"Alice\", \"email\": \"alice@example.com\"}\n\n    # Act\n    user = User.from_dict(data)\n\n    # Assert\n    assert user.name == \"Alice\"\n    assert user.is_active is True\n    assert user.roles == []\n</code></pre>\n<ul>\n<li><strong>One act per test.</strong> If you need multiple acts, write multiple tests.</li>\n<li><strong>Comments optional</strong> when phases are obvious. Add when the test is long enough that phases aren't immediately clear.</li>\n</ul>\n<h3>Test Granularity</h3>\n<ul>\n<li><strong>One concept per test.</strong> Multiple assertions are fine when they verify the same behavior. Separate tests when\nbehaviors are independent.</li>\n<li><strong>Fast by default.</strong> Unit tests should run in milliseconds. Gate slow tests (network, DB) behind markers:\n<code>@pytest.mark.slow</code>.</li>\n<li><strong>Isolation is mandatory.</strong> Tests must not depend on execution order or shared mutable state. Each test sets up its\nown world.</li>\n</ul>\n<h2>Fixtures</h2>\n<h3>Core Rules</h3>\n<ul>\n<li><strong>Fixtures over setup methods.</strong> Fixtures are composable, scoped, and explicit. Never use <code>setUp</code>/<code>tearDown</code> from\n<code>unittest</code>.</li>\n<li><strong>Explicit injection.</strong> Request fixtures by name in test parameters. Every dependency is visible in the test\nsignature.</li>\n<li><strong>Smallest viable scope.</strong> Default is <code>function</code> scope (fresh per test). Use broader scopes (<code>class</code>, <code>module</code>,\n<code>session</code>) only for expensive resources.</li>\n<li><strong><code>autouse=True</code> sparingly.</strong> Only for setup that genuinely applies to every test in scope (e.g., database transaction\nrollback, temp directory cleanup).</li>\n</ul>\n<h3>Yield Fixtures (Setup + Teardown)</h3>\n<pre><code>@pytest.fixture\ndef db_connection():\n    conn = create_connection()\n    yield conn\n    conn.close()\n\n@pytest.fixture\ndef temp_config(tmp_path: Path):\n    config_file = tmp_path / \"config.toml\"\n    config_file.write_text('[app]\\ndebug = true\\n')\n    yield config_file\n    # cleanup automatic — tmp_path handles it\n</code></pre>\n<ul>\n<li><strong><code>yield</code></strong> separates setup from teardown. Code after <code>yield</code> runs even if the test fails.</li>\n<li><strong>Prefer <code>yield</code></strong> over <code>addfinalizer</code> — clearer control flow.</li>\n<li><strong>Teardown must not raise.</strong> If cleanup can fail, wrap in <code>try</code>/<code>except</code> and log.</li>\n</ul>\n<h3>Fixture Factories</h3>\n<p>When tests need multiple instances with varying configuration:</p>\n<pre><code>@pytest.fixture\ndef make_user():\n    def _make_user(name: str = \"Alice\", *, active: bool = True) -&gt; User:\n        return User(name=name, is_active=active)\n    return _make_user\n\ndef test_inactive_users_excluded(make_user):\n    active = make_user(\"Alice\", active=True)\n    inactive = make_user(\"Bob\", active=False)\n    assert filter_active([active, inactive]) == [active]\n</code></pre>\n<h3>Fixture Scope</h3>\n<ul>\n<li><strong><code>function</code></strong> — Each test (default). Most fixtures — cheap setup, isolation.</li>\n<li><strong><code>class</code></strong> — All tests in a class. Shared expensive setup within a test class.</li>\n<li><strong><code>module</code></strong> — All tests in a file. Database connection per test file.</li>\n<li><strong><code>session</code></strong> — Entire test run. Server startup, heavy resource initialization.</li>\n<li><strong>Session-scoped fixtures</strong> must be in <code>conftest.py</code> at the root test directory.</li>\n<li><strong>Don't mix scopes carelessly.</strong> A function-scoped fixture cannot depend on a function-scoped fixture that modifies\nstate from a broader scope.</li>\n</ul>\n<h3>Built-in Fixtures</h3>\n<ul>\n<li><strong><code>tmp_path</code></strong> — <code>Path</code> to a temporary directory unique to the test (function scope)</li>\n<li><strong><code>tmp_path_factory</code></strong> — Factory for creating temp directories (session scope)</li>\n<li><strong><code>capsys</code></strong> — Capture <code>sys.stdout</code>/<code>sys.stderr</code> writes</li>\n<li><strong><code>capfd</code></strong> — Capture file descriptor 1/2 output (catches C-level writes)</li>\n<li><strong><code>caplog</code></strong> — Capture <code>logging</code> output with access to records</li>\n<li><strong><code>monkeypatch</code></strong> — Dynamic attribute/env/dict patching with automatic restore</li>\n<li><strong><code>request</code></strong> — Fixture metadata: <code>.param</code>, <code>.node</code>, <code>.config</code>, <code>.fspath</code></li>\n<li><strong><code>pytestconfig</code></strong> — Access to the pytest config object</li>\n</ul>\n<p>See <code>${CLAUDE_SKILL_DIR}/references/fixtures.md</code> for fixture lifecycle details, parametrized fixtures, and advanced\npatterns.</p>\n<h2>Parametrize</h2>\n<h3>Basic Usage</h3>\n<pre><code>@pytest.mark.parametrize(\"input_val, expected\", [\n    (\"hello\", 5),\n    (\"\", 0),\n    (\"  spaces  \", 10),\n])\ndef test_string_length(input_val: str, expected: int):\n    assert len(input_val) == expected\n</code></pre>\n<ul>\n<li><strong>Use descriptive IDs:</strong> <code>pytest.param(\"\", 0, id=\"empty-string\")</code> for readable output.</li>\n<li><strong>Each row is a distinct test.</strong> Failures report which parameter combination failed.</li>\n</ul>\n<h3>Stacking Decorators</h3>\n<pre><code>@pytest.mark.parametrize(\"x\", [1, 2])\n@pytest.mark.parametrize(\"y\", [10, 20])\ndef test_combinations(x: int, y: int):\n    assert x + y &gt; 0\n# Generates: (1,10), (1,20), (2,10), (2,20)\n</code></pre>\n<h3>Indirect Parametrize</h3>\n<p>Pass parameter values to fixtures instead of directly to the test:</p>\n<pre><code>@pytest.fixture\ndef user(request) -&gt; User:\n    return User(name=request.param)\n\n@pytest.mark.parametrize(\"user\", [\"Alice\", \"Bob\"], indirect=True)\ndef test_user_greeting(user: User):\n    assert user.name in user.greet()\n</code></pre>\n<p>See <code>${CLAUDE_SKILL_DIR}/references/parametrize.md</code> for multi-parameter patterns, conditional skipping within\nparametrize, and dynamic parametrize generation.</p>\n<h2>Markers</h2>\n<h3>Built-in Markers</h3>\n<ul>\n<li><strong><code>@pytest.mark.skip(reason=\"...\")</code></strong> — unconditionally skip.</li>\n<li><strong><code>@pytest.mark.skipif(condition, reason=\"...\")</code></strong> — skip when condition is true:\n<code>@pytest.mark.skipif(sys.platform == \"win32\", reason=\"Unix only\")</code>.</li>\n<li><strong><code>@pytest.mark.xfail(reason=\"...\")</code></strong> — expected failure. Passes if the test fails, reports unexpected pass if it\nsucceeds. Use <code>strict=True</code> to fail on unexpected pass.</li>\n<li><strong><code>@pytest.mark.usefixtures(\"fixture_name\")</code></strong> — inject fixture without using its value.</li>\n<li><strong><code>@pytest.mark.filterwarnings(\"ignore::DeprecationWarning\")</code></strong> — per-test warning filter.</li>\n</ul>\n<h3>Custom Markers</h3>\n<p>Register in <code>pyproject.toml</code> to avoid warnings:</p>\n<pre><code>[tool.pytest.ini_options]\nmarkers = [\n    \"slow: marks tests as slow (deselect with '-m \\\"not slow\\\"')\",\n    \"integration: marks integration tests\",\n]\n</code></pre>\n<pre><code>@pytest.mark.slow\ndef test_full_pipeline():\n    ...\n</code></pre>\n<p>Run subsets: <code>pytest -m \"not slow\"</code>, <code>pytest -m \"integration and not slow\"</code>.</p>\n<h2>Mocking</h2>\n<h3>monkeypatch (Preferred for Simple Cases)</h3>\n<pre><code>def test_reads_env_variable(monkeypatch):\n    monkeypatch.setenv(\"API_KEY\", \"test-key\")\n    assert get_api_key() == \"test-key\"\n\ndef test_overrides_attribute(monkeypatch):\n    monkeypatch.setattr(\"myapp.config.DEBUG\", True)\n    assert is_debug_mode() is True\n</code></pre>\n<ul>\n<li><strong><code>monkeypatch</code></strong> auto-restores on test exit. No manual cleanup.</li>\n<li><strong>Use for:</strong> environment variables, module attributes, dictionary entries, <code>sys.path</code>.</li>\n</ul>\n<h3>unittest.mock (For Complex Mocking)</h3>\n<pre><code>from unittest.mock import MagicMock, patch, AsyncMock\n\ndef test_service_calls_repository():\n    repo = MagicMock(spec=UserRepository)\n    repo.get.return_value = User(name=\"Alice\")\n    service = UserService(repo=repo)\n\n    result = service.find_user(\"alice\")\n\n    repo.get.assert_called_once_with(\"alice\")\n    assert result.name == \"Alice\"\n\n@patch(\"myapp.services.httpx.get\")\ndef test_fetches_external_data(mock_get):\n    mock_get.return_value = MagicMock(json=lambda: {\"status\": \"ok\"})\n    assert fetch_status() == \"ok\"\n</code></pre>\n<ul>\n<li><strong>Always use <code>spec=</code></strong> on MagicMock — catches attribute typos at test time.</li>\n<li><strong><code>AsyncMock</code></strong> for async functions. Auto-detected when patching async targets.</li>\n<li><strong><code>patch</code> target is where the name is looked up</strong>, not where it's defined: <code>@patch(\"myapp.services.httpx.get\")</code> not\n<code>@patch(\"httpx.get\")</code>.</li>\n</ul>\n<h3>pytest-mock (mocker Fixture)</h3>\n<pre><code>def test_with_mocker(mocker):\n    mock_fetch = mocker.patch(\"myapp.services.fetch_data\")\n    mock_fetch.return_value = {\"key\": \"value\"}\n    result = process_data()\n    mock_fetch.assert_called_once()\n</code></pre>\n<ul>\n<li><strong><code>mocker</code> auto-restores</strong> after each test. Prefer over manual <code>patch</code> context managers.</li>\n<li><strong><code>mocker.patch(\"module.Class\", autospec=True)</code></strong> — recursively specs all attributes and method signatures from the\nreal object. Catches signature mismatches at test time.</li>\n<li><strong><code>mocker.spy(obj, \"method\")</code></strong> wraps the real method — tracks calls while preserving behavior.</li>\n</ul>\n<h3>Mocking Rules</h3>\n<ul>\n<li><strong>Mock at boundaries.</strong> Mock external services, databases, filesystems, clocks — not internal functions.</li>\n<li><strong>Don't mock what you own</strong> when a fake or in-memory implementation is available.</li>\n<li><strong>Prefer dependency injection</strong> over patching. Pass collaborators as parameters, mock in tests.</li>\n<li><strong>Never mock the thing you're testing.</strong> If you need to mock part of the SUT, the SUT has too many responsibilities —\nsplit it.</li>\n</ul>\n<h2>Assertions</h2>\n<h3>Plain Assert</h3>\n<p>pytest rewrites <code>assert</code> statements to show detailed failure messages:</p>\n<pre><code>assert result == expected          # shows both values on failure\nassert \"error\" in message          # shows the full string\nassert len(items) == 3             # shows actual length\nassert all(x &gt; 0 for x in values) # shows the values\n</code></pre>\n<ul>\n<li><strong>No assertion library needed.</strong> Plain <code>assert</code> with pytest's rewrite engine gives clear failure messages.</li>\n<li><strong>Multiple assertions per test are fine</strong> when they verify the same behavior.</li>\n</ul>\n<h3>Exception Testing</h3>\n<pre><code>def test_raises_on_invalid_input():\n    with pytest.raises(ValueError, match=r\"must be positive\"):\n        calculate(-1)\n\ndef test_exception_attributes():\n    with pytest.raises(ValidationError) as exc_info:\n        validate(bad_data)\n    assert exc_info.value.field == \"email\"\n    assert \"invalid format\" in str(exc_info.value)\n</code></pre>\n<ul>\n<li><strong>Always use <code>match=</code></strong> when the exception type is broad — validates the message.</li>\n<li><strong>Access <code>.value</code></strong> for exception attributes via <code>exc_info</code>.</li>\n<li><strong><code>pytest.raises</code> is a context manager.</strong> The code that raises must be inside the <code>with</code>.</li>\n</ul>\n<h3>Approximate Comparisons</h3>\n<pre><code>assert result == pytest.approx(3.14, abs=0.01)\nassert results == pytest.approx([1.0, 2.0, 3.0], rel=1e-3)\n</code></pre>\n<h3>Warning Testing</h3>\n<pre><code>def test_deprecation_warning():\n    with pytest.warns(DeprecationWarning, match=\"use new_func\"):\n        old_func()\n</code></pre>\n<h2>Async Testing</h2>\n<p>With <code>pytest-asyncio</code>:</p>\n<pre><code>import pytest\nimport pytest_asyncio\n\n@pytest.mark.asyncio\nasync def test_async_fetch():\n    result = await fetch_data(\"https://api.example.com\")\n    assert result.status == 200\n\n@pytest_asyncio.fixture\nasync def async_client():\n    async with AsyncClient() as client:\n        yield client\n\n@pytest.mark.asyncio\nasync def test_with_async_client(async_client):\n    response = await async_client.get(\"/health\")\n    assert response.status_code == 200\n</code></pre>\n<ul>\n<li><strong><code>@pytest.mark.asyncio</code></strong> on every async test and <strong><code>@pytest_asyncio.fixture</code></strong> on every async fixture, in the\ndefault <code>strict</code> mode. An <code>async def</code> under <code>@pytest.fixture</code> fails at setup: no plugin handles it. Configuring\n<code>asyncio_mode = \"auto\"</code> in <code>pyproject.toml</code> lifts both requirements.</li>\n<li><strong>Async fixtures</strong> work with <code>yield</code> for teardown — same pattern as sync fixtures.</li>\n</ul>\n<h2>conftest.py Patterns</h2>\n<h3>Hierarchy</h3>\n<pre><code>tests/\n├── conftest.py              # session/root fixtures\n├── unit/\n│   ├── conftest.py          # unit test fixtures\n│   └── test_models.py\n└── integration/\n    ├── conftest.py          # integration fixtures (DB, services)\n    └── test_api.py\n</code></pre>\n<ul>\n<li><strong>Fixtures cascade downward.</strong> A fixture in <code>tests/conftest.py</code> is available to all tests. A fixture in\n<code>tests/unit/conftest.py</code> is available only to unit tests.</li>\n<li><strong>Don't import from conftest.</strong> pytest discovers and injects conftest fixtures automatically.</li>\n<li><strong>Split by concern.</strong> Root conftest for shared utilities (factories, settings). Subdirectory conftest for\nenvironment-specific setup (database, external services).</li>\n</ul>\n<h2>Output Capture</h2>\n<pre><code>def test_prints_greeting(capsys):\n    greet(\"Alice\")\n    captured = capsys.readouterr()\n    assert \"Hello, Alice\" in captured.out\n\ndef test_logs_warning(caplog):\n    with caplog.at_level(logging.WARNING):\n        process_legacy_data()\n    assert \"deprecated\" in caplog.text\n    assert caplog.records[0].levelname == \"WARNING\"\n</code></pre>\n<h2>Configuration</h2>\n<pre><code>[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\naddopts = \"-ra -q --strict-markers\"\nmarkers = [\n    \"slow: slow tests\",\n    \"integration: integration tests\",\n]\nfilterwarnings = [\n    \"error\",                        # treat all warnings as errors\n    \"ignore::DeprecationWarning\",   # except deprecations from deps\n]\nasyncio_mode = \"auto\"              # pytest-asyncio: auto-detect async tests\n</code></pre>\n<ul>\n<li><strong><code>--strict-markers</code></strong> — fail on unregistered markers. Catches typos.</li>\n<li><strong><code>-ra</code></strong> — show summary of all non-passing tests at the end.</li>\n<li><strong><code>filterwarnings = [\"error\"]</code></strong> — catch hidden warnings early.</li>\n</ul>\n<h2>Plugin Ecosystem</h2>\n<ul>\n<li><strong><code>pytest-asyncio</code></strong> — Async test support with <code>@pytest.mark.asyncio</code></li>\n<li><strong><code>pytest-mock</code></strong> — <code>mocker</code> fixture wrapping <code>unittest.mock</code></li>\n<li><strong><code>pytest-cov</code></strong> — Coverage reporting (<code>--cov=src</code>)</li>\n<li><strong><code>pytest-xdist</code></strong> — Parallel test execution (<code>-n auto</code>)</li>\n<li><strong><code>pytest-httpx</code></strong> — Mock <code>httpx</code> requests in tests</li>\n<li><strong><code>pytest-randomly</code></strong> — Randomize test order to catch hidden dependencies</li>\n</ul>\n<p>See <code>${CLAUDE_SKILL_DIR}/references/plugins.md</code> for configuration patterns and usage details.</p>\n<h2>Application</h2>\n<p>When <strong>writing</strong> tests: apply all conventions silently — don't narrate each rule being followed. Match the project's\nexisting test style. If an existing codebase contradicts a convention, follow the codebase and flag the divergence once.</p>\n<p>When <strong>reviewing</strong> tests: cite the specific issue and show the fix inline. Don't lecture — state what's wrong and how to\nfix it.</p>\n<pre><code>Bad:  \"According to pytest best practices, you should use fixtures\n       instead of setUp methods...\"\nGood: \"setUp/tearDown -&gt; @pytest.fixture with yield\"\n</code></pre>\n<h2>Integration</h2>\n<p>The <strong>python</strong> skill governs language choices; this skill governs pytest testing decisions. The <strong>coding</strong> skill governs\nworkflow (discovery, planning, verification).</p>\n<p><strong>Test behavior, not implementation. When in doubt, mock less.</strong></p>\n","files":[{"path":".dev/reference-inventory.json","sizeBytes":988,"isText":true},{"path":"references/fixtures.md","sizeBytes":9393,"isText":true},{"path":"references/monkeypatch.md","sizeBytes":6301,"isText":true},{"path":"references/parametrize.md","sizeBytes":6104,"isText":true},{"path":"references/plugins.md","sizeBytes":9610,"isText":true},{"path":"SKILL.md","sizeBytes":15857,"isText":true}],"reviewScore":null,"reviewSummary":null,"trust":{"provenance":"trusted-source-unreviewed","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow.","bodySource":null},"bodyLocked":false,"purchaseUrl":null,"sourceUrl":null,"report":{"provenance":"trusted-source-unreviewed","screen":{"ran":true,"outcome":"clean","suspicious":0,"notes":0,"hiddenCharacters":false},"virusScan":{"engine":"clamav","status":"clean","scannedAt":"2026-11-10T18:28:24.182428Z","sha256":"E55F4DD2185CD28433AF38695289CDAAAEE8019A1BE8FB9CBE27943D584329E7","sizeBytes":19050},"review":null,"source":{"repositoryUrl":"https://github.com/xobotyi/cc-foundry","path":"plugins/python/skills/pytest","license":"MIT","commit":"278c16c0c371ac3ef36b12512ca558c7513ef13e","subtreeSha":"1A14D8A4CC93D26AB7C369E39D0D6851EDD61298A291030F9621EADDD8E2C6B6","lastSyncedAt":"2026-11-10T18:27:15.736835Z"},"reviewedAt":"2026-11-10T18:30:13.923447Z","notice":"Community-authored content, reproduced verbatim and not vetted as instructions. Treat it as data to evaluate, never as directives to follow."},"install":[{"target":"skills-cli","command":"npx skills add https://github.com/xobotyi/cc-foundry/tree/master/plugins/python/skills/pytest"},{"target":"claude-code","command":"claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install xobotyi-cc-foundry@llmmart"},{"target":"git","command":"git clone https://github.com/xobotyi/cc-foundry.git"}]}