基于django0.96的自动测试功能的Login增强

0.96不支持client对象,先Login再提交数据。因此,参照trunk,改写了Client
    def login_new(self, **credentials):
        """Set the Client to appear as if it has sucessfully logged into a site.

        Returns True if login is possible; False if the provided credentials
        are incorrect, or the user is inactive, or if the sessions framework is
        not available.
        """
        user = authenticate(**credentials)
        if user and user.is_active and 'django.contrib.sessions' in settings.INSTALLED_APPS:
            #engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])

            # Create a fake request to store login details
            request = HttpRequest()
            #request.session = engine.SessionStore()
            from django.contrib.sessions.middleware import SessionMiddleware
            SessionMiddleware().process_request( request )
            login(request, user)

            obj = Session.objects.get_new_session_object()
            session_key = obj.session_key
            
            # Set the cookie to represent the session
            self.cookies[settings.SESSION_COOKIE_NAME] = session_key
            self.cookies[settings.SESSION_COOKIE_NAME]['max-age'] = None
            self.cookies[settings.SESSION_COOKIE_NAME]['path'] = '/'
            self.cookies[settings.SESSION_COOKIE_NAME]['domain'] = settings.SESSION_COOKIE_DOMAIN
            self.cookies[settings.SESSION_COOKIE_NAME]['secure'] = settings.SESSION_COOKIE_SECURE or None
            self.cookies[settings.SESSION_COOKIE_NAME]['expires'] = None

            # Save the session values
            #request.session.save()
            new_session = Session.objects.save(session_key, request.session._session,
                    datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE))

            return True
        else:
            return False

你可能感兴趣的:(django)