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".
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
?
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With