Writing a contextmanager that patches an object

。_饼干妹妹 提交于 2021-02-10 17:47:58

问题


In my Python 3 test code, I have a lot of these statements:

from unittest.mock import patch

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

Now I want to write this as:

with request_user(user):
    # do something

How would I write a method request_user as context manager such that it patches the authentication in this way, and removes the patch after the with block?


回答1:


You can write a simple wrapper like this:

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

And use it:

with request_user(user):
    # ...


来源:https://stackoverflow.com/questions/48299554/writing-a-contextmanager-that-patches-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!