Why django.test.client.Client does not allow me to log in

I use django.test.client.Client to check if any text appears when a user logs in. However, I do not seem to support the client account.

This test passes if it is executed manually using Firefox, but not executed with the Client object.

class Test(TestCase): def test_view(self): user.set_password(password) user.save() client = self.client # I thought a more manual way would work, but no luck # client.post('/login', {'username':user.username, 'password':password}) login_successful = client.login(username=user.username, password=password) # this assert passes self.assertTrue(login_successful) response = client.get("/path", follow=True) #whether follow=True or not doesn't seem to work self.assertContains(response, "needle" ) 

When I print the answer, it returns a login form that is hidden:

 {% if not request.user.is_authenticated %} ... form ... {% endif %} 

This is confirmed when running ipython manage.py shell .

The problem is that the Client object does not support an authentication session.

+4
source share
3 answers

FWIW, Django 1.2 update (I used to run 1.1.1), fixed it. I have no idea what was broken there, given that when I last ran this test suite about 2 weeks ago, it worked great.

0
source

It just happened to me when I repeated testing an application that worked and was forgotten for several months.

Solution (other than upgrading to Django 1.2) fix # 11821 . In short, Python 2.6.5 has some bug fixes in the Cookie module, causing a cache error in the test client.

+1
source

I use RequestContext to include the user in the template context.

 from django.shortcuts import render_to_response from django.contrib.auth.decorators import login_required from django.template import RequestContext @login_required def index(request): return render_to_response('page.html', {}, context_instance=RequestContext(request)) 

and in the template

 {% if user.is_authenticated %} ... {{ user.username }} .. {% endif %} 

This works as expected (I don’t get to this page without logging in, and when I get there, the username is in response.content ) when passing through the test client.

0
source

Source: https://habr.com/ru/post/1310438/


All Articles