Django验证单元测试

编程入门 行业动态 更新时间:2024-10-11 15:13:24
本文介绍了Django验证单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试模拟django.contrib.auth authenticate方法的返回值,该方法在视图的登录方法中调用.

I am trying to mock the return value of the django.contrib.auth authenticate method which is called within the login method of a view.

有view.py代码:

There's the view.py code:

def login(request): if request.method == 'POST': username = get_username(request.POST.get('email')) password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: if not request.POST.get('remember_me', None): request.session.set_expiry(0) auth_login(request, user) return redirect('/') else: return redirect('/') # some error page else: return redirect('/') # error again else: return render(request, 'auth/login.html')

还有test.py代码:

And the test.py code:

from django.contrib import auth ... @patch.object(auth, 'authenticate') def test_login_missing_user(self, mock_auth): request = self.request_factory.post('', data={'email': u'test@abv.bg', 'password': u'PA$$WORD'}) self.assertIsInstance(login(request), HttpResponse) #this test PASSES user = User.objects.create_user('test_user', 'test@testmail', 'test_password') mock_auth.return_value = True login(request) self.assertTrue(mock_auth.called)

最后一个断言失败并出现AssertionError:False不为真

The last assertion fails with AssertionError: False is not true

推荐答案

您正在修补错误的东西:您所做的只是更改测试中而不是视图中authenticate所指的内容.您应该修补your_view.auth.authenticate.

You're patching the wrong thing: all you've done is change what authenticate refers to within your test, not in the view. You should patch your_view.auth.authenticate.

在在何处修补上查看Mock文档.

See the Mock docs on Where to patch.

更多推荐

Django验证单元测试

本文发布于:2023-10-10 21:54:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1479861.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单元测试   Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!