用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/fabioc-aloha/Alex_Skill_Mall --skill python-mock-patching-location命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
Create or improve a Markdown instruction, skill, prompt, or agent from an explicitly selected file or user-identified text. Use when a user asks to optimize an existing brain artifact or create one for consistent future execution.
Clear documentation through visual excellence
Assess active Markdown brain files in a local AI agent project or plugin source without changing it. Use before modifying a brain or reviewing declared instructions, skills, prompts, agents, bundled Markdown resources, and research documentation.
基于 SOC 职业分类
正在显示 SKILL.md
| name | python-mock-patching-location |
| description | Python mock.patch must target the import location, not the definition location |
| lastReviewed | 2026-04-30T00:00:00.000Z |
Category: Testing Time Saved: 30+ minutes debugging "mock not working" Battle-tested: Yes — ChessCoach, multiple Python projects
You're writing a test that needs to mock get_client() from module_a. You patch module_a.get_client. The mock doesn't work — the real function still runs.
Python's import system creates a reference to the function in the importing module. When module_b does from module_a import get_client, it creates module_b.get_client as a separate reference. Patching the original doesn't affect the copy.
Patch where the function is USED, not where it's DEFINED
# module_a.py defines get_client()
# module_b.py imports and calls it
# ❌ WRONG — patches the definition, not the usage
@patch('module_a.get_client')
def test_something(mock_client):
result = module_b.do_work() # Still calls real get_client!
# ✅ CORRECT — patches where it's called
@patch('module_b.get_client')
def test_something(mock_client):
result = module_b.do_work() # Uses mock
| Import Style in Target Module | Patch Target |
|---|---|
from module_a import func | target_module.func |
import module_a then module_a.func() | module_a.func |
from module_a import func as alias | target_module.alias |
MagicMock doesn't support async with by default:
# ❌ FAILS — MagicMock can't handle async context manager
mock_lock = MagicMock()
async with mock_lock: # TypeError
# ✅ WORKS — proper async mock
class MockAsyncLock:
async def __aenter__(self):
return self
async def __aexit__(self, *args):
pass
mock_lock = MockAsyncLock()
Test passes AND you've confirmed the mock was actually called:
@patch('module_b.get_client')
def test_something(mock_client):
mock_client.return_value = fake_response
result = module_b.do_work()
mock_client.assert_called_once() # Verify mock was hit
If assert_called_once() fails with "Expected call not found", you patched the wrong location.
Source: Promoted from AI-Memory global-knowledge.md (2026-04-27)