Here's what to do if you want to test your own Middleware but rely on another Middleware.
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 when
request.user` is referenced unless it goes through session-related middleware.
--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.
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)
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
__init__
in Python - George Shuklin - Medium
--I referred to the sample injecting a function that does nothing with lambda for __init__
.Recommended Posts