开发者

django:: invoking middleware in tests

开发者 https://www.devze.com 2023-01-27 07:45 出处:网络
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 t

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开发者_Go百科 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 >


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.


Off the top of my head (I can't test this idea right now, but I'm having the same problem as you have): would it be a solution to inlude a context processor that takes simply returns the request variables inserted by the middleware component?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号