简体   繁体   English

功能的Python unittest.mock.patch不起作用

[英]Python unittest.mock.patch for function don't work

I'm trying to test my python application use unittests with mock.patch but it don't work as well. 我正在尝试通过嘲笑我的python应用程序使用unittests,但它不能正常工作。 My code: 我的代码:

test_file.py test_file.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')

The post request call the decorator that check "user auth" use get_authenticated_user function. 发布请求调用装饰器,该装饰器使用get_authenticated_user函数检查“ user auth”。 But in decorator I got function instead mock-object. 但是在装饰器中我得到了函数而不是模拟对象。

decorators.py decorators.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'}

Why in decorators.py I got a function instead the mock-object? 为什么在decorators.py有一个函数而不是模拟对象? Python version is 3.4.0 Python版本是3.4.0

You appear to be patching the wrong location. 您似乎在修补错误的位置。 In decorators.py you are using a global name get_authenticated_user() , but you are patching a name in api.accounts.helpers instead. decorators.py您使用的是全局名称get_authenticated_user() ,但您是在api.accounts.helpers中修补名称。

You probably imported get_authenticated_user with: 您可能使用以下命令导入了get_authenticated_user

from api.accounts.helpers import get_authenticated_user

which means that patching the original location won't change the reference in decorators . 这意味着修补原始位置不会改变decorators的参考

Patch the global in decorators : decorators修补全局decorators

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

Also see the Where to patch section of the mock documentation: 另请参见mock文档的“ 何处修补”部分

patch() works by (temporarily) changing the object that a name points to with another one. patch()通过(临时)将名称指向的对象更改为另一个对象来工作。 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. 基本原理是,您修补在其中查找对象的位置,该对象不一定与定义对象的位置相同。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM