class Client: """ A class that can act as a client for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. Client objects are stateful - they will retain cookie (and thus session) details for the lifetime of the Client instance. This is not intended as a replacement for Twill/Selenium or the like - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ def __init__(self, **defaults): self.handler = ClientHandler() self.defaults = defaults self.cookies = SimpleCookie() self.exc_info = None def store_exc_info(self, **kwargs): """ Stores exceptions when they are generated by a view. """ self.exc_info = sys.exc_info() def _session(self): """ 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) if cookie: return engine.SessionStore(cookie.value) return {} session = property(_session) def request(self, **request): """ The master request method. Composes the environment dictionary and passes to the handler, returning the result of the handler. Assumes defaults for the query environment, which can be overridden using the arguments to the request. """ environ = { 'HTTP_COOKIE': self.cookies, 'PATH_INFO': '/', 'QUERY_STRING': '', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': '80', 'SERVER_PROTOCOL': 'HTTP/1.1', } environ.update(self.defaults) environ.update(request) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = curry(store_rendered_templates, data) signals.template_rendered.connect(on_template_render) # Capture exceptions created by the handler. got_request_exception.connect(self.store_exc_info) try: response = self.handler(environ) except TemplateDoesNotExist as e: # If the view raises an exception, Django will attempt to show # the 500.html template. If that template is not available, # we should ignore the error in favor of re-raising the # underlying exception that caused the 500 error. Any other # template found to be missing during view error handling # should be reported as-is. if e.args != ('500.html',): raise # Look for a signalled exception, clear the current context # exception data, then re-raise the signalled exception. # Also make sure that the signalled exception is cleared from # the local cache! if self.exc_info: exc_info = self.exc_info self.exc_info = None raise exc_info[1].with_traceback(exc_info[2]) # Save the client and request that stimulated the response. response.client = self response.request = request # 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. for detail in ('template', 'context'): if data.get(detail): if len(data[detail]) == 1: setattr(response, detail, data[detail][0]); else: setattr(response, detail, data[detail]) else: setattr(response, detail, None) # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response def get(self, path, data={}, **extra): """ Requests a response from the server using GET. """ r = { 'CONTENT_LENGTH': None, 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': urllib.parse.unquote(path), 'QUERY_STRING': urlencode(data, doseq=True), 'REQUEST_METHOD': 'GET', } r.update(extra) return self.request(**r) def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra): """ Requests a response from the server using POST. """ if content_type is MULTIPART_CONTENT: post_data = encode_multipart(BOUNDARY, data) else: post_data = data r = { 'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': urllib.parse.unquote(path), 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(post_data), } r.update(extra) return self.request(**r) def login(self, **credentials): """ 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: engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) # Create a fake request to store login details. request = HttpRequest() if self.session: request.session = self.session else: 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, } self.cookies[session_cookie].update(cookie_data) # Save the session values. request.session.save() return True else: return False def logout(self): """ Removes the authenticated user's cookies. Causes the authenticated user to be logged out. """ session = __import__(settings.SESSION_ENGINE, {}, {}, ['']).SessionStore() session.delete(session_key=self.cookies[settings.SESSION_COOKIE_NAME].value) self.cookies = SimpleCookie()
class Client: """ A class that can act as a client for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. Client objects are stateful - they will retain cookie (and thus session) details for the lifetime of the Client instance. This is not intended as a replacement for Twill/Selenium or the like - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ def __init__(self, **defaults): self.handler = ClientHandler() self.defaults = defaults self.cookies = SimpleCookie() self.exc_info = None def store_exc_info(self, *args, **kwargs): """ Utility method that can be used to store exceptions when they are generated by a view. """ self.exc_info = sys.exc_info() def _session(self): "Obtain the current session variables" if 'django.contrib.sessions' in settings.INSTALLED_APPS: cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) if cookie: return SessionWrapper(cookie.value) return {} session = property(_session) def request(self, **request): """ The master request method. Composes the environment dictionary and passes to the handler, returning the result of the handler. Assumes defaults for the query environment, which can be overridden using the arguments to the request. """ environ = { 'HTTP_COOKIE': self.cookies, 'PATH_INFO': '/', 'QUERY_STRING': '', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': None, 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, 'SERVER_PROTOCOL': 'HTTP/1.1', } environ.update(self.defaults) environ.update(request) # 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 dispatcher.connect(self.store_exc_info, signal=got_request_exception) response = self.handler(environ) # 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 for detail in ('template', 'context'): if data.get(detail): if len(data[detail]) == 1: setattr(response, detail, data[detail][0]); else: setattr(response, detail, data[detail]) else: setattr(response, detail, None) # Look for a signalled exception and reraise it if self.exc_info: raise self.exc_info[1], None, self.exc_info[2] # 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." r = { 'CONTENT_LENGTH': None, 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': path, 'QUERY_STRING': urlencode(data), 'REQUEST_METHOD': 'GET', } r.update(extra) return self.request(**r) def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra): "Request a response from the server using POST." if content_type is MULTIPART_CONTENT: post_data = encode_multipart(BOUNDARY, data) else: post_data = data r = { 'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': path, 'REQUEST_METHOD': 'POST', 'wsgi.input': StringIO(post_data), } r.update(extra) return self.request(**r) def login(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 if the Sessions framework is not available. """ user = authenticate(**credentials) if user and 'django.contrib.sessions' in settings.INSTALLED_APPS: obj = Session.objects.get_new_session_object() # Create a fake request to store login details request = HttpRequest() request.session = SessionWrapper(obj.session_key) login(request, user) # Set the cookie to represent the session self.cookies[settings.SESSION_COOKIE_NAME] = obj.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 # Set the session values Session.objects.save(obj.session_key, request.session._session, datetime.datetime.now() + datetime.timedelta(seconds=settings.SESSION_COOKIE_AGE)) return True else: return False
class Client: """ A class that can act as a client for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. Client objects are stateful - they will retain cookie (and thus session) details for the lifetime of the Client instance. This is not intended as a replacement for Twill/Selenium or the like - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ def __init__(self, **defaults): self.handler = ClientHandler() self.defaults = defaults self.cookies = SimpleCookie() self.exc_info = None def store_exc_info(self, *args, **kwargs): """ Stores exceptions when they are generated by a view. """ self.exc_info = sys.exc_info() def _session(self): """ 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) if cookie: return engine.SessionStore(cookie.value) return {} session = property(_session) def request(self, **request): """ The master request method. Composes the environment dictionary and passes to the handler, returning the result of the handler. Assumes defaults for the query environment, which can be overridden using the arguments to the request. """ environ = { 'HTTP_COOKIE': self.cookies, 'PATH_INFO': '/', 'QUERY_STRING': '', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': '', 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, 'SERVER_PROTOCOL': 'HTTP/1.1', } environ.update(self.defaults) environ.update(request) # 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. dispatcher.connect(self.store_exc_info, signal=got_request_exception) try: response = self.handler(environ) except TemplateDoesNotExist as e: # If the view raises an exception, Django will attempt to show # the 500.html template. If that template is not available, # we should ignore the error in favor of re-raising the # underlying exception that caused the 500 error. Any other # template found to be missing during view error handling # should be reported as-is. if e.args != ('500.html',): raise # Look for a signalled exception, clear the current context # exception data, then re-raise the signalled exception. # Also make sure that the signalled exception is cleared from # the local cache! if self.exc_info: exc_info = self.exc_info self.exc_info = None raise exc_info[1].with_traceback(exc_info[2]) # Save the client and request that stimulated the response. response.client = self response.request = request # 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. for detail in ('template', 'context'): if data.get(detail): if len(data[detail]) == 1: setattr(response, detail, data[detail][0]); else: setattr(response, detail, data[detail]) else: setattr(response, detail, None) # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response def get(self, path, data={}, **extra): """ Requests a response from the server using GET. """ r = { 'CONTENT_LENGTH': None, 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': urllib.parse.unquote(path), 'QUERY_STRING': urlencode(data, doseq=True), 'REQUEST_METHOD': 'GET', } r.update(extra) return self.request(**r) def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra): """ Requests a response from the server using POST. """ if content_type is MULTIPART_CONTENT: post_data = encode_multipart(BOUNDARY, data) else: post_data = data r = { 'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': urllib.parse.unquote(path), 'REQUEST_METHOD': 'POST', 'wsgi.input': FakePayload(post_data), } r.update(extra) return self.request(**r) def login(self, **credentials): """ 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: engine = __import__(settings.SESSION_ENGINE, {}, {}, ['']) # Create a fake request to store login details. request = HttpRequest() 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, } self.cookies[session_cookie].update(cookie_data) # Save the session values. request.session.save() return True else: return False def logout(self): """ Removes the authenticated user's cookies. Causes the authenticated user to be logged out. """ session = __import__(settings.SESSION_ENGINE, {}, {}, ['']).SessionStore() session.delete(session_key=self.cookies[settings.SESSION_COOKIE_NAME].value) self.cookies = SimpleCookie()
class Client: """ A class that can act as a client for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. Client objects are stateful - they will retain cookie (and thus session) details for the lifetime of the Client instance. This is not intended as a replacement for Twill/Selenium or the like - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ def __init__(self, **defaults): self.handler = ClientHandler() self.defaults = defaults self.cookies = SimpleCookie() self.session = {} self.exc_info = None def store_exc_info(self, *args, **kwargs): """ Utility method that can be used to store exceptions when they are generated by a view. """ self.exc_info = sys.exc_info() def request(self, **request): """ The master request method. Composes the environment dictionary and passes to the handler, returning the result of the handler. Assumes defaults for the query environment, which can be overridden using the arguments to the request. """ environ = { 'HTTP_COOKIE': self.cookies, 'PATH_INFO': '/', 'QUERY_STRING': '', 'REQUEST_METHOD': 'GET', 'SCRIPT_NAME': None, 'SERVER_NAME': 'testserver', 'SERVER_PORT': 80, 'SERVER_PROTOCOL': 'HTTP/1.1', } environ.update(self.defaults) environ.update(request) # 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 dispatcher.connect(self.store_exc_info, signal=got_request_exception) response = self.handler(environ) # 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 for detail in ('template', 'context'): if data.get(detail): if len(data[detail]) == 1: setattr(response, detail, data[detail][0]); else: setattr(response, detail, data[detail]) else: setattr(response, detail, None) # Look for a signalled exception and reraise it if self.exc_info: raise self.exc_info[1], None, self.exc_info[2] # Update persistent cookie and session data if response.cookies: self.cookies.update(response.cookies) if 'django.contrib.sessions' in settings.INSTALLED_APPS: from django.contrib.sessions.middleware import SessionWrapper cookie = self.cookies.get(settings.SESSION_COOKIE_NAME, None) if cookie: self.session = SessionWrapper(cookie.value) return response def get(self, path, data={}, **extra): "Request a response from the server using GET." r = { 'CONTENT_LENGTH': None, 'CONTENT_TYPE': 'text/html; charset=utf-8', 'PATH_INFO': path, 'QUERY_STRING': urlencode(data), 'REQUEST_METHOD': 'GET', } r.update(extra) return self.request(**r) def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra): "Request a response from the server using POST." if content_type is MULTIPART_CONTENT: post_data = encode_multipart(BOUNDARY, data) else: post_data = data r = { 'CONTENT_LENGTH': len(post_data), 'CONTENT_TYPE': content_type, 'PATH_INFO': path, 'REQUEST_METHOD': 'POST', 'wsgi.input': StringIO(post_data), } r.update(extra) return self.request(**r) def login(self, path, username, password, **extra): """ A specialized sequence of GET and POST to log into a view that is protected by a @login_required access decorator. path should be the URL of the page that is login protected. Returns the response from GETting the requested URL after login is complete. Returns False if login process failed. """ # First, GET the page that is login protected. # This page will redirect to the login page. response = self.get(path) if response.status_code != 302: return False _, _, login_path, _, data, _= urlparse(response['Location']) next = data.split('=')[1] # Second, GET the login page; required to set up cookies response = self.get(login_path, **extra) if response.status_code != 200: return False # Last, POST the login data. form_data = { 'username': username, 'password': password, 'next' : next, } response = self.post(login_path, data=form_data, **extra) # Login page should 302 redirect to the originally requested page if (response.status_code != 302 or urlparse(response['Location'])[2] != path): return False # Since we are logged in, request the actual page again return self.get(path)