python / intermediate
Snippet
Isolated View Request Testing using Django RequestFactory
RequestFactory creates a direct HttpRequest instance without passing through the URL routing system or middleware chain. This allows targeted, high-speed unit testing of individual view functions with customized request state.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
from django.test import RequestFactory, TestCasefrom django.contrib.auth.models import AnonymousUserfrom myapp.views import dashboard_viewclass ViewIsolationTestCase(TestCase):def setUp(self):self.factory = RequestFactory()def test_dashboard_anonymous_access(self):request = self.factory.get('/dashboard/')request.user = AnonymousUser()response = dashboard_view(request)self.assertEqual(response.status_code, 302)
django
Breakdown
1
self.factory = RequestFactory()
Initializes the RequestFactory helper instance inside test setup.
2
request = self.factory.get('/dashboard/')
Generates a mock GET request object targeted at the specified path.
3
request.user = AnonymousUser()
Attaches a dummy unauthenticated user to simulate request context.
4
response = dashboard_view(request)
Invokes the view directly by passing the engineered request object.