Skip to content

Instantly share code, notes, and snippets.

@trfiladelfo
Created March 8, 2025 17:13
Show Gist options
  • Save trfiladelfo/9184d3ebbd0ab3234b61d566227a6366 to your computer and use it in GitHub Desktop.
Save trfiladelfo/9184d3ebbd0ab3234b61d566227a6366 to your computer and use it in GitHub Desktop.
Exemplo de teste unitário para client do MongoDB
import pytest
from unittest.mock import AsyncMock, MagicMock
from motor.motor_asyncio import AsyncIOMotorClient
# Example function to test
async def get_data_from_collection(db_client, collection_name, query):
collection = db_client["test_database"][collection_name]
result = await collection.find_one(query)
return result
@pytest.mark.asyncio
async def test_get_data_from_collection(mocker):
# Mock the AsyncIOMotorClient
mock_client = MagicMock(AsyncIOMotorClient)
# Mock the database and collection
mock_db = MagicMock()
mock_collection = AsyncMock()
mock_db.__getitem__.return_value = mock_collection
mock_client.__getitem__.return_value = mock_db
# Mock the find_one method
mock_collection.find_one.return_value = {"key": "value"}
# Inject the mock client into the function
result = await get_data_from_collection(mock_client, "test_collection", {"key": "value"})
# Assertions
mock_collection.find_one.assert_awaited_once_with({"key": "value"})
assert result == {"key": "value"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment