So my concrete problem is that I am trying to create a unit test for something like this:
from mongo_models import Record
async def do_something(record_id: str):
record = await Record.find_one(Record.id == record_id)
if record is None:
record = Record(id='randomly_generated_string', content='')
# Other operations with `record` but we can ignore them for this
return record
Where the mongo_models.py
contains:
from beanie import Document
class Record(Document):
id: str
content: str
So I tried doing something like this:
import pytest
from core_code import do_something
@pytest.mark.asyncio
async def test_do_something():
""" Test do_something method."""
# Create a mock for the object that will be returned by find_one
record_mock = AsyncMock(spec=Record)
record_mock.id = "test-id"
record_mock.content = "Test content"
# Test with the find_one method patched
with patch('mongo_models.Record.find_one', return_value=record_mock) as mock_find_one:
result = await do_something(record_id="input_id")
# Assert that find_one was called
mock_find_one.assert_awaited_once()
# Assert the right object is being used
assert result == record_mock
But I am getting an AttributeError: id
error when is executed the instruction:
record = await Record.find_one(Record.id == record_id)
line.
I think it gives an error is because you are trying to access a class attribute before the class is defined at Record.id, you can try to check if record exists before checking for equality with expected value.
record = await Record.find_one(Record.id == record_id)
Attached sample examples:
Code which will give error:
class test():
id: str
test: str
print(hasattr(test, 'id') -> will give False
print(test.id) -> will give AttributeError: type object 'test' has no attribute 'id'
Code which worked
class test():
id = '1'
test: str
print(hasattr(test, 'id')) -> gives True
print(test.id) -> gives '1'
2