[PYTHON] Django: Test Middleware that depends on another Middleware

Overview

Here's what to do if you want to test your own Middleware but rely on another Middleware.

What kind of case?

Generally, when testing Middleware, it seems that it is major to create an instance of Middleware and call the process_request method. See also: Unit Testing Django Middleware --Adam Donaghy --Medium

However, the above method cannot be used for Middleware that assumes that something is being done in another Middleware. For example, in the case of Middleware that processes authentication information, it is possible that the ʻuserattribute does not exist and an exception occurs whenrequest.user` is referenced unless it goes through session-related middleware.

Coping

--Run with self.client.get () (similar to testing View) --Replace get_response () where Middleware calls the lower layer with the appropriate Mock -* Since get_response () of the class instance is injected with __init__, it is necessary to replace __init__ with an appropriate method.

sample

Middleware

class SampleMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        #Do various things

        return self.get_response(request)

test

def fake_init(self, _):
    def get_response(request):
        return HttpResponse()

    self.get_response = get_response


class SampleMiddlewareTest(TestCase):
    def setUp(self):
        self.mock_init = mock.patch.object(
            AuthMiddleware, "__init__", fake_init
        ).start()

        self.addCleanup(mock.patch.stopall)

    def test_Various tests(self):
        #Request
        self.client.get("/")

        #assert

reference

Recommended Posts

Django: Test Middleware that depends on another Middleware
Django test
[Django] About users that can be used on template
Statistical test level 2 that passes almost only on Youtube
Django Middleware Execution Order
Celery notes on Django
Run Django on PythonAnywhere
Hello World on Django