views:

85

answers:

2

Hi all,

I'm trying to build a test for a view that's decorated with @login_required, since I failed to make it work, I did a simple test and still can't make it pass.

Here is the code for the simple test and the view:

def test_login(self):
    user = self._create_new_user()
    self.assertTrue(user.is_active)
    login = self.client.login(username=user.username,
password=self.data['password1'])
    self.failUnless(login, 'Could not log in')
    response = self.client.get('/accounts/testlogin/')
    self.assertEqual(response.status_code, 200)

@login_required
def testlogin(request):
    print 'testlogin !! '
    return HttpResponse('OK')

_create_new_user() is saving the user and there is a test inside that method to see that is working.

The test fails in the response.status_code, returning 302 and the response instance is of a HttpResponseRedirect, is redirecting it as if not logged in.

Any clue? I'm missing something?

Regards Esteban

A: 

This testcase works for me:

from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test.client import Client
import unittest

class LoginTestCase(unittest.TestCase):
    def setUp(self):
        self.client = Client()
        self.user = User.objects.create_user('john', '[email protected]', 'johnpassword')

    def testLogin(self):
        self.client.login(username='john', password='johnpassword')
        response = self.client.get(reverse('testlogin-view'))
        self.assertEqual(response.status_code, 200)

I suggest you (if you don't use them already) to use the reverse() function and name your URLs. This way you are sure that you get always the right URL.

aeby
@aeby: I copied and pasted your code and still get a 302, are you using @login_required in your view?
Esteban Feldman
Django version 1.1.1 - Double checked that the testlogin view is working from the browser and that is available only by logged in user
Esteban Feldman
Yes I do: from django.contrib.auth.decorators import login_required@login_requireddef testlogin(request): return HttpResponse("Test")
aeby
A: 

Here is the answer:

Python 2.6.5 made a change to the way cookies are stored which is subtly incompatible with the test client. This problem has been fixed in the 1.1.X and trunk branches, but the fix hasn't yet made it into a formal release.

If you are using 1.1.X and Python 2.6.5, you're going to have problems with any test activity involving cookies. You either need to downgrade Python, or use the 1.1.X branch rather than the 1.1.1 release.

A 1.1.2 release (that will include the fix for the problem you describe) will be made at the same time that we release 1.2 - hopefully, very very soon.

Yours, Russ Magee %-)

http://groups.google.com/group/django-users/browse_frm/thread/617457f5d62366ae/05f0c01fff0b9e6d?hl=en&lnk=gst&q=2.6.5#05f0c01fff0b9e6d

Esteban Feldman