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.
From the documentation for the RequestFactory
object:
It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.
You could try manually setting request.session
to be a dictionary with appropriate stuff in it, as you say. It might turn out to be easier to use the old-fashioned Django test client though.
Such like this: request.session = {'num_visits': 0}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With