Reputation: 265
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.
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')
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'[email protected]', 'password': u'PA$$WORD'})
self.assertIsInstance(login(request), HttpResponse) #this test PASSES
user = User.objects.create_user('test_user', '[email protected]', 'test_password')
mock_auth.return_value = True
login(request)
self.assertTrue(mock_auth.called)
The last assertion fails with AssertionError: False is not true
Upvotes: 0
Views: 3115
Reputation: 599450
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
.
See the Mock docs on Where to patch.
Upvotes: 1