Modify requests in your unit tests (improvement on RequestFactory)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from django.test import Client
from django.core.handlers.wsgi import WSGIRequest
from django.core.handlers.base import BaseHandler

# Adapted from Simon Willison's snippet: http://djangosnippets.org/snippets/963/.
class RequestFactory(Client):
    """
    Class that lets you create mock Request objects for use in testing.
    
    Usage:
    
    rf = RequestFactory()
    get_request = rf.get('/hello/')
    post_request = rf.post('/submit/', {'foo': 'bar'})
    
    This class re-uses the django.test.client.Client interface, docs here:
    http://www.djangoproject.com/documentation/testing/#the-test-client
    
    Once you have a request object you can pass it to any view function, 
    just as if that view had been hooked up using a URLconf.
    
    """
    def request(self, **request):
        """
        Similar to parent class, but returns the request object as soon as it
        has created it.
        """
        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)
        request = WSGIRequest(environ)
        
        handler = BaseHandler()
        handler.load_middleware()
        for middleware_method in handler._request_middleware:
            if middleware_method(request):
                raise Exception("Couldn't create request object - "
                                "request middleware returned a response")
        
        return request

More like this

  1. RequestFactory: Easily create mock request objects, for use in testing by simon 4 years, 9 months ago
  2. Decorator and context manager to override settings by jezdez 2 years ago
  3. Automatic testing of add and changelist admin views by Taifu 1 year, 9 months ago
  4. "Zoom in" on rendered HTML that the test client returns by peterbe 4 years, 1 month ago
  5. Monkey-patch Django's test client to return WSGIRequest objects by robmadole 2 years, 6 months ago

Comments

vaughnkoch (on October 11, 2010):

For an example of how to use this:

http://vaughnkoch.wordpress.com/2010/10/11/unit-testing-complex-views-in-django-with-requestfactory-and-mocker/

#

jsdalton (on December 20, 2010):

Nice work on this, btw.

You should note, btw that Simon's original RequestFactory is now part of the django.test.client module. The Test Client actually implements his RequestFactory now to generate the request object and then executes it against the view.

I'm not sure when it was introduced btw, but I'm running the trunk right now. It looks like there have been some additional enhancements since Simon first posted the snippet.

You might want to refactor this to extend the RequestFactory that's now in Django, since they do not appear to have any middleware handling on it as you have created. You can probably achieve your revision in about 5 lines of code I'd imagine.

Cheers.

#

(Forgotten your password?)