Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using session object in Django unit test

Tags:

django

session

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.

like image 480
Kintarō Avatar asked Feb 05 '13 18:02

Kintarō


2 Answers

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.

like image 130
Duncan Parkes Avatar answered Sep 21 '22 19:09

Duncan Parkes


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

like image 36
Alex Fang Avatar answered Sep 20 '22 19:09

Alex Fang