Opened 12 years ago

Last modified 11 years ago

#14350 closed

Please add a login method to the test Client that doesn't depend on passwords — at Version 2

Reported by: James Westby <jw+debian@…> Owned by: nobody
Component: Testing framework Version: 1.2
Severity: Keywords:
Cc: hv@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Ramiro Morales)


Requiring passwords in tests that don't test the login is unnecessary and
binds them too tightly to implementation that they don't care about.

I suggest something like the following:

      def login_user(self, user):
          if not 'django.contrib.sessions' in settings.INSTALLED_APPS:
              raise AssertionError("Unable to login without django.contrib.sessions in INSTALLED_APPS")
          user.backend = "%s.%s" % ("django.contrib.auth.backends",
          engine = import_module(settings.SESSION_ENGINE)

          # Create a fake request to store login details.
          request = HttpRequest()
          if self.session:
              request.session = self.session
              request.session = engine.SessionStore()
          login(request, user)

          # Set the cookie to represent the session.
          session_cookie = settings.SESSION_COOKIE_NAME
          self.cookies[session_cookie] = request.session.session_key
          cookie_data = {
              'max-age': None,
              'path': '/',
              'domain': settings.SESSION_COOKIE_DOMAIN,
              'secure': settings.SESSION_COOKIE_SECURE or None,
              'expires': None,

          # Save the session values.

refactoring with the common code in other methods.

That would allow you to just login with a User object.



Change History (3)

Changed 12 years ago by James Westby <jw+debian@…>

Attachment: login_user.txt added

Suggested approach

comment:1 Changed 12 years ago by James Westby <jw+debian@…>

Attached the code as I messed up the formatting.



comment:2 Changed 12 years ago by Ramiro Morales

Description: modified (diff)

Re-formatted description.

Note: See TracTickets for help on using tickets.
Back to Top