One minute
[Python] async 程式的單元測試:IsolatedAsyncioTestCase、AsyncMock 與 mongomock-motor
框架改成 async 之後,舊的單元測試幾乎全壞了。MagicMock 回傳的不是 coroutine,setUp 裡不能 await,資料庫的 mock 也是同步的。下面是我搬測試時的做法。
改用 IsolatedAsyncioTestCase
標準庫就有,不用另外裝:
import unittest
class TestFlow(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.db = await make_test_db()
async def test_reply(self):
result = await handle_message("hi")
self.assertEqual(result.text, "Hello!")
async def asyncTearDown(self):
await self.db.drop()
每個測試有自己的 event loop,互不干擾。
MagicMock 換成 AsyncMock
會被 await 的東西用 AsyncMock:
from unittest.mock import AsyncMock, patch
@patch("app.flow.send_whatsapp", new_callable=AsyncMock)
async def test_send(self, mock_send):
await run_flow()
mock_send.assert_awaited_once() # 注意是 assert_awaited,不是 assert_called
AsyncMock 上用 assert_called_once() 也會過,但它只檢查有沒有被呼叫,沒檢查有沒有被 await,忘記 await 的 bug 就這樣溜過去。所以要用 assert_awaited_*。
測試數量多,我寫了一個小腳本,自動找出 patch 目標其實是 async 函式的地方,把 MagicMock 換成 AsyncMock。
資料庫改用 mongomock-motor
以前用 mongomock,換成 Motor(async 的 MongoDB driver)之後改用 mongomock-motor:
from mongomock_motor import AsyncMongoMockClient
client = AsyncMongoMockClient()
db = client["test"]
await db.users.insert_one({"name": "ivan"})
循環 import 和模組層級的初始化
很多舊程式在 import 的時候就讀設定、建連線。改成 async 後初始化變成 coroutine,import 時就跑不了。
我在 conftest.py 先 import 會造成循環依賴的模組,再在測試開始前跑一次 async 的 bootstrap:
# conftest.py
import app.features # 先載入,打破循環 import
asyncio.run(bootstrap_for_tests())
pytest 和 python -m unittest 都要能跑
本機大家用 pytest,CI 用 unittest 一個檔案一個檔案跑。兩邊行為不一樣,例如 pytest 會載入 conftest.py,unittest 不會。
我的處理方式是測試一律寫成 unittest.TestCase 的風格,bootstrap 放在一個兩邊都會呼叫到的 helper,CI 上兩種 runner 都跑一次。
搬完之後抓到的 bug
測試搬完跑起來,抓到好幾個正式環境的 bug,都是遷移時漏掉的 await 或同步 cursor。測試遷移沒辦法省略,有些問題只有在這一步才會被發現。
對照表
| 同步 | async |
|---|---|
TestCase |
IsolatedAsyncioTestCase |
setUp |
asyncSetUp |
MagicMock |
AsyncMock |
assert_called_once |
assert_awaited_once |
mongomock |
mongomock-motor |