【问题标题】:Writing a contextmanager that patches an object编写一个修补对象的上下文管理器
【发布时间】:2018-01-17 11:04:01
【问题描述】:

在我的 Python 3 测试代码中,我有很多这样的语句:

from unittest.mock import patch

user = User(...)
with patch.object(MyAuthenticationClass, 'authenticate', return_value=(user, 'token'):
    # do something

现在我想写成:

with request_user(user):
    # do something

我将如何编写一个方法 request_user 作为上下文管理器,以便它以这种方式修补身份验证,并在 with 块之后删除修补程序?

【问题讨论】:

    标签: python mocking contextmanager


    【解决方案1】:

    你可以像这样写一个简单的包装器:

    def request_user(user):
        return patch.object(MyAuthenticationClass, 'authenticate', return_value=(user, 'token')
    

    并使用它:

    with request_user(user):
        # ...
    

    【讨论】:

    • 如果不将其注释为@contextmanager,这将不起作用。你得到的错误:AttributeError: __enter__
    • 好,你把装饰器放在上面了吗?
    • 没关系,我在实现中错过了return。成功了,谢谢!
    猜你喜欢
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-22
    • 2021-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多