Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django:: invoking middleware in tests

I have a middleware function which defines request.foo. A function I want to test depends on foo being defined from the middleware. How do I test said function since the middleware isn't run during tests?

There really should be a function which takes in a request, runs the request through all the middleware in order, then spits out the final request (just as it would be when passed to a view). Does such a function exist?

I could manually call the middleware function, but that seems like a hack. What if the middleware under test depends on another middleware? I would run into "middleware hell".

< example >

middleware function:

class FooMiddleware():
    def process_request(self, request):
        req.foo = True if req.session.get('foo') in [1,2,3,4,5,6,7,8,9,10] else False

Here's the function I want to test:

def getBaz(request):
    if request.foo == True:
        return something()
    else:
        return somethingElse()

How do I test getBaz?

< /example >

< Possibility >

I could manually run the middleware:

def test_getBaz(self):
    request = HttpRequest('/blarg')
    request.session['foo'] = 2

    middleware = FooMiddleware()
    request = middleware.process_request(request)

    value = getBaz(request)
    assertEqual( value, expected )

but that seems like a hack. What if the middleware under test depends on another middleware?

< /Possibility >

like image 840
Alexander Bird Avatar asked Nov 30 '10 05:11

Alexander Bird


1 Answers

I've seen your "manual" solution, but I suggest you consider using the test client described here:

http://docs.djangoproject.com/en/1.2/topics/testing/#testing-tools

As to the middleware dependency, you might consider mocking that middleware.

like image 57
tobych Avatar answered Oct 08 '22 18:10

tobych