Loading django/test/client.py +37 −26 Original line number Diff line number Diff line Loading @@ -5,6 +5,7 @@ try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.conf import settings from django.contrib.auth import authenticate, login from django.core.handlers.base import BaseHandler Loading @@ -22,6 +23,7 @@ from django.utils.itercompat import is_iterable BOUNDARY = 'BoUnDaRyStRiNg' MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY class FakePayload(object): """ A wrapper around StringIO that restricts what can be read since data from Loading @@ -41,6 +43,7 @@ class FakePayload(object): self.__len -= num_bytes return content class ClientHandler(BaseHandler): """ A HTTP Handler that can be used for testing purposes. Loading @@ -61,7 +64,7 @@ class ClientHandler(BaseHandler): request = WSGIRequest(environ) response = self.get_response(request) # Apply response middleware # Apply response middleware. for middleware_method in self._response_middleware: response = middleware_method(request, response) response = self.apply_response_fixes(request, response) Loading @@ -71,14 +74,15 @@ class ClientHandler(BaseHandler): return response def store_rendered_templates(store, signal, sender, template, context): "A utility function for storing templates and contexts that are rendered" """ Stores templates and contexts that are rendered. """ store.setdefault('template',[]).append(template) store.setdefault('context',[]).append(context) def encode_multipart(boundary, data): """ A simple method for encoding multipart POST data from a dictionary of form values. Encodes multipart POST data from a dictionary of form values. The key will be used as the form data name; the value will be transmitted as content. If the value is a file, the contents of the file will be sent Loading @@ -90,7 +94,8 @@ def encode_multipart(boundary, data): if isinstance(value, file): lines.extend([ '--' + boundary, 'Content-Disposition: form-data; name="%s"; filename="%s"' % (to_str(key), to_str(os.path.basename(value.name))), 'Content-Disposition: form-data; name="%s"; filename="%s"' \ % (to_str(key), to_str(os.path.basename(value.name))), 'Content-Type: application/octet-stream', '', value.read() Loading Loading @@ -144,13 +149,14 @@ class Client: def store_exc_info(self, *args, **kwargs): """ Utility method that can be used to store exceptions when they are generated by a view. Stores exceptions when they are generated by a view. """ self.exc_info = sys.exc_info() def _session(self): "Obtain the current session variables" """ Obtains the current session variables. """ if 'django.contrib.sessions' in settings.INSTALLED_APPS: engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) Loading @@ -166,7 +172,6 @@ class Client: Assumes defaults for the query environment, which can be overridden using the arguments to the request. """ environ = { 'HTTP_COOKIE': self.cookies, 'PATH_INFO': '/', Loading @@ -180,13 +185,13 @@ class Client: environ.update(self.defaults) environ.update(request) # Curry a data dictionary into an instance of # the template renderer callback function # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = curry(store_rendered_templates, data) dispatcher.connect(on_template_render, signal=signals.template_rendered) # Capture exceptions created by the handler # Capture exceptions created by the handler. dispatcher.connect(self.store_exc_info, signal=got_request_exception) try: Loading @@ -210,13 +215,13 @@ class Client: self.exc_info = None raise exc_info[1], None, exc_info[2] # Save the client and request that stimulated the response # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response # Add any rendered template detail to the response. # If there was only one template rendered (the most likely case), # flatten the list to a single element # flatten the list to a single element. for detail in ('template', 'context'): if data.get(detail): if len(data[detail]) == 1: Loading @@ -226,14 +231,16 @@ class Client: else: setattr(response, detail, None) # Update persistent cookie data # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response def get(self, path, data={}, **extra): "Request a response from the server using GET." """ Requests a response from the server using GET. """ r = { 'CONTENT_LENGTH': None, 'CONTENT_TYPE': 'text/html; charset=utf-8', Loading @@ -246,8 +253,9 @@ class Client: return self.request(**r) def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra): "Request a response from the server using POST." """ Requests a response from the server using POST. """ if content_type is MULTIPART_CONTENT: post_data = encode_multipart(BOUNDARY, data) else: Loading @@ -265,22 +273,24 @@ class Client: return self.request(**r) def login(self, **credentials): """Set the Client to appear as if it has sucessfully logged into a site. """ Sets the Client to appear as if it has successfully 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: 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 # Create a fake request to store login details. request = HttpRequest() request.session = engine.SessionStore() login(request, user) # Set the cookie to represent the session # Set the cookie to represent the session. self.cookies[settings.SESSION_COOKIE_NAME] = request.session.session_key self.cookies[settings.SESSION_COOKIE_NAME]['max-age'] = None self.cookies[settings.SESSION_COOKIE_NAME]['path'] = '/' Loading @@ -288,7 +298,7 @@ class Client: 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 # Save the session values. request.session.save() return True Loading @@ -296,7 +306,8 @@ class Client: return False def logout(self): """Removes the authenticated user's cookies. """ Removes the authenticated user's cookies. Causes the authenticated user to be logged out. """ Loading Loading
django/test/client.py +37 −26 Original line number Diff line number Diff line Loading @@ -5,6 +5,7 @@ try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from django.conf import settings from django.contrib.auth import authenticate, login from django.core.handlers.base import BaseHandler Loading @@ -22,6 +23,7 @@ from django.utils.itercompat import is_iterable BOUNDARY = 'BoUnDaRyStRiNg' MULTIPART_CONTENT = 'multipart/form-data; boundary=%s' % BOUNDARY class FakePayload(object): """ A wrapper around StringIO that restricts what can be read since data from Loading @@ -41,6 +43,7 @@ class FakePayload(object): self.__len -= num_bytes return content class ClientHandler(BaseHandler): """ A HTTP Handler that can be used for testing purposes. Loading @@ -61,7 +64,7 @@ class ClientHandler(BaseHandler): request = WSGIRequest(environ) response = self.get_response(request) # Apply response middleware # Apply response middleware. for middleware_method in self._response_middleware: response = middleware_method(request, response) response = self.apply_response_fixes(request, response) Loading @@ -71,14 +74,15 @@ class ClientHandler(BaseHandler): return response def store_rendered_templates(store, signal, sender, template, context): "A utility function for storing templates and contexts that are rendered" """ Stores templates and contexts that are rendered. """ store.setdefault('template',[]).append(template) store.setdefault('context',[]).append(context) def encode_multipart(boundary, data): """ A simple method for encoding multipart POST data from a dictionary of form values. Encodes multipart POST data from a dictionary of form values. The key will be used as the form data name; the value will be transmitted as content. If the value is a file, the contents of the file will be sent Loading @@ -90,7 +94,8 @@ def encode_multipart(boundary, data): if isinstance(value, file): lines.extend([ '--' + boundary, 'Content-Disposition: form-data; name="%s"; filename="%s"' % (to_str(key), to_str(os.path.basename(value.name))), 'Content-Disposition: form-data; name="%s"; filename="%s"' \ % (to_str(key), to_str(os.path.basename(value.name))), 'Content-Type: application/octet-stream', '', value.read() Loading Loading @@ -144,13 +149,14 @@ class Client: def store_exc_info(self, *args, **kwargs): """ Utility method that can be used to store exceptions when they are generated by a view. Stores exceptions when they are generated by a view. """ self.exc_info = sys.exc_info() def _session(self): "Obtain the current session variables" """ Obtains the current session variables. """ if 'django.contrib.sessions' in settings.INSTALLED_APPS: engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) Loading @@ -166,7 +172,6 @@ class Client: Assumes defaults for the query environment, which can be overridden using the arguments to the request. """ environ = { 'HTTP_COOKIE': self.cookies, 'PATH_INFO': '/', Loading @@ -180,13 +185,13 @@ class Client: environ.update(self.defaults) environ.update(request) # Curry a data dictionary into an instance of # the template renderer callback function # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = curry(store_rendered_templates, data) dispatcher.connect(on_template_render, signal=signals.template_rendered) # Capture exceptions created by the handler # Capture exceptions created by the handler. dispatcher.connect(self.store_exc_info, signal=got_request_exception) try: Loading @@ -210,13 +215,13 @@ class Client: self.exc_info = None raise exc_info[1], None, exc_info[2] # Save the client and request that stimulated the response # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response # Add any rendered template detail to the response. # If there was only one template rendered (the most likely case), # flatten the list to a single element # flatten the list to a single element. for detail in ('template', 'context'): if data.get(detail): if len(data[detail]) == 1: Loading @@ -226,14 +231,16 @@ class Client: else: setattr(response, detail, None) # Update persistent cookie data # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response def get(self, path, data={}, **extra): "Request a response from the server using GET." """ Requests a response from the server using GET. """ r = { 'CONTENT_LENGTH': None, 'CONTENT_TYPE': 'text/html; charset=utf-8', Loading @@ -246,8 +253,9 @@ class Client: return self.request(**r) def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra): "Request a response from the server using POST." """ Requests a response from the server using POST. """ if content_type is MULTIPART_CONTENT: post_data = encode_multipart(BOUNDARY, data) else: Loading @@ -265,22 +273,24 @@ class Client: return self.request(**r) def login(self, **credentials): """Set the Client to appear as if it has sucessfully logged into a site. """ Sets the Client to appear as if it has successfully 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: 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 # Create a fake request to store login details. request = HttpRequest() request.session = engine.SessionStore() login(request, user) # Set the cookie to represent the session # Set the cookie to represent the session. self.cookies[settings.SESSION_COOKIE_NAME] = request.session.session_key self.cookies[settings.SESSION_COOKIE_NAME]['max-age'] = None self.cookies[settings.SESSION_COOKIE_NAME]['path'] = '/' Loading @@ -288,7 +298,7 @@ class Client: 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 # Save the session values. request.session.save() return True Loading @@ -296,7 +306,8 @@ class Client: return False def logout(self): """Removes the authenticated user's cookies. """ Removes the authenticated user's cookies. Causes the authenticated user to be logged out. """ Loading