Wednesday, March 28, 2012

Re: TestCase Client.login() fails

On 28-03-12 08:05, jondbaker wrote:

> def test_login(self):
> user = User.objects.create_user('test', 'test@test.com', 't3stp@s$')
> response = self.client.login(username=user.username, password=user.password)
> self.assertTrue(response)
>
> After creating the user, I can verify that user.is_active is in fact
> True, but unfortunately response returns False. Both
> 'django.contrib.auth.middleware.AuthenticationMiddleware' and
> 'django.contrib.auth' are declared in settings.py.
>
> Any thoughts?

Yes: You have to call user.save() after creating it. Otherwise the user
object exists, but it isn't saved to the database yet. And
"self.client.login()" queries the database, not user objects local to
the test.


Creating model objects in tests and testing them afterwards is something
that needs a bit of care. I've made several mistakes with them already
:-) Look at [1] for an example error.


Reinout

[1]:
http://reinout.vanrees.org/weblog/2011/11/18/django_unicodedecodeerror.html

--
Reinout van Rees http://reinout.vanrees.org/
reinout@vanrees.org http://www.nelen-schuurmans.nl/
"If you're not sure what to do, make something. -- Paul Graham"

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment