The test patched the service, and its first run still rewrote real plan data. A helper called an async function inside with patch and awaited it outside; by the time the body ran the patch was gone, with no warning at all.
In September I added unit tests for the plan-item create, update and delete endpoints. On the first run six cases failed, and in the failure output was a line saying the plan had been synced to a path in the real data directory.
In that directory, plan.json had two new test entries, an existing entry had been renamed and then deleted, and plan.md had been overwritten several times. The directory is in .gitignore, so there was no version to roll back to; I restored it by hand, word for word, from content read earlier in the session.
The test had replaced the service with a fake. The helper looked like this:
class _RouteTestCase(unittest.IsolatedAsyncioTestCase):
def _call(self, journal, coro_factory):
with patch("core.services.journal.service.get_journal_service",
return_value=journal):
return coro_factory()
# 用例
resp = await self._call(journal, lambda: add_plan_item(req))It even passes a lambda as a factory, as if the timing of the call had been thought through. But add_plan_item is async def: calling it only produces a coroutine object, and not one line of the body runs. return coro_factory() carries that unstarted coroutine out of the with, the patch is undone at that moment, and only the await outside starts the body. And the endpoint imports the service inside the function:
async def add_plan_item(req):
from core.services.journal.service import get_journal_service
journal = get_journal_service()
...That from ... import looks up the attribute on the module only when the body runs, by which point the patch is gone, so it gets the real get_journal_service.
01Reproduced in a dozen lines
# service.py
def get_service():
return "REAL"
# demo.py
import asyncio
from unittest.mock import patch
async def endpoint():
from service import get_service
return get_service()
def call_sync():
with patch("service.get_service", return_value="FAKE"):
return endpoint()
async def call_async():
with patch("service.get_service", return_value="FAKE"):
return await endpoint()
async def main():
print(await call_sync()) # REAL
print(await call_async()) # FAKE
asyncio.run(main())The two functions differ only in whether return is followed by await. In IsolatedAsyncioTestCase the test methods are async themselves, so a synchronous helper raises no warning, and since the returned coroutine is eventually awaited, “coroutine was never awaited” never shows up either.
The fixed helper:
async def _call(self, journal, coro_factory):
with (
patch("core.services.journal.service.get_journal_service",
return_value=journal),
# 安全网:作用域再写错,也只会让测试失败
patch("core.services.journal.service.JournalService",
side_effect=AssertionError("测试不得构造真实 JournalService")),
):
return await coro_factory()_call becomes async def and awaits inside the with. The second patch makes JournalService raise as soon as anything constructs it, so if the scope is ever wrong again the worst outcome is a failing test.
The cases did go red on the very first run, but the writes had happened before they failed: the tests only asserted what the fake received, and nothing stopped the real service from being constructed. The test support code does have a sandbox that points the data directory at a temp dir; it was deliberately left off by default because some tests rely on real data.