gpt4 book ai didi

函数的 Python unittest.mock.patch 不起作用

转载 作者:行者123 更新时间:2023-11-28 22:33:03 32 4
gpt4 key购买 nike

我正在尝试使用带有 mock.patch 的单元测试来测试我的 python 应用程序,但效果不佳。我的代码:

测试文件.py

from unittest.mock import patch

class TestMaterialsUpdate(TestCase):
def setUp(self):
self.client = Client()

@patch('api.accounts.helpers.get_authenticated_user', return_value={'username': 'username'})
def test_my_castom_method(self):
import api.accounts.helpers as he
print(he.get_authenticated_user) # printed mock here
print(he.get_authenticated_user) # returned {'username': 'username'}

url = reverse('materials_create')
# next call get_authenticated_user will be in post request
self.client.post(url,data=json.dumps({'data': 'data'}), content_type='application/json')

post 请求调用检查“用户身份验证”的装饰器使用 get_authenticated_user 函数。但是在装饰器中我得到的是函数而不是模拟对象。

装饰器.py

def login_required(func):
def wrapper(*args, **kwargs):
print(get_authenticated_user) # printed <function get_authenticated_user at 0x7fec34b62510>
user = get_authenticated_user(request) # return None instead {'username: 'username'}

为什么在 decorators.py 中我得到一个函数而不是模拟对象?Python版本为3.4.0

最佳答案

您似乎在修补错误的位置。在 decorators.py 中,您使用的是全局名称 get_authenticated_user(),但您在 api.accounts.helpers 中修补了一个名称。

您可能导入了 get_authenticated_user :

from api.accounts.helpers import get_authenticated_user

这意味着修补原始位置不会更改装饰器中的引用。

装饰器中修补全局:

@patch('decorators.get_authenticated_user', return_value={'username': 'username'})

另见 Where to patch section mock 文档:

patch() works by (temporarily) changing the object that a name points to with another one. There can be many names pointing to any individual object, so for patching to work you must ensure that you patch the name used by the system under test.

The basic principle is that you patch where an object is looked up, which is not necessarily the same place as where it is defined.

关于函数的 Python unittest.mock.patch 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40329263/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com