Command Palette

Search for a command to run...

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

pytest-asyncio-patterns

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

Use for any question or task about testing async Python code, including how to test an async function, async tests that are skipped or fail with event-loop…

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

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

pytest-asyncio-patterns

Overview

Per pytest-asyncio.readthedocs.io:

pytest-asyncio runs async def test functions under pytest; without it, coroutine tests are collected but never awaited. It provides the @pytest.mark.asyncio marker (or an auto-mode that drops the marker), async-aware fixtures with configurable event-loop scoping, and works with FastAPI/Starlette (via httpx.AsyncClient) and aiohttp (via pytest-aiohttp).

Nearest neighbor: python-unit-tests covers the full framework but treats async in one paragraph. This skill covers the asyncio path end to end: modes, loop scoping, async fixtures, AsyncMock, and framework client patterns.

Step 1 - Install

pip install pytest-asyncio
# For FastAPI / httpx testing:
pip install httpx
# For aiohttp testing:
pip install pytest-aiohttp

Verify the plugin is active:

pytest --co -q   # should show no "PytestUnraisableExceptionWarning" about coroutines

Step 2 - Choose a mode

asyncio_mode has two practical values:

Mode Behavior
strict (default) Only tests marked @pytest.mark.asyncio are collected as async. Async fixtures must use @pytest_asyncio.fixture.
auto All async def test_* functions are automatically treated as asyncio tests. @pytest.fixture works for async fixtures too.

Set in pyproject.toml:

[tool.pytest.ini_options]
asyncio_mode = "auto"

Or override per run: pytest --asyncio-mode=strict. The CLI flag takes precedence over the config file when both are present.

Recommendation: use auto for pure-asyncio projects; use strict when the project mixes async test libraries (e.g., pytest-trio alongside pytest-asyncio) to avoid mode conflicts.

Step 3 - Mark individual tests (strict mode)

import pytest

@pytest.mark.asyncio
async def test_fetch_returns_data():
    result = await fetch_data()
    assert result == {"status": "ok"}

Apply the marker at module level to avoid repeating it:

# test_api.py
import pytest

pytestmark = pytest.mark.asyncio

async def test_one():
    assert await compute() == 42

async def test_two():
    assert await status() == "ready"

In auto mode, neither the decorator nor pytestmark is required.

Step 4 - Event-loop scoping

The loop_scope parameter controls how long an event loop lives:

Scope Loop lifetime
function (default) One loop per test function
class One loop shared across all tests in the class
module One loop shared across all tests in the file
package One loop per package (subdirectory); subpackages do not share with parents
session One loop for the entire test session

Function-scope (the default) provides the strongest isolation. Wider scopes are useful when spinning up a database connection or network server is expensive.

# Share a loop across all tests in a module
@pytest.mark.asyncio(loop_scope="module")
class TestDatabaseSuite:
    async def test_insert(self):
        await db.insert({"key": "val"})

    async def test_read(self):
        result = await db.get("key")
        assert result == "val"

Configure the default loop scope for all tests in pyproject.toml:

[tool.pytest.ini_options]
asyncio_mode = "auto"
asyncio_default_test_loop_scope = "function"

asyncio_default_test_loop_scope defaults to function when unset.

Step 5 - Async fixtures

In strict mode, async fixtures must use @pytest_asyncio.fixture (not @pytest.fixture). In auto mode, @pytest.fixture works for async fixtures too.

import pytest_asyncio

# Strict mode: explicit decorator required
@pytest_asyncio.fixture
async def db_pool():
    pool = await create_pool(dsn="postgresql://localhost/test")
    yield pool
    await pool.close()

# Auto mode: standard decorator works
@pytest.fixture
async def http_session():
    async with aiohttp.ClientSession() as session:
        yield session

Scope async fixtures the same way as sync fixtures:

@pytest_asyncio.fixture(scope="module")
async def app_server():
    server = await start_server(port=0)
    yield server
    await server.stop()

asyncio_default_fixture_loop_scope determines which event loop async fixtures run in; it defaults to matching the fixture's own scope.

Step 6 - Mock async functions with AsyncMock

AsyncMock (stdlib since Python 3.8) makes a mock object behave as a coroutine function. MagicMock does not: calling it returns a coroutine object but inspect.iscoroutinefunction(MagicMock()) is False, which breaks code that checks type before awaiting.

from unittest.mock import AsyncMock, patch
import pytest

@pytest.mark.asyncio
async def test_service_calls_repository():
    mock_repo = AsyncMock()
    mock_repo.find_by_id.return_value = {"id": 1, "name": "Alice"}

    service = UserService(repo=mock_repo)
    result = await service.g
Полный SKILL.md на GitHub

Установить pytest-asyncio-patterns в Claude Code и Claude Desktop

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

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

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

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

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

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

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

.tessl-plugin/plugin.jsonevals/aiohttp-fixed-port-server/criteria.jsonevals/aiohttp-fixed-port-server/task.mdevals/anyio-dual-backend-suite/criteria.jsonevals/anyio-dual-backend-suite/task.mdevals/asyncio-run-in-test-bodies/criteria.jsonevals/asyncio-run-in-test-bodies/task.mdevals/ci-async-tests-silently-skipped/criteria.jsonevals/ci-async-tests-silently-skipped/task.mdevals/fastapi-lifespan-never-fires/criteria.jsonevals/fastapi-lifespan-never-fires/task.mdevals/fastapi-testclient-loop-mismatch/criteria.jsonevals/fastapi-testclient-loop-mismatch/task.mdevals/mock-passes-without-await/criteria.jsonevals/mock-passes-without-await/task.mdevals/patched-client-not-awaitable/criteria.jsonevals/patched-client-not-awaitable/task.mdevals/session-pool-different-loop/criteria.jsonevals/session-pool-different-loop/task.mdevals/strict-mode-async-fixture-ignored/criteria.jsonevals/strict-mode-async-fixture-ignored/task.mdreferences/asyncmock-assertions.mdreferences/framework-clients.md

FAQ

Что делает скилл pytest-asyncio-patterns?

Use for any question or task about testing async Python code, including how to test an async function, async tests that are skipped or fail with event-loop errors, and tests for FastAPI or aiohttp endpoints: pytest-asyncio modes and loop scopes, async fixtures, AsyncMock (assert_awaited), httpx.AsyncClient with ASGITransport and aiohttp_client.

Как установить скилл pytest-asyncio-patterns?

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

Скилл pytest-asyncio-patterns запускает скрипты?

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

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

Сравнить pytest-asyncio-patterns с