简体   繁体   English

如何向 AsyncMock 添加属性?

[英]How do I add an attribute to AsyncMock?

Code:代码:

class SomeClass(BaseClass):
    async def async_method(arg1, arg2, **kwargs):
        await self.foo.bar(arg1=arg1, arg2=arg2).baz(**kwargs)

One of the tests used:使用的测试之一:

@pytest.fixture
def same_class():
    return SameClass()


async def test_async_method(some_class: SomeClass):
    arg1_mock = 1
    arg2_mock = 2
    some_class.foo.bar = AsyncMock()
    some_class.foo.bar.baz = AsyncMock()
    
    await some_class.async_method(arg1=arg1_mock, arg2=arg2_moc)
    
    some_class.foo.bar.assert_called_once()

I get an error:我收到一个错误:

AttributeError: 'coroutine' object has no attribute 'baz'

How to add an asynchronous attribute method to AsyncMock?如何向 AsyncMock 添加异步属性方法? Any help任何帮助

From the AsyncMock documentation来自AsyncMock文档

The AsyncMock object will behave so the object is recognized as an async function, and the result of a call is an awaitable. AsyncMock object 将运行,因此 object 被识别为异步 function,并且调用的结果是可等待的。

In your code, bar is the async function that returns an awaitable.在您的代码中, bar是异步 function ,它返回一个等待。 To make the awaitable return something with a baz attribute, set it on the return value instead.要使可等待返回具有baz属性的内容,请将其设置为返回值。

some_class.foo.bar = AsyncMock()
some_class.foo.bar.return_value.baz = AsyncMock()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 AsyncMock 调用(未等待)时返回的属性是什么? - What is the attribute returned when AsyncMock called (not awaited)? 如何将属性名称添加到数组? - How do I add an attribute name to an array? 如何从该模块中动态向模块添加属性? - How do I dynamically add an attribute to a module from within that module? 如何为 Python 中的类添加额外的属性? - How do I add an extra attribute for classes in Python? 如何在 Django 表单的输入中添加额外的属性? - How do I add an extra attribute in my input for Django forms? 如何在networkx中向边添加新属性? - How do I add a new attribute to an edge in networkx? 如何使用 python 基于另一个元素属性在 xml 中添加元素? - How do I add elements in xml based on another element attribute using python? 如何检查json列表中是否有属性? 如果没有,我如何仅在缺少的地方添加它? - How can I check if there is a attribute in a json list? And if there is not how do I add it only where is lacking? 如何向文本框添加项目符号? (我试过了,它说形状必须是段落属性? - How do I add a bullet to a textbox? (I tried and it says shapes have to paragraph attribute? 如何改变/修改实例属性? - How do I mutate/modify an instance attribute?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM