编写一个修补对象的上下文管理器

Writing a contextmanager that patches an object

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

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 块之后删除补丁?

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

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

并使用它:

with request_user(user):
    # ...