Pytest asyncio httpx mocking

From Project-N-E-K-O/N.E.K.O · View interactive version

Pytest asyncio httpx mocking is an AI agent skill from the GitHub repository Project-N-E-K-O/N.E.K.O. When masking httpx.AsyncClient with unittest.mock in Pytest, AsyncMock must be used instead of MagicMock for async methods like post/get to prevent TypeError when awaited.

How to use this skill

Skill file

httpx.AsyncClient Mocking with AsyncMock

症状

根本原因

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

代码解决方案

❌ 错误写法:

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])):
    ...

关键经验

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.