Created
March 8, 2025 17:13
-
-
Save trfiladelfo/9184d3ebbd0ab3234b61d566227a6366 to your computer and use it in GitHub Desktop.
Exemplo de teste unitário para client do MongoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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