views:

43

answers:

2

I have this test case

def setUp(self):
    self.user = User.objects.create(username="tauri", password='gaul')

def test_loginin_student_control_panel(self):
   c = Client()
   c.login(username="tauri", password="gaul")
   response = c.get('/student/')
   self.assertEqual(response.status_code, 200)

the view associated with the test case is this

@login_required
def student(request):
    return render_to_response('student/controlpanel.html')

so my question is why the above test case redirects user to login page? should not c.login suppose to take care authenticating user?

A: 

Did you make sure to create the user entry in your setUp function?

User.objects.create_user(username="tauri", password="gual")

mountainswhim
yes, let me add that snippet too.
Mohamed
+2  A: 

The problem is the way you create your User object.

Django does not store your password in plain text in the database, it stores its hash value. But in your code password is set in plain text.

So when you use c.login(...) internally Django will make a call to check_password method which will generate a hash value from the password you passed and will compare it to the password stored in the database and as a result will return False because 'gaul' from DB is not equal to get_hexdigest('gaul')

There are two options:

1) Use a User.objects.create_user method that will take care of password hashing:

def setUp(self):
    self.user = User.objects.create_user(username='tauri', 
                                         password='gaul', 
                                         email='')

2) Or set a password with a set_password method:

def setUp(self):
    self.user = user = User.objects.create(username='tauri')
    user.set_password('gaul')
    user.save()
Ruslan Spivak
uh! I thought that I was using create_user, thanks Ruslan.
Mohamed