所以我的具体问题是我正在尝试为这样的事情创建一个单元测试:
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
其中
mongo_models.py
包含:
from beanie import Document
class Record(Document):
id: str
content: str
所以我尝试做这样的事情:
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
但是我在
AttributeError: id
行中遇到了 record = await Record.find_one(Record.id == record_id)
错误。
我认为它给出了一个错误,因为您试图在Record.id定义类之前访问类属性,您可以尝试在检查与预期值是否相等之前检查记录是否存在。
record = await Record.find_one(Record.id == record_id)
附示例:
会报错的代码:
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'
有效的代码
class test():
id = '1'
test: str
print(hasattr(test, 'id')) -> gives True
print(test.id) -> gives '1'
注意:我没有足够的声誉来发表评论,所以回答,如果您不喜欢答案,请不要投反对票