プログラムを中心とした個人的なメモ用のブログです。 タイトルは迷走中。
内容の保証はできませんのであしからずご了承ください。

2023/11/13

[Python] pytest で motor のテストを行う

event_note2023/11/13 1:23

MongoDB 用の非同期ライブラリに motor を使用しており、pytest でテストコードを記述する際にモックをどうすればいいか悩みました。

当初は pymongo を使って同期的に使用していたため、MongoDB のモックには mongomock を使用していましたが、motor を使用する場合には mongomock-motor が使うとテストできました。

インストール

pip install mongomock-motor

サンプルコード

上記のページにあるサンプルコードを pytest で実行する例です。

import pytest
from mongomock_motor import AsyncMongoMockClient

@pytest.mark.asyncio
async def test_mock_client():
    collection = AsyncMongoMockClient()['tests']['test-1']

    assert await collection.find({}).to_list(None) == []

    result = await collection.insert_one({'a': 1})
    assert result.inserted_id

    assert len(await collection.find({}).to_list(None)) == 1