testing Client support for middleware
|Reported by:||Henrik Vendelbo||Owned by:||nobody|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I propose the following improvement:
The testing client is great for testing the whole request chain.
If you want to test the middleware part of the request, you need
1) Doing a regular request with an added middleware instance for
testing the request object.
2) Directly call one or more middleware instances passing a request
If your middleware sets a host_name attribute on the request object you can test it this way:
from django.test import Client,LastRequestMiddleware ... def test_host_name(self): lrm = LastRequestMiddleware() c = Client(middleware_instances = [lrm]) response = c.get('/') assert haskey(lrm.request,"host_name"), "The host name was not set"
Using this approach you can add any custom middleware to the chain.
If you want to test your middleware without relying on the url resolution and views
working, you can invoke a simplified handler that returns a blank response in place
of calling the view.
c = Client() mym = MyMiddleware() response = c.get('/',only_middleware=[mym]) assert 'RESULT' in response, "RESULT header not added to response"
Calling the client this was means that the middleware classes from settings are not called,
but only the ones you specify by passing the list of instances.