Ticket #9159: django.test.patch

File django.test.patch, 7.8 KB (added by Henrik Vendelbo, 16 years ago)

Patch without docs

  • django/test/__init__.py

    diff --git a/django/test/__init__.py b/django/test/__init__.py
    index 554e72b..1fced4f 100644
    a b Django Unit Test and Doctest framework.  
    44
    55from django.test.client import Client
    66from django.test.testcases import TestCase
     7from django.test.middleware import LastRequestMiddleware
  • django/test/client.py

    diff --git a/django/test/client.py b/django/test/client.py
    index ea2fd32..264726f 100644
    a b from django.contrib.auth import authenticate, login  
    1111from django.core.handlers.base import BaseHandler
    1212from django.core.handlers.wsgi import WSGIRequest
    1313from django.core.signals import got_request_exception
    14 from django.http import SimpleCookie, HttpRequest
     14from django.http import SimpleCookie, HttpRequest, HttpResponse
    1515from django.template import TemplateDoesNotExist
    1616from django.test import signals
    1717from django.utils.functional import curry
    class ClientHandler(BaseHandler):  
    4848    A HTTP Handler that can be used for testing purposes.
    4949    Uses the WSGI interface to compose requests, but returns
    5050    the raw HttpResponse object
     51   
     52    middleware_instances Allows plugging in middleware instances in the chain
    5153    """
     54    def __init__(self,use_middleware_classes = True,use_blank_view=False,middleware_instances = []):
     55        super(ClientHandler,self).__init__()
     56        self.use_middleware_classes = use_middleware_classes
     57        self.use_blank_view = use_blank_view
     58        self.middleware_instances = middleware_instances
     59       
    5260    def __call__(self, environ):
    5361        from django.conf import settings
    5462        from django.core import signals
    class ClientHandler(BaseHandler):  
    6169        signals.request_started.send(sender=self.__class__)
    6270        try:
    6371            request = WSGIRequest(environ)
    64             response = self.get_response(request)
     72            if self.use_blank_view:
     73                response = self.get_blank_response(request)
     74            else:
     75                response = self.get_response(request)
    6576
    6677            # Apply response middleware.
    6778            for middleware_method in self._response_middleware:
    class ClientHandler(BaseHandler):  
    7182            signals.request_finished.send(sender=self.__class__)
    7283
    7384        return response
     85       
     86    def load_middleware(self):
     87        if self.use_middleware_classes:
     88            super(ClientHandler,self).load_middleware()
     89        else:
     90            self._request_middleware = []
     91            self._view_middleware = []
     92            self._response_middleware = []
     93            self._exception_middleware = []
     94           
     95        for mw_instance in self.middleware_instances:
     96            if hasattr(mw_instance, 'process_request'):
     97                self._request_middleware.append(mw_instance.process_request)
     98            if hasattr(mw_instance, 'process_view'):
     99                self._view_middleware.append(mw_instance.process_view)
     100            if hasattr(mw_instance, 'process_response'):
     101                self._response_middleware.insert(0, mw_instance.process_response)
     102            if hasattr(mw_instance, 'process_exception'):
     103                self._exception_middleware.insert(0, mw_instance.process_exception)
     104       
     105    def get_blank_response(self, request):
     106        """Returns an HttpResponse object with blank contents for the given HttpRequest.
     107        Exceptions raised by the middleware will not be handled.
     108        """
     109        from django.core import urlresolvers
     110        from django.conf import settings
     111
     112        # Apply request middleware
     113        for middleware_method in self._request_middleware:
     114            response = middleware_method(request)
     115            if response:
     116                return response
     117
     118        # Get urlconf from request object, if available.  Otherwise use default.
     119        urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
     120
     121        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
     122        callback, callback_args, callback_kwargs = resolver.resolve(
     123                request.path_info)
     124
     125        # Apply view middleware
     126        for middleware_method in self._view_middleware:
     127            response = middleware_method(request, callback, callback_args, callback_kwargs)
     128            if response:
     129                return response
     130
     131        return HTTPResponse('')
    74132
    75133def store_rendered_templates(store, signal, sender, template, context, **kwargs):
    76134    """
    class Client:  
    153211    contexts and templates produced by a view, rather than the
    154212    HTML rendered to the end-user.
    155213    """
    156     def __init__(self, **defaults):
    157         self.handler = ClientHandler()
     214    def __init__(self, middleware_instances=[], **defaults):
     215        self.middleware_instances = middleware_instances
     216        self.handler = ClientHandler(middleware_instances = middleware_instances)
    158217        self.defaults = defaults
    159218        self.cookies = SimpleCookie()
    160219        self.exc_info = None
    class Client:  
    176235                return engine.SessionStore(cookie.value)
    177236        return {}
    178237    session = property(_session)
    179 
     238   
    180239    def request(self, **request):
    181240        """
    182241        The master request method. Composes the environment dictionary
    class Client:  
    249308
    250309        return response
    251310
    252     def get(self, path, data={}, **extra):
     311    def middleware_only_request(self, middleware_instances, **request):
     312        """
     313        Middleware testing. Composes the environment dictionary
     314        and passes to a slimmed down handler. The handler only calls the specified
     315        middleware and calls a view that returns a blank page.
     316        This is intended for direct unit testing of middleware instances"""
     317        environ = {
     318            'HTTP_COOKIE':      self.cookies,
     319            'PATH_INFO':         '/',
     320            'QUERY_STRING':      '',
     321            'REQUEST_METHOD':    'GET',
     322            'SCRIPT_NAME':       '',
     323            'SERVER_NAME':       'testserver',
     324            'SERVER_PORT':       '80',
     325            'SERVER_PROTOCOL':   'HTTP/1.1',
     326        }
     327        environ.update(self.defaults)
     328        environ.update(request)
     329
     330        handler = ClientHandler(use_middleware_classes = False,middleware_instances = middleware_instances)
     331        response = handler(environ)
     332
     333        # Save the client and request that stimulated the response.
     334        response.client = self
     335        response.request = request
     336
     337        # Update persistent cookie data.
     338        if response.cookies:
     339            self.cookies.update(response.cookies)
     340
     341        return response
     342       
     343    def get(self, path, data={}, only_middleware=None, **extra):
    253344        """
    254345        Requests a response from the server using GET.
     346       
     347        If only_middleware is specified the specified middleware is
     348        run around a view that returns a blank page.
    255349        """
    256350        r = {
    257351            'CONTENT_LENGTH':  None,
    class Client:  
    262356        }
    263357        r.update(extra)
    264358
     359        if only_middleware:
     360            return self.middleware_only_request(only_middleware,**r)
    265361        return self.request(**r)
    266362
    267     def post(self, path, data={}, content_type=MULTIPART_CONTENT, **extra):
     363    def post(self, path, data={}, content_type=MULTIPART_CONTENT, only_middleware=None, **extra):
    268364        """
    269365        Requests a response from the server using POST.
     366
     367        If only_middleware is specified the specified middleware is
     368        run around a view that returns a blank page.
    270369        """
    271370        if content_type is MULTIPART_CONTENT:
    272371            post_data = encode_multipart(BOUNDARY, data)
    class Client:  
    282381        }
    283382        r.update(extra)
    284383
     384        if only_middleware:
     385            return self.middleware_only_request(only_middleware,**r)
    285386        return self.request(**r)
    286387
    287388    def login(self, **credentials):
Back to Top