Django验证单元测试

时间:2015-07-13 07:02:32

标签: django unit-testing authentication mocking

我正在尝试模拟在视图的登录方法中调用的django.contrib.auth身份验证方法的返回值。

有view.py代码:

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代码:

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.com', 'test_password')

    mock_auth.return_value = True
    login(request)
    self.assertTrue(mock_auth.called)

最后一个断言因AssertionError而失败:False不正确

1 个答案:

答案 0 :(得分:1)

你正在修补错误的事情:你所做的只是更改authenticate在测试中所指的内容,而不是在视图中。你应该修补your_view.auth.authenticate

请参阅Where to patch上的模拟文档。