pytest-asyncio-httpx-mocking

A testing guideline for mocking asynchronous HTTP calls in Pytest with Python’s unittest.mock library. AsyncMock represents methods that must be awaited, such as httpx.AsyncClient.get or post.

In plain words
What is it for?
Writing tests for async HTTP clients, replacing async get or post calls, and simulating multiple requests with side effects.
Why use it?
Using a regular MagicMock for an awaited method causes a TypeError because the returned value cannot be awaited.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/project-n-e-k-o/n.e.k.o/pytest-asyncio-httpx-mocking
Any agent
npx skills add Project-N-E-K-O/N.E.K.O --skill pytest-asyncio-httpx-mocking
Clone the repo
git clone --depth 1 https://github.com/Project-N-E-K-O/N.E.K.O

Made for: Claude Code, Codex.

Per session 44 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 590 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00044 $0.00590
Opus 5 $0.00022 $0.00295
Sonnet 5 $0.00009 $0.00118
Haiku 4.5 $0.00004 $0.00059

Measured yesterday against content hash c7d966db4eac, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

pytest-asyncio-httpx-mocking scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured yesterday.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.agent/skills/pytest-asyncio-httpx-mocking/SKILL.md · 49 lines

What it actually says

httpx.AsyncClient Mocking with AsyncMock

症状

  • 在测试中使用 patch.object(httpx.AsyncClient, 'post', return_value=mock_response)
  • 运行时,代码中包含 response = await client.post(...) 的地方抛出 TypeError: object MagicMock can't be used in 'await' expression

根本原因

原因 1: 异步函数的返回值必须是 Coroutine

  • 问题: httpx.AsyncClient.post 是一个 async def 方法,调用它会返回一个可等待(awaitable)的协程。
  • 为什么发生: 默认的 patchMagicMock 没有自动推断对象的异步特性时,它只是同步地返回了 return_value。当事件循环试图 await 这个同步的 MagicMock 对象时,就会报错。
  • 解决方案: 在 patch 参数里显式使用 new=AsyncMock(return_value=...)new_callable=AsyncMock

代码解决方案

❌ 错误写法:

from unittest.mock import patch, MagicMock

mock_response = MagicMock(status_code=200)
# 当被 await 时会触发 TypeError!
with patch.object(httpx.AsyncClient, 'post', return_value=mock_response):
    await my_crawler.fetch()

✅ 正确写法:

from unittest.mock import patch, MagicMock, AsyncMock

mock_response = MagicMock(status_code=200) # Response 对象本身及其方法通常是同步的
# 正确!覆盖掉原来的方法,使其行为成为一个 AsyncMock
with patch.object(httpx.AsyncClient, 'post', new=AsyncMock(return_value=mock_response)):
    await my_crawler.fetch()

使用 side_effect 模拟循序多次请求:

with patch.object(httpx.AsyncClient, 'get', new=AsyncMock(side_effect=[mock_1, mock_2])):
    ...

关键经验

  • 针对任何 async def 的 Mock,必须保证它被调用时能走协程语境。
  • 严格区分 异步的请求方法同步的响应对象httpx.AsyncClient.get 是异步的(需 AsyncMock),但它返回的 Response 对象上的 .json() 是同步的(需 MagicMock 即可)。
Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. yesterday First seen · 49 lines · 44 tokens per session scan A c7d966db4eac

Subscribe to this mod's changes

pytest-asyncio-httpx-mocking is a skill published in the GitHub repository Project-N-E-K-O/N.E.K.O (2,708 stars, last pushed yesterday), licensed Apache-2.0. It adds 44 tokens to every session and 590 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.