Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

python-unit-tests

БесплатноБез исполняемых скриптовНе проверен

Use for any question or task about Python tests, including quick how-to questions and tests for one function: pytest fixtures and conftest.py, parametrize…

testlandот testland★ 18 звёзд на GitHub

Об этом скилле

python-unit-tests

Overview

Per docs.pytest.org/en/stable:

pytest is the de facto Python test framework. Unlike stdlib unittest, it uses function-style tests (no TestCase), fixture-based dependency injection, parametrize for data-driven tests, and plain-assert rewriting for diff-rich failures.

Lifecycle scope: configure / run / fixtures / mocking / coverage / CI. Test code hygiene (assertions, AAA, mocking anti-patterns) is in test-code-conventions (qa-test-review plugin).

Choosing a framework

  1. pytest for new code - the modern default; migration from unittest is mostly mechanical because pytest runs TestCase classes natively.
  2. Match an existing unittest convention when maintaining a legacy suite or constrained to stdlib-only (no pip install) → references/unittest.md. unittest.mock is the canonical mocking library in either style.
  3. doctest only for documentation-as-tests - executable examples in docstrings, not regression coverage → references/doctest.md.
  4. Async code → the standalone pytest-asyncio-patterns skill (loop scoping, modes, AsyncMock).

Step 1 - Install

pip install "pytest>=9"
# Common plugins:
pip install pytest-cov pytest-asyncio pytest-mock pytest-xdist

Step 2 - First test

# test_sum.py
def sum(a, b):
    return a + b

def test_adds_1_and_2():
    assert sum(1, 2) == 3
pytest

pytest auto-discovers via test_*.py / *_test.py filenames and test_* / Test* function/class names (pt-docs).

Step 3 - Configuration

pytest 9 (2025-11-05) reads native TOML. Per pt-config: "Use [tool.pytest] to leverage native TOML types (supported since pytest 9.0)". New projects on pytest 9+ use that table:

# pyproject.toml (pytest 9+)
[tool.pytest]
minversion = "9.0"
testpaths = ["tests"]
python_files = ["test_*.py", "*_test.py"]
addopts = ["-ra"]
strict = true
markers = [
    "slow: marks tests as slow (deselect with -m 'not slow')",
    "integration: marks tests requiring DB/external resources",
]

Per the changelog, strict = true enables strict_config, strict_markers, strict_parametrization_ids and strict_xfail in one switch, and future strictness options join it. Strict markers reject undeclared names, which catches typos like @pytest.mark.skipp (silently skipped before).

Other config locations, and what to keep when a project already has one:

File and table pytest version Notes
pyproject.toml [tool.pytest] 9.0+ Native TOML lists, booleans and numbers.
pyproject.toml [tool.pytest.ini_options] 6.0+ INI-style string values (addopts = "-ra -q"). Per the changelog it "can't be used alongside [tool.pytest]": convert, don't add a second table.
pytest.toml or .pytest.toml [pytest] 9.0+ Per pt-config, "pytest.toml files take precedence over other files, even when empty."
pytest.ini, tox.ini [pytest], setup.cfg [tool:pytest] all Older INI formats; still read.

Per pt-config, "Options from multiple configfiles candidates are never merged - the first match wins", so a stray pytest.ini silently hides the pyproject.toml table. Check which file pytest picked from the configfile: line in the run header.

On pytest 8 or older, keep [tool.pytest.ini_options] with addopts = "-ra --strict-markers --strict-config"; the strict switch does not exist there.

Step 4 - Fixtures

import pytest

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

@pytest.fixture(scope="session")
def app_config():
    return load_config()

@pytest.fixture(autouse=True)
def reset_state():
    yield
    cleanup_after_test()

def test_user_creation(db_connection, app_config):
    user = create_user(db_connection, app_config)
    assert user.id is not None

Fixture scopes: function (default), class, module, package, session. Choose the narrowest scope that doesn't waste setup time. conftest.py shares fixtures across test files in the same directory (and subdirectories). Fixtures are requested by naming them as test-function parameters - pytest "searches for fixtures that have the same names as those parameters" (docs.pytest.org/how-to/fixtures).

Step 5 - Parametrize

@pytest.mark.parametrize("a,b,expected", [
    (1, 2, 3),
    (0, 0, 0),
    (-1, 1, 0),
    (100, 200, 300),
])
def test_sum_parametrized(a, b, expected):
    assert sum(a, b) == expected
``
Полный SKILL.md на GitHub

Установить python-unit-tests в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

.tessl-plugin/plugin.jsonreferences/doctest.mdreferences/unittest.md

FAQ

Что делает скилл python-unit-tests?

Use for any question or task about Python tests, including quick how-to questions and tests for one function: pytest fixtures and conftest.py, parametrize, mocking, markers, slow or untrusted suites, coverage gates and CI. Has pytest 9 config and strict mode, subtests, and a checklist for edge cases and weak assertions.

Как установить скилл python-unit-tests?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл python-unit-tests запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить python-unit-tests с