I am writing a login view and would like to add a unit test for the view. My view looks like this:
def login(request):
if request.POST:
usrname = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=usrname, password=password)
if user is not None:
auth_login(request, user)
return redirect('/core/home/')
else:
context = {'error_message': "Invalid username or password"}
return render(request, 'core/login.html', context)
else:
c = {}
c.update(csrf(request))
return render_to_response('core/login.html',c)
def home(request):
if request.user.is_authenticated():
context = {'user' : request.user}
return render(request, 'core/home.html', context)
else:
return render(request, 'core/login.html')
And my unit test looks like this:
class CoreViewTests(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_login_view_with_valid_user(self):
uf = UserFactory()
user = uf.make_user("ValidUser1", "12345", "[email protected]")
self.assertEqual(user.username, "ValidUser1")
request = self.factory.post('/core/login', {"username": "ValidUser1", "password": "12345"})
response = login(request)
self.assertEqual(response.status_code, 200)
The unit test crash because they cannot find the session object. I follow couple tutorial on the websites by defining a dummy session dictionary but it doesn't help.
Can anyone shed some light for me how to write a unit test for a view that need to deal with session object?
Thanks.
request = self.factory.post('/core/login', {"username": "ValidUser1", "password": "12345")
- it should berequest = self.factory.post('/core/login', {"username": "ValidUser1", "password": "12345",})
– Baroscope