8

I am having problems using the Django test Client() for testing middleware. It seems to emulate the sessions middleware specifically. However, since it is based on the RequestFactory, it does not seem to run any middleware.

Is there any way to get the test Client to apply middleware for both, the request and the response? I understand that there are often other ways of specifically testing middleware. However, in certain cases, I would like to test a request with the full middleware stack. Any way of doing this?

I was thinking of extending the Client and modifying its request() class and running the request through the middleware stack at the beginning of the function, and the response through the middleware stack at the bottom of the function. Do you think such a thing would work? If not, can you point me at some resources which would explain why?

4

1 回答 1

7

您可能需要override_settings.

请参阅https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.override_settings

@override_settings(MIDDLEWARE_CLASSES=(
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
))
class ViewTest(TestCase):

    def setUp(self):
        pass
于 2015-01-02T15:43:14.633 回答