diff --git a/tests/admin_changelist/tests.py b/tests/admin_changelist/tests.py index d0468e725b..df2c1b09f7 100644 --- a/tests/admin_changelist/tests.py +++ b/tests/admin_changelist/tests.py @@ -49,14 +49,12 @@ def build_tbody_html(pk, href, extra_fields): @override_settings(ROOT_URLCONF="admin_changelist.urls") class ChangeListTests(TestCase): + factory = RequestFactory() @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser(username='super', email='a@b.com', password='xxx') - def setUp(self): - self.factory = RequestFactory() - def _create_superuser(self, username): return User.objects.create_superuser(username=username, email='a@b.com', password='xxx') diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py index 57a4d1acda..01e1076141 100644 --- a/tests/admin_filters/tests.py +++ b/tests/admin_filters/tests.py @@ -249,6 +249,7 @@ class BookmarkAdminGenericRelation(ModelAdmin): class ListFiltersTests(TestCase): + request_factory = RequestFactory() @classmethod def setUpTestData(cls): @@ -297,9 +298,6 @@ class ListFiltersTests(TestCase): cls.john = Employee.objects.create(name='John Blue', department=cls.dev) cls.jack = Employee.objects.create(name='Jack Red', department=cls.design) - def setUp(self): - self.request_factory = RequestFactory() - def test_choicesfieldlistfilter_has_none_choice(self): """ The last choice is for the None value. diff --git a/tests/admin_inlines/tests.py b/tests/admin_inlines/tests.py index bad1986fd0..0a1ab5acbb 100644 --- a/tests/admin_inlines/tests.py +++ b/tests/admin_inlines/tests.py @@ -27,6 +27,8 @@ class TestDataMixin: @override_settings(ROOT_URLCONF='admin_inlines.urls') class TestInline(TestDataMixin, TestCase): + factory = RequestFactory() + @classmethod def setUpTestData(cls): super().setUpTestData() @@ -35,7 +37,6 @@ class TestInline(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) - self.factory = RequestFactory() def test_can_delete(self): """ diff --git a/tests/admin_ordering/tests.py b/tests/admin_ordering/tests.py index 026c76fe23..f68b64ae70 100644 --- a/tests/admin_ordering/tests.py +++ b/tests/admin_ordering/tests.py @@ -34,6 +34,7 @@ class TestAdminOrdering(TestCase): in ModelAdmin rather that ordering defined in the model's inner Meta class. """ + request_factory = RequestFactory() @classmethod def setUpTestData(cls): @@ -43,9 +44,6 @@ class TestAdminOrdering(TestCase): Band(name='Van Halen', bio='', rank=2), ]) - def setUp(self): - self.request_factory = RequestFactory() - def test_default_ordering(self): """ The default ordering should be by name, as specified in the inner Meta diff --git a/tests/admin_views/test_adminsite.py b/tests/admin_views/test_adminsite.py index 5359a95dce..86e0a357db 100644 --- a/tests/admin_views/test_adminsite.py +++ b/tests/admin_views/test_adminsite.py @@ -23,13 +23,14 @@ class SiteEachContextTest(TestCase): Check each_context contains the documented variables and that available_apps context variable structure is the expected one. """ + request_factory = RequestFactory() + @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_superuser(username='super', password='secret', email='super@example.com') def setUp(self): - factory = RequestFactory() - request = factory.get(reverse('test_adminsite:index')) + request = self.request_factory.get(reverse('test_adminsite:index')) request.user = self.u1 self.ctx = site.each_context(request) @@ -41,7 +42,7 @@ class SiteEachContextTest(TestCase): self.assertIs(ctx['has_permission'], True) def test_each_context_site_url_with_script_name(self): - request = RequestFactory().get(reverse('test_adminsite:index'), SCRIPT_NAME='/my-script-name/') + request = self.request_factory.get(reverse('test_adminsite:index'), SCRIPT_NAME='/my-script-name/') request.user = self.u1 self.assertEqual(site.each_context(request)['site_url'], '/my-script-name/') diff --git a/tests/admin_views/test_templatetags.py b/tests/admin_views/test_templatetags.py index 65548bf7e0..71953d08ca 100644 --- a/tests/admin_views/test_templatetags.py +++ b/tests/admin_views/test_templatetags.py @@ -14,12 +14,13 @@ from .tests import AdminViewBasicTestCase class AdminTemplateTagsTest(AdminViewBasicTestCase): + request_factory = RequestFactory() + def test_submit_row(self): """ submit_row template tag should pass whole context. """ - factory = RequestFactory() - request = factory.get(reverse('admin:auth_user_change', args=[self.superuser.pk])) + request = self.request_factory.get(reverse('admin:auth_user_change', args=[self.superuser.pk])) request.user = self.superuser admin = UserAdmin(User, site) extra_context = {'extra': True} @@ -33,9 +34,8 @@ class AdminTemplateTagsTest(AdminViewBasicTestCase): admin_modify template tags follow the standard search pattern admin/app_label/model/template.html. """ - factory = RequestFactory() article = Article.objects.all()[0] - request = factory.get(reverse('admin:admin_views_article_change', args=[article.pk])) + request = self.request_factory.get(reverse('admin:admin_views_article_change', args=[article.pk])) request.user = self.superuser admin = ArticleAdmin(Article, site) extra_context = {'show_publish': True, 'extra': True} @@ -53,8 +53,7 @@ class AdminTemplateTagsTest(AdminViewBasicTestCase): admin_list template tags follow the standard search pattern admin/app_label/model/template.html. """ - factory = RequestFactory() - request = factory.get(reverse('admin:admin_views_article_changelist')) + request = self.request_factory.get(reverse('admin:admin_views_article_changelist')) request.user = self.superuser admin = ArticleAdmin(Article, site) admin.date_hierarchy = 'date' diff --git a/tests/auth_tests/test_decorators.py b/tests/auth_tests/test_decorators.py index 9cd79b4190..fbccebea57 100644 --- a/tests/auth_tests/test_decorators.py +++ b/tests/auth_tests/test_decorators.py @@ -58,6 +58,8 @@ class PermissionsRequiredDecoratorTest(TestCase): """ Tests for the permission_required decorator """ + factory = RequestFactory() + @classmethod def setUpTestData(cls): cls.user = models.User.objects.create(username='joe', password='qwerty') @@ -65,9 +67,6 @@ class PermissionsRequiredDecoratorTest(TestCase): perms = models.Permission.objects.filter(codename__in=('add_customuser', 'change_customuser')) cls.user.user_permissions.add(*perms) - def setUp(self): - self.factory = RequestFactory() - def test_many_permissions_pass(self): @permission_required(['auth_tests.add_customuser', 'auth_tests.change_customuser']) diff --git a/tests/auth_tests/test_templates.py b/tests/auth_tests/test_templates.py index db35dc930d..ec1a4e5b75 100644 --- a/tests/auth_tests/test_templates.py +++ b/tests/auth_tests/test_templates.py @@ -14,13 +14,13 @@ from .client import PasswordResetConfirmClient @override_settings(ROOT_URLCONF='auth_tests.urls') class AuthTemplateTests(TestCase): + request_factory = RequestFactory() @classmethod def setUpTestData(cls): - rf = RequestFactory() user = User.objects.create_user('jsmith', 'jsmith@example.com', 'pass') user = authenticate(username=user.username, password='pass') - request = rf.get('/somepath/') + request = cls.request_factory.get('/somepath/') request.user = user cls.user, cls.request = user, request diff --git a/tests/cache/tests.py b/tests/cache/tests.py index ad0ef05765..6d957c54bb 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -264,9 +264,7 @@ def caches_setting_for_tests(base=None, exclude=None, **params): class BaseCacheTests: # A common set of tests to apply to all cache backends - - def setUp(self): - self.factory = RequestFactory() + factory = RequestFactory() def tearDown(self): cache.clear() @@ -1584,11 +1582,9 @@ class DefaultNonExpiringCacheKeyTests(SimpleTestCase): ) class CacheUtils(SimpleTestCase): """TestCase for django.utils.cache functions.""" - - def setUp(self): - self.host = 'www.example.com' - self.path = '/cache/test/' - self.factory = RequestFactory(HTTP_HOST=self.host) + host = 'www.example.com' + path = '/cache/test/' + factory = RequestFactory(HTTP_HOST=host) def tearDown(self): cache.clear() @@ -1734,10 +1730,8 @@ class PrefixedCacheUtils(CacheUtils): }, ) class CacheHEADTest(SimpleTestCase): - - def setUp(self): - self.path = '/cache/test/' - self.factory = RequestFactory() + path = '/cache/test/' + factory = RequestFactory() def tearDown(self): cache.clear() @@ -1786,10 +1780,8 @@ class CacheHEADTest(SimpleTestCase): ], ) class CacheI18nTest(SimpleTestCase): - - def setUp(self): - self.path = '/cache/test/' - self.factory = RequestFactory() + path = '/cache/test/' + factory = RequestFactory() def tearDown(self): cache.clear() @@ -2014,10 +2006,9 @@ def csrf_view(request): }, ) class CacheMiddlewareTest(SimpleTestCase): + factory = RequestFactory() def setUp(self): - super().setUp() - self.factory = RequestFactory() self.default_cache = caches['default'] self.other_cache = caches['other'] @@ -2226,9 +2217,8 @@ class TestWithTemplateResponse(SimpleTestCase): content being complete (which is not necessarily always the case with a TemplateResponse) """ - def setUp(self): - self.path = '/cache/test/' - self.factory = RequestFactory() + path = '/cache/test/' + factory = RequestFactory() def tearDown(self): cache.clear() diff --git a/tests/generic_inline_admin/tests.py b/tests/generic_inline_admin/tests.py index 8ba24037d4..8279e32405 100644 --- a/tests/generic_inline_admin/tests.py +++ b/tests/generic_inline_admin/tests.py @@ -91,10 +91,10 @@ class GenericAdminViewTest(TestDataMixin, TestCase): @override_settings(ROOT_URLCONF='generic_inline_admin.urls') class GenericInlineAdminParametersTest(TestDataMixin, TestCase): + factory = RequestFactory() def setUp(self): self.client.force_login(self.superuser) - self.factory = RequestFactory() def _create_object(self, model): """ diff --git a/tests/generic_views/test_edit.py b/tests/generic_views/test_edit.py index d85d5a79b5..bdabf1d0d2 100644 --- a/tests/generic_views/test_edit.py +++ b/tests/generic_views/test_edit.py @@ -12,6 +12,8 @@ from .models import Artist, Author class FormMixinTests(SimpleTestCase): + request_factory = RequestFactory() + def test_initial_data(self): """ Test instance independence of initial data dict (see #16138) """ initial_1 = FormMixin().get_initial() @@ -23,8 +25,7 @@ class FormMixinTests(SimpleTestCase): """ Test prefix can be set (see #18872) """ test_string = 'test' - rf = RequestFactory() - get_request = rf.get('/') + get_request = self.request_factory.get('/') class TestFormMixin(FormMixin): request = get_request @@ -39,7 +40,7 @@ class FormMixinTests(SimpleTestCase): def test_get_form(self): class TestFormMixin(FormMixin): - request = RequestFactory().get('/') + request = self.request_factory.get('/') self.assertIsInstance( TestFormMixin().get_form(forms.Form), forms.Form, @@ -56,7 +57,7 @@ class FormMixinTests(SimpleTestCase): def test_get_context_data(self): class FormContext(FormMixin): - request = RequestFactory().get('/') + request = self.request_factory.get('/') form_class = forms.Form self.assertIsInstance(FormContext().get_context_data()['form'], forms.Form) diff --git a/tests/handlers/tests.py b/tests/handlers/tests.py index 2edca592ab..70f0e875a5 100644 --- a/tests/handlers/tests.py +++ b/tests/handlers/tests.py @@ -8,6 +8,7 @@ from django.test import ( class HandlerTests(SimpleTestCase): + request_factory = RequestFactory() def setUp(self): request_started.disconnect(close_old_connections) @@ -24,7 +25,7 @@ class HandlerTests(SimpleTestCase): A non-UTF-8 path populates PATH_INFO with an URL-encoded path and produces a 404. """ - environ = RequestFactory().get('/').environ + environ = self.request_factory.get('/').environ environ['PATH_INFO'] = '\xed' handler = WSGIHandler() response = handler(environ, lambda *a, **k: None) @@ -35,7 +36,7 @@ class HandlerTests(SimpleTestCase): """ Non-ASCII query strings are properly decoded (#20530, #22996). """ - environ = RequestFactory().get('/').environ + environ = self.request_factory.get('/').environ raw_query_strings = [ b'want=caf%C3%A9', # This is the proper way to encode 'café' b'want=caf\xc3\xa9', # UA forgot to quote bytes @@ -53,7 +54,7 @@ class HandlerTests(SimpleTestCase): def test_non_ascii_cookie(self): """Non-ASCII cookies set in JavaScript are properly decoded (#20557).""" - environ = RequestFactory().get('/').environ + environ = self.request_factory.get('/').environ raw_cookie = 'want="café"'.encode('utf-8').decode('iso-8859-1') environ['HTTP_COOKIE'] = raw_cookie request = WSGIRequest(environ) @@ -64,7 +65,7 @@ class HandlerTests(SimpleTestCase): Invalid cookie content should result in an absent cookie, but not in a crash while trying to decode it (#23638). """ - environ = RequestFactory().get('/').environ + environ = self.request_factory.get('/').environ environ['HTTP_COOKIE'] = 'x=W\x03c(h]\x8e' request = WSGIRequest(environ) # We don't test COOKIES content, as the result might differ between @@ -78,7 +79,7 @@ class HandlerTests(SimpleTestCase): Invalid boundary string should produce a "Bad Request" response, not a server error (#23887). """ - environ = RequestFactory().post('/malformed_post/').environ + environ = self.request_factory.post('/malformed_post/').environ environ['CONTENT_TYPE'] = 'multipart/form-data; boundary=WRONG\x07' handler = WSGIHandler() response = handler(environ, lambda *a, **k: None) @@ -153,6 +154,7 @@ def empty_middleware(get_response): @override_settings(ROOT_URLCONF='handlers.urls') class HandlerRequestTests(SimpleTestCase): + request_factory = RequestFactory() def test_suspiciousop_in_view_returns_400(self): response = self.client.get('/suspicious/') @@ -172,14 +174,14 @@ class HandlerRequestTests(SimpleTestCase): self.assertContains(response, '\u260e%E2%A9\u2665', status_code=404) def test_environ_path_info_type(self): - environ = RequestFactory().get('/%E2%A8%87%87%A5%E2%A8%A0').environ + environ = self.request_factory.get('/%E2%A8%87%87%A5%E2%A8%A0').environ self.assertIsInstance(environ['PATH_INFO'], str) def test_handle_accepts_httpstatus_enum_value(self): def start_response(status, headers): start_response.status = status - environ = RequestFactory().get('/httpstatus_enum/').environ + environ = self.request_factory.get('/httpstatus_enum/').environ WSGIHandler()(environ, start_response) self.assertEqual(start_response.status, '200 OK') diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py index c9d4ecde28..317a380a2f 100644 --- a/tests/i18n/tests.py +++ b/tests/i18n/tests.py @@ -1142,10 +1142,7 @@ class FormattingTests(SimpleTestCase): class MiscTests(SimpleTestCase): - - def setUp(self): - super().setUp() - self.rf = RequestFactory() + rf = RequestFactory() @override_settings(LANGUAGE_CODE='de') def test_english_fallback(self): @@ -1640,10 +1637,7 @@ class UnprefixedDefaultLanguageTests(SimpleTestCase): ROOT_URLCONF='i18n.urls' ) class CountrySpecificLanguageTests(SimpleTestCase): - - def setUp(self): - super().setUp() - self.rf = RequestFactory() + rf = RequestFactory() def test_check_for_language(self): self.assertTrue(check_for_language('en')) diff --git a/tests/logging_tests/tests.py b/tests/logging_tests/tests.py index d48b3cd8db..37010ab7d0 100644 --- a/tests/logging_tests/tests.py +++ b/tests/logging_tests/tests.py @@ -246,6 +246,7 @@ class CallbackFilterTest(SimpleTestCase): class AdminEmailHandlerTest(SimpleTestCase): logger = logging.getLogger('django') + request_factory = RequestFactory() def get_admin_email_handler(self, logger): # AdminEmailHandler does not get filtered out @@ -307,8 +308,7 @@ class AdminEmailHandlerTest(SimpleTestCase): orig_filters = admin_email_handler.filters try: admin_email_handler.filters = [] - rf = RequestFactory() - request = rf.get('/') + request = self.request_factory.get('/') self.logger.error( message, token1, token2, extra={ @@ -388,9 +388,8 @@ class AdminEmailHandlerTest(SimpleTestCase): """ handler = self.get_admin_email_handler(self.logger) record = self.logger.makeRecord('name', logging.ERROR, 'function', 'lno', 'message', None, None) - rf = RequestFactory() url_path = '/º' - record.request = rf.get(url_path) + record.request = self.request_factory.get(url_path) handler.emit(record) self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] diff --git a/tests/messages_tests/test_api.py b/tests/messages_tests/test_api.py index 86fd5c6838..603aea437f 100644 --- a/tests/messages_tests/test_api.py +++ b/tests/messages_tests/test_api.py @@ -15,8 +15,9 @@ class DummyStorage: class ApiTests(SimpleTestCase): + rf = RequestFactory() + def setUp(self): - self.rf = RequestFactory() self.request = self.rf.request() self.storage = DummyStorage() diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py index 88e33348e6..2da1e11a4e 100644 --- a/tests/middleware/tests.py +++ b/tests/middleware/tests.py @@ -428,9 +428,10 @@ class BrokenLinkEmailsMiddlewareTest(SimpleTestCase): @override_settings(ROOT_URLCONF='middleware.cond_get_urls') class ConditionalGetMiddlewareTest(SimpleTestCase): + request_factory = RequestFactory() def setUp(self): - self.req = RequestFactory().get('/') + self.req = self.request_factory.get('/') self.resp = self.client.get(self.req.path_info) # Tests for the ETag header @@ -569,7 +570,7 @@ class ConditionalGetMiddlewareTest(SimpleTestCase): """ get_response = ConditionalGetMiddleware().process_response(self.req, self.resp) etag = get_response['ETag'] - put_request = RequestFactory().put('/', HTTP_IF_MATCH=etag) + put_request = self.request_factory.put('/', HTTP_IF_MATCH=etag) put_response = HttpResponse(status=200) conditional_get_response = ConditionalGetMiddleware().process_response(put_request, put_response) self.assertEqual(conditional_get_response.status_code, 200) # should never be a 412 @@ -580,7 +581,7 @@ class ConditionalGetMiddlewareTest(SimpleTestCase): HEAD request since it can't do so accurately without access to the response body of the corresponding GET. """ - request = RequestFactory().head('/') + request = self.request_factory.head('/') response = HttpResponse(status=200) conditional_get_response = ConditionalGetMiddleware().process_response(request, response) self.assertNotIn('ETag', conditional_get_response) @@ -700,9 +701,10 @@ class GZipMiddlewareTest(SimpleTestCase): incompressible_string = b''.join(int2byte(random.randint(0, 255)) for _ in range(500)) sequence = [b'a' * 500, b'b' * 200, b'a' * 300] sequence_unicode = ['a' * 500, 'é' * 200, 'a' * 300] + request_factory = RequestFactory() def setUp(self): - self.req = RequestFactory().get('/') + self.req = self.request_factory.get('/') self.req.META['HTTP_ACCEPT_ENCODING'] = 'gzip, deflate' self.req.META['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1' self.resp = HttpResponse() diff --git a/tests/servers/test_basehttp.py b/tests/servers/test_basehttp.py index 3e694c3750..32fdbf3c0e 100644 --- a/tests/servers/test_basehttp.py +++ b/tests/servers/test_basehttp.py @@ -15,9 +15,10 @@ class Stub: class WSGIRequestHandlerTestCase(SimpleTestCase): + request_factory = RequestFactory() def test_log_message(self): - request = WSGIRequest(RequestFactory().get('/').environ) + request = WSGIRequest(self.request_factory.get('/').environ) request.makefile = lambda *args, **kwargs: BytesIO() handler = WSGIRequestHandler(request, '192.168.0.2', None) level_status_codes = { @@ -39,7 +40,7 @@ class WSGIRequestHandlerTestCase(SimpleTestCase): self.assertNotEqual(cm.records[0].levelname, wrong_level.upper()) def test_https(self): - request = WSGIRequest(RequestFactory().get('/').environ) + request = WSGIRequest(self.request_factory.get('/').environ) request.makefile = lambda *args, **kwargs: BytesIO() handler = WSGIRequestHandler(request, '192.168.0.2', None) diff --git a/tests/sessions_tests/tests.py b/tests/sessions_tests/tests.py index c213628dbb..733f5adb1d 100644 --- a/tests/sessions_tests/tests.py +++ b/tests/sessions_tests/tests.py @@ -625,10 +625,11 @@ class CacheSessionTests(SessionTestsMixin, unittest.TestCase): class SessionMiddlewareTests(TestCase): + request_factory = RequestFactory() @override_settings(SESSION_COOKIE_SECURE=True) def test_secure_session_cookie(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() @@ -642,7 +643,7 @@ class SessionMiddlewareTests(TestCase): @override_settings(SESSION_COOKIE_HTTPONLY=True) def test_httponly_session_cookie(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() @@ -660,7 +661,7 @@ class SessionMiddlewareTests(TestCase): @override_settings(SESSION_COOKIE_SAMESITE='Strict') def test_samesite_session_cookie(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') response = HttpResponse() middleware = SessionMiddleware() middleware.process_request(request) @@ -670,7 +671,7 @@ class SessionMiddlewareTests(TestCase): @override_settings(SESSION_COOKIE_HTTPONLY=False) def test_no_httponly_session_cookie(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() @@ -687,7 +688,7 @@ class SessionMiddlewareTests(TestCase): ) def test_session_save_on_500(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') response = HttpResponse('Horrible error') response.status_code = 500 middleware = SessionMiddleware() @@ -704,7 +705,7 @@ class SessionMiddlewareTests(TestCase): def test_session_update_error_redirect(self): path = '/foo/' - request = RequestFactory().get(path) + request = self.request_factory.get(path) response = HttpResponse() middleware = SessionMiddleware() @@ -723,7 +724,7 @@ class SessionMiddlewareTests(TestCase): middleware.process_response(request, response) def test_session_delete_on_end(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() @@ -750,7 +751,7 @@ class SessionMiddlewareTests(TestCase): @override_settings(SESSION_COOKIE_DOMAIN='.example.local', SESSION_COOKIE_PATH='/example/') def test_session_delete_on_end_with_custom_domain_and_path(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() @@ -778,7 +779,7 @@ class SessionMiddlewareTests(TestCase): ) def test_flush_empty_without_session_cookie_doesnt_set_cookie(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() @@ -799,7 +800,7 @@ class SessionMiddlewareTests(TestCase): If a session is emptied of data but still has a key, it should still be updated. """ - request = RequestFactory().get('/') + request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() diff --git a/tests/template_backends/test_django.py b/tests/template_backends/test_django.py index 567537f7a2..e7a4a03546 100644 --- a/tests/template_backends/test_django.py +++ b/tests/template_backends/test_django.py @@ -12,6 +12,7 @@ class DjangoTemplatesTests(TemplateStringsTests): engine_class = DjangoTemplates backend_name = 'django' + request_factory = RequestFactory() def test_context_has_priority_over_template_context_processors(self): # See ticket #23789. @@ -25,7 +26,7 @@ class DjangoTemplatesTests(TemplateStringsTests): }) template = engine.from_string('{{ processors }}') - request = RequestFactory().get('/') + request = self.request_factory.get('/') # Context processors run content = template.render({}, request) @@ -45,7 +46,7 @@ class DjangoTemplatesTests(TemplateStringsTests): }) template = engine.from_string('') context = Context() - request_context = RequestContext(RequestFactory().get('/'), {}) + request_context = RequestContext(self.request_factory.get('/'), {}) msg = 'context must be a dict rather than Context.' with self.assertRaisesMessage(TypeError, msg): template.render(context) diff --git a/tests/template_tests/syntax_tests/test_url.py b/tests/template_tests/syntax_tests/test_url.py index 2103ba6159..a6cc2d50a0 100644 --- a/tests/template_tests/syntax_tests/test_url.py +++ b/tests/template_tests/syntax_tests/test_url.py @@ -7,6 +7,7 @@ from ..utils import setup @override_settings(ROOT_URLCONF='template_tests.urls') class UrlTagTests(SimpleTestCase): + request_factory = RequestFactory() # Successes @setup({'url01': '{% url "client" client.id %}'}) @@ -227,7 +228,7 @@ class UrlTagTests(SimpleTestCase): @setup({'url-namespace01': '{% url "app:named.client" 42 %}'}) def test_url_namespace01(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') request.resolver_match = resolve('/ns1/') template = self.engine.get_template('url-namespace01') context = RequestContext(request) @@ -236,7 +237,7 @@ class UrlTagTests(SimpleTestCase): @setup({'url-namespace02': '{% url "app:named.client" 42 %}'}) def test_url_namespace02(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') request.resolver_match = resolve('/ns2/') template = self.engine.get_template('url-namespace02') context = RequestContext(request) @@ -245,7 +246,7 @@ class UrlTagTests(SimpleTestCase): @setup({'url-namespace03': '{% url "app:named.client" 42 %}'}) def test_url_namespace03(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') template = self.engine.get_template('url-namespace03') context = RequestContext(request) output = template.render(context) @@ -253,7 +254,7 @@ class UrlTagTests(SimpleTestCase): @setup({'url-namespace-no-current-app': '{% url "app:named.client" 42 %}'}) def test_url_namespace_no_current_app(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') request.resolver_match = resolve('/ns1/') request.current_app = None template = self.engine.get_template('url-namespace-no-current-app') @@ -263,7 +264,7 @@ class UrlTagTests(SimpleTestCase): @setup({'url-namespace-explicit-current-app': '{% url "app:named.client" 42 %}'}) def test_url_namespace_explicit_current_app(self): - request = RequestFactory().get('/') + request = self.request_factory.get('/') request.resolver_match = resolve('/ns1/') request.current_app = 'app' template = self.engine.get_template('url-namespace-explicit-current-app') diff --git a/tests/template_tests/test_context.py b/tests/template_tests/test_context.py index 5cd2ec2e82..bdfd556690 100644 --- a/tests/template_tests/test_context.py +++ b/tests/template_tests/test_context.py @@ -213,6 +213,7 @@ class ContextTests(SimpleTestCase): class RequestContextTests(SimpleTestCase): + request_factory = RequestFactory() def test_include_only(self): """ @@ -224,7 +225,7 @@ class RequestContextTests(SimpleTestCase): 'child': '{{ var|default:"none" }}', }), ]) - request = RequestFactory().get('/') + request = self.request_factory.get('/') ctx = RequestContext(request, {'var': 'parent'}) self.assertEqual(engine.from_string('{% include "child" %}').render(ctx), 'parent') self.assertEqual(engine.from_string('{% include "child" only %}').render(ctx), 'none') @@ -233,7 +234,7 @@ class RequestContextTests(SimpleTestCase): """ #7116 -- Optimize RequetsContext construction """ - request = RequestFactory().get('/') + request = self.request_factory.get('/') ctx = RequestContext(request, {}) # The stack should now contain 3 items: # [builtins, supplied context, context processor, empty dict] @@ -245,7 +246,7 @@ class RequestContextTests(SimpleTestCase): # test comparing RequestContext to prevent problems if somebody # adds __eq__ in the future - request = RequestFactory().get('/') + request = self.request_factory.get('/') self.assertEqual( RequestContext(request, dict_=test_data), @@ -254,7 +255,7 @@ class RequestContextTests(SimpleTestCase): def test_modify_context_and_render(self): template = Template('{{ foo }}') - request = RequestFactory().get('/') + request = self.request_factory.get('/') context = RequestContext(request, {}) context['foo'] = 'foo' self.assertEqual(template.render(context), 'foo') diff --git a/tests/template_tests/test_response.py b/tests/template_tests/test_response.py index 39292a0713..b0d66dc809 100644 --- a/tests/template_tests/test_response.py +++ b/tests/template_tests/test_response.py @@ -224,9 +224,7 @@ class SimpleTemplateResponseTest(SimpleTestCase): }, }]) class TemplateResponseTest(SimpleTestCase): - - def setUp(self): - self.factory = RequestFactory() + factory = RequestFactory() def _response(self, template='foo', *args, **kwargs): self._request = self.factory.get('/') diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py index 22e28be198..bb6c8bbff0 100644 --- a/tests/test_client/tests.py +++ b/tests/test_client/tests.py @@ -861,9 +861,7 @@ class RequestFactoryTest(SimpleTestCase): ('options', _generic_view), ('trace', trace_view), ) - - def setUp(self): - self.request_factory = RequestFactory() + request_factory = RequestFactory() def test_request_factory(self): """The request factory implements all the HTTP/1.1 methods.""" diff --git a/tests/view_tests/tests/test_defaults.py b/tests/view_tests/tests/test_defaults.py index c34f38a8ca..e93558abc1 100644 --- a/tests/view_tests/tests/test_defaults.py +++ b/tests/view_tests/tests/test_defaults.py @@ -19,6 +19,7 @@ class DefaultsTests(TestCase): '/nonexistent_url/', # this is in urls.py '/other_nonexistent_url/', # this NOT in urls.py ] + request_factory = RequestFactory() @classmethod def setUpTestData(cls): @@ -73,8 +74,7 @@ class DefaultsTests(TestCase): self.assertEqual(response.status_code, 500) def test_bad_request(self): - rf = RequestFactory() - request = rf.get('/') + request = self.request_factory.get('/') response = bad_request(request, Exception()) self.assertEqual(response.status_code, 400) self.assertEqual(response.content, b'