Made reused RequestFactory instances class attributes.

This commit is contained in:
Simon Charette 2018-11-26 14:01:27 -05:00 committed by Tim Graham
parent 7f63b894c0
commit 0f212db29d
25 changed files with 93 additions and 109 deletions

View File

@ -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')

View File

@ -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.

View File

@ -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):
"""

View File

@ -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

View File

@ -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/')

View File

@ -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'

View File

@ -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'])

View File

@ -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

32
tests/cache/tests.py vendored
View File

@ -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()

View File

@ -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):
"""

View File

@ -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)

View File

@ -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')

View File

@ -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'))

View File

@ -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]

View File

@ -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()

View File

@ -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()

View File

@ -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)

View File

@ -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()

View File

@ -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)

View File

@ -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')

View File

@ -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')

View File

@ -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('/')

View File

@ -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."""

View File

@ -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'<h1>Bad Request (400)</h1>')
@ -116,8 +116,7 @@ class DefaultsTests(TestCase):
Default error views should raise TemplateDoesNotExist when passed a
template that doesn't exist.
"""
rf = RequestFactory()
request = rf.get('/')
request = self.request_factory.get('/')
with self.assertRaises(TemplateDoesNotExist):
bad_request(request, Exception(), template_name='nonexistent')

View File

@ -9,6 +9,7 @@ from django.test.client import RequestFactory
@override_settings(ROOT_URLCONF='wsgi.urls')
class WSGITest(SimpleTestCase):
request_factory = RequestFactory()
def setUp(self):
request_started.disconnect(close_old_connections)
@ -22,7 +23,7 @@ class WSGITest(SimpleTestCase):
"""
application = get_wsgi_application()
environ = RequestFactory()._base_environ(
environ = self.request_factory._base_environ(
PATH_INFO="/",
CONTENT_TYPE="text/html; charset=utf-8",
REQUEST_METHOD="GET"
@ -53,7 +54,7 @@ class WSGITest(SimpleTestCase):
def __init__(self, filelike, blksize=8192):
filelike.close()
application = get_wsgi_application()
environ = RequestFactory()._base_environ(
environ = self.request_factory._base_environ(
PATH_INFO='/file/',
REQUEST_METHOD='GET',
**{'wsgi.file_wrapper': FileWrapper}