7

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", "user@abc.com")
            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.

Kintarō
  • 2,947
  • 10
  • 48
  • 75
  • Is this your exact code? You have an unclosed dictionary on this line `request = self.factory.post('/core/login', {"username": "ValidUser1", "password": "12345")` - it should be `request = self.factory.post('/core/login', {"username": "ValidUser1", "password": "12345",})` – Dan Hoerst Feb 05 '13 at 18:59
  • Yes it is, I copy my code from the repo. Probably I had a typo when I check in. – Kintarō Feb 05 '13 at 19:10
  • So do you still get the error with the code corrected? – Dan Hoerst Feb 05 '13 at 19:59

2 Answers2

9

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.

Duncan Parkes
  • 1,902
  • 1
  • 15
  • 24
1

Such like this: request.session = {'num_visits': 0}

Alex Fang
  • 79
  • 3