我试图测试我的python应用程序使用unitkit与mock.patch,但它不工作。 我的代码:python unittest.mock.patch函数不起作用
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')
POST请求调用勾选 “用户身份验证” 使用get_authenticated_user
功能的装饰。但在装饰器中,我得到了函数,而不是模拟对象。
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'}
为什么decorators.py
我有一个函数,而不是模拟对象? Python版本是3.4.0
在他们的测试方法中'输入api.accounts.helpers as he'也似乎有点奇怪。当然,这并不是指出正确的修补位置,但是一直以来,它不会引起问题吗? – idjaw
@idjaw:这只是试图验证补丁是否到位的OP。这是修补错误的参考,但是。如果他们尝试过'输入装饰器'和'decorators.get_authenticated_user',他们会发现该引用没有被修补。 –
^^是的。这就是我想说的。谢谢。 – idjaw