本文介绍了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验证单元测试
发布评论