Skip to content

Instantly share code, notes, and snippets.

@pablorecio
Last active March 8, 2023 11:41
Show Gist options
  • Save pablorecio/7022796 to your computer and use it in GitHub Desktop.
Save pablorecio/7022796 to your computer and use it in GitHub Desktop.
Example TestCase for unit test Django middlewares
from django.test import RequestFactory, TestCase
from myapp.middleware import MyMiddleware
class MyMiddlewareTestCase(TestCase):
def setUp(self):
super(MyMiddlewareTestCase, self).setUp()
self.factory = RequestFactory()
self.mm = MyMiddlewareTest()
self.view = lambda x: None
self.request = self.factory.get('/')
def test_stuff_get_access_denied(self):
response = self.mm.process_view(self.request, self.view, [], {})
self.assertEqual(response.status_code, 403)
def test_stuff_with_user(self):
# code for setting up and login a user
response = self.mm.process_view(self.request, self.view, [], {})
self.assertEqual(response.status_code, 200)
@chokosabe
Copy link

You have a typo; self.mm is not set properly. Could argue this is incomplete as well (code for setting up and login a user should be part of the test)....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment