1
0
mirror of https://github.com/django/django.git synced 2024-12-22 17:16:24 +00:00

Fixed #21774 -- Isolate all test urls from eachother.

This (nearly) completes the work to isolate all the test modules from
each other. This is now more important as importing models from another
module will case PendingDeprecationWarnings if those modules are not in
INSTALLED_APPS. The only remaining obvious dependencies are:

- d.c.auth depends on d.c.admin (because of the is_admin flag to some
  views), but this is not so important and d.c.admin is in
  always_installed_apps
- test_client_regress depends on test_client. Eventually these should
  become a single module, as the split serves no useful purpose.
This commit is contained in:
Marc Tamlyn 2014-01-14 15:43:27 +00:00
parent ac8d0a4815
commit 2607fa9016
24 changed files with 397 additions and 350 deletions

View File

@ -17,6 +17,7 @@ from django.utils.http import urlsafe_base64_encode
PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',), PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
) )
class AuthTemplateTests(TestCase): class AuthTemplateTests(TestCase):
urls = 'django.contrib.auth.tests.urls'
def test_titles(self): def test_titles(self):
rf = RequestFactory() rf = RequestFactory()

View File

@ -1,4 +1,5 @@
from django.conf.urls import patterns, url from django.conf.urls import patterns, url, include
from django.contrib import admin
from django.contrib.auth import context_processors from django.contrib.auth import context_processors
from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth.urls import urlpatterns from django.contrib.auth.urls import urlpatterns
@ -98,4 +99,7 @@ urlpatterns = urlpatterns + patterns('',
(r'^auth_processor_messages/$', auth_processor_messages), (r'^auth_processor_messages/$', auth_processor_messages),
(r'^custom_request_auth_login/$', custom_request_auth_login), (r'^custom_request_auth_login/$', custom_request_auth_login),
url(r'^userpage/(.+)/$', userpage, name="userpage"), url(r'^userpage/(.+)/$', userpage, name="userpage"),
# This line is only required to render the password reset with is_admin=True
(r'^admin/', include(admin.site.urls)),
) )

View File

@ -16,6 +16,7 @@ class AdminCustomUrlsTest(TestCase):
* The ModelAdmin for Action customizes the add_view URL, it's * The ModelAdmin for Action customizes the add_view URL, it's
'<app name>/<model name>/!add/' '<app name>/<model name>/!add/'
""" """
urls = 'admin_custom_urls.urls'
fixtures = ['users.json', 'actions.json'] fixtures = ['users.json', 'actions.json']
def setUp(self): def setUp(self):
@ -28,7 +29,7 @@ class AdminCustomUrlsTest(TestCase):
""" """
Ensure GET on the add_view works. Ensure GET on the add_view works.
""" """
response = self.client.get('/custom_urls/admin/admin_custom_urls/action/!add/') response = self.client.get('/admin/admin_custom_urls/action/!add/')
self.assertIsInstance(response, TemplateResponse) self.assertIsInstance(response, TemplateResponse)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -37,7 +38,7 @@ class AdminCustomUrlsTest(TestCase):
Ensure GET on the add_view plus specifying a field value in the query Ensure GET on the add_view plus specifying a field value in the query
string works. string works.
""" """
response = self.client.get('/custom_urls/admin/admin_custom_urls/action/!add/', {'name': 'My Action'}) response = self.client.get('/admin/admin_custom_urls/action/!add/', {'name': 'My Action'})
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertContains(response, 'value="My Action"') self.assertContains(response, 'value="My Action"')
@ -50,7 +51,7 @@ class AdminCustomUrlsTest(TestCase):
"name": 'Action added through a popup', "name": 'Action added through a popup',
"description": "Description of added action", "description": "Description of added action",
} }
response = self.client.post('/custom_urls/admin/admin_custom_urls/action/!add/', post_data) response = self.client.post('/admin/admin_custom_urls/action/!add/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertContains(response, 'dismissAddAnotherPopup') self.assertContains(response, 'dismissAddAnotherPopup')
self.assertContains(response, 'Action added through a popup') self.assertContains(response, 'Action added through a popup')
@ -61,7 +62,7 @@ class AdminCustomUrlsTest(TestCase):
""" """
# Should get the change_view for model instance with PK 'add', not show # Should get the change_view for model instance with PK 'add', not show
# the add_view # the add_view
response = self.client.get('/custom_urls/admin/admin_custom_urls/action/add/') response = self.client.get('/admin/admin_custom_urls/action/add/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertContains(response, 'Change action') self.assertContains(response, 'Change action')
@ -84,6 +85,7 @@ class AdminCustomUrlsTest(TestCase):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class CustomRedirects(TestCase): class CustomRedirects(TestCase):
urls = 'admin_custom_urls.urls'
fixtures = ['users.json', 'actions.json'] fixtures = ['users.json', 'actions.json']
def setUp(self): def setUp(self):

View File

@ -1542,6 +1542,7 @@ class ArgumentOrder(AdminScriptTestCase):
class StartProject(LiveServerTestCase, AdminScriptTestCase): class StartProject(LiveServerTestCase, AdminScriptTestCase):
urls = 'admin_scripts.urls'
available_apps = [ available_apps = [
'admin_scripts', 'admin_scripts',
'django.contrib.auth', 'django.contrib.auth',
@ -1649,7 +1650,7 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
def test_custom_project_template_from_tarball_by_url(self): def test_custom_project_template_from_tarball_by_url(self):
"Make sure the startproject management command is able to use a different project template from a tarball via a url" "Make sure the startproject management command is able to use a different project template from a tarball via a url"
template_url = '%s/admin_scripts/custom_templates/project_template.tgz' % self.live_server_url template_url = '%s/custom_templates/project_template.tgz' % self.live_server_url
args = ['startproject', '--template', template_url, 'urltestproject'] args = ['startproject', '--template', template_url, 'urltestproject']
testproject_dir = os.path.join(test_dir, 'urltestproject') testproject_dir = os.path.join(test_dir, 'urltestproject')
@ -1662,7 +1663,7 @@ class StartProject(LiveServerTestCase, AdminScriptTestCase):
def test_project_template_tarball_url(self): def test_project_template_tarball_url(self):
"Startproject management command handles project template tar/zip balls from non-canonical urls" "Startproject management command handles project template tar/zip balls from non-canonical urls"
template_url = '%s/admin_scripts/custom_templates/project_template.tgz/' % self.live_server_url template_url = '%s/custom_templates/project_template.tgz/' % self.live_server_url
args = ['startproject', '--template', template_url, 'urltestproject'] args = ['startproject', '--template', template_url, 'urltestproject']
testproject_dir = os.path.join(test_dir, 'urltestproject') testproject_dir = os.path.join(test_dir, 'urltestproject')

View File

@ -184,13 +184,14 @@ class AdminFormfieldForDBFieldTests(TestCase):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase): class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"] fixtures = ["admin-widgets-users.xml"]
urls = 'admin_widgets.urls'
def testFilterChoicesByRequestUser(self): def testFilterChoicesByRequestUser(self):
""" """
Ensure the user can only see their own cars in the foreign key dropdown. Ensure the user can only see their own cars in the foreign key dropdown.
""" """
self.client.login(username="super", password="secret") self.client.login(username="super", password="secret")
response = self.client.get("/widget_admin/admin_widgets/cartire/add/") response = self.client.get("/admin_widgets/cartire/add/")
self.assertNotContains(response, "BMW M3") self.assertNotContains(response, "BMW M3")
self.assertContains(response, "Volkswagon Passat") self.assertContains(response, "Volkswagon Passat")
@ -198,7 +199,7 @@ class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class AdminForeignKeyWidgetChangeList(DjangoTestCase): class AdminForeignKeyWidgetChangeList(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"] fixtures = ["admin-widgets-users.xml"]
admin_root = '/widget_admin' urls = 'admin_widgets.urls'
def setUp(self): def setUp(self):
self.client.login(username="super", password="secret") self.client.login(username="super", password="secret")
@ -207,14 +208,14 @@ class AdminForeignKeyWidgetChangeList(DjangoTestCase):
self.client.logout() self.client.logout()
def test_changelist_foreignkey(self): def test_changelist_foreignkey(self):
response = self.client.get('%s/admin_widgets/car/' % self.admin_root) response = self.client.get('/admin_widgets/car/')
self.assertContains(response, '%s/auth/user/add/' % self.admin_root) self.assertContains(response, '/auth/user/add/')
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class AdminForeignKeyRawIdWidget(DjangoTestCase): class AdminForeignKeyRawIdWidget(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"] fixtures = ["admin-widgets-users.xml"]
admin_root = '/widget_admin' urls = 'admin_widgets.urls'
def setUp(self): def setUp(self):
self.client.login(username="super", password="secret") self.client.login(username="super", password="secret")
@ -231,8 +232,7 @@ class AdminForeignKeyRawIdWidget(DjangoTestCase):
} }
# Try posting with a non-existent pk in a raw id field: this # Try posting with a non-existent pk in a raw id field: this
# should result in an error message, not a server exception. # should result in an error message, not a server exception.
response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root, response = self.client.post('/admin_widgets/event/add/', post_data)
post_data)
self.assertContains(response, self.assertContains(response,
'Select a valid choice. That choice is not one of the available choices.') 'Select a valid choice. That choice is not one of the available choices.')
@ -240,7 +240,7 @@ class AdminForeignKeyRawIdWidget(DjangoTestCase):
for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234): for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234):
# This should result in an error message, not a server exception. # This should result in an error message, not a server exception.
response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root, response = self.client.post('/admin_widgets/event/add/',
{"main_band": test_str}) {"main_band": test_str})
self.assertContains(response, self.assertContains(response,
@ -392,6 +392,8 @@ class AdminFileWidgetTest(DjangoTestCase):
class ForeignKeyRawIdWidgetTest(DjangoTestCase): class ForeignKeyRawIdWidgetTest(DjangoTestCase):
urls = 'admin_widgets.urls'
def test_render(self): def test_render(self):
band = models.Band.objects.create(name='Linkin Park') band = models.Band.objects.create(name='Linkin Park')
band.album_set.create( band.album_set.create(
@ -402,7 +404,7 @@ class ForeignKeyRawIdWidgetTest(DjangoTestCase):
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual( self.assertHTMLEqual(
w.render('test', band.pk, attrs={}), w.render('test', band.pk, attrs={}),
'<input type="text" name="test" value="%(bandpk)s" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/band/?_to_field=id" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Linkin Park</strong>' % dict(admin_static_prefix(), bandpk=band.pk) '<input type="text" name="test" value="%(bandpk)s" class="vForeignKeyRawIdAdminField" /><a href="/admin_widgets/band/?_to_field=id" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Linkin Park</strong>' % dict(admin_static_prefix(), bandpk=band.pk)
) )
def test_relations_to_non_primary_key(self): def test_relations_to_non_primary_key(self):
@ -417,7 +419,7 @@ class ForeignKeyRawIdWidgetTest(DjangoTestCase):
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site) w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual( self.assertHTMLEqual(
w.render('test', core.parent_id, attrs={}), w.render('test', core.parent_id, attrs={}),
'<input type="text" name="test" value="86" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/inventory/?_to_field=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Apple</strong>' % admin_static_prefix() '<input type="text" name="test" value="86" class="vForeignKeyRawIdAdminField" /><a href="/admin_widgets/inventory/?_to_field=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Apple</strong>' % admin_static_prefix()
) )
def test_fk_related_model_not_in_admin(self): def test_fk_related_model_not_in_admin(self):
@ -459,11 +461,13 @@ class ForeignKeyRawIdWidgetTest(DjangoTestCase):
) )
self.assertHTMLEqual( self.assertHTMLEqual(
w.render('test', child_of_hidden.parent_id, attrs={}), w.render('test', child_of_hidden.parent_id, attrs={}),
'<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField" /><a href="/widget_admin/admin_widgets/inventory/?_to_field=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Hidden</strong>' % admin_static_prefix() '<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField" /><a href="/admin_widgets/inventory/?_to_field=barcode" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>&nbsp;<strong>Hidden</strong>' % admin_static_prefix()
) )
class ManyToManyRawIdWidgetTest(DjangoTestCase): class ManyToManyRawIdWidgetTest(DjangoTestCase):
urls = 'admin_widgets.urls'
def test_render(self): def test_render(self):
band = models.Band.objects.create(name='Linkin Park') band = models.Band.objects.create(name='Linkin Park')
@ -475,12 +479,12 @@ class ManyToManyRawIdWidgetTest(DjangoTestCase):
w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site) w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual( self.assertHTMLEqual(
w.render('test', [m1.pk, m2.pk], attrs={}), w.render('test', [m1.pk, m2.pk], attrs={}),
'<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="/static/admin/img/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(admin_static_prefix(), m1pk=m1.pk, m2pk=m2.pk) '<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" /><a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="/static/admin/img/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(admin_static_prefix(), m1pk=m1.pk, m2pk=m2.pk)
) )
self.assertHTMLEqual( self.assertHTMLEqual(
w.render('test', [m1.pk]), w.render('test', [m1.pk]),
'<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField" /><a href="/widget_admin/admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(admin_static_prefix(), m1pk=m1.pk) '<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField" /><a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" onclick="return showRelatedObjectLookupPopup(this);"> <img src="%(ADMIN_STATIC_PREFIX)simg/selector-search.gif" width="16" height="16" alt="Lookup" /></a>' % dict(admin_static_prefix(), m1pk=m1.pk)
) )
def test_m2m_related_model_not_in_admin(self): def test_m2m_related_model_not_in_admin(self):

View File

@ -12,7 +12,7 @@ class Author(models.Model):
return self.name return self.name
def get_absolute_url(self): def get_absolute_url(self):
return '/views/authors/%s/' % self.id return '/authors/%s/' % self.id
@python_2_unicode_compatible @python_2_unicode_compatible

View File

@ -29,6 +29,8 @@ UPLOAD_TO = os.path.join(MEDIA_ROOT, 'test_upload')
@override_settings(MEDIA_ROOT=MEDIA_ROOT) @override_settings(MEDIA_ROOT=MEDIA_ROOT)
class FileUploadTests(TestCase): class FileUploadTests(TestCase):
urls = 'file_uploads.urls'
@classmethod @classmethod
def setUpClass(cls): def setUpClass(cls):
if not os.path.isdir(MEDIA_ROOT): if not os.path.isdir(MEDIA_ROOT):
@ -44,7 +46,7 @@ class FileUploadTests(TestCase):
'name': 'Ringo', 'name': 'Ringo',
'file_field': fp, 'file_field': fp,
} }
response = self.client.post('/file_uploads/upload/', post_data) response = self.client.post('/upload/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
def test_large_upload(self): def test_large_upload(self):
@ -71,7 +73,7 @@ class FileUploadTests(TestCase):
except AttributeError: except AttributeError:
post_data[key + '_hash'] = hashlib.sha1(force_bytes(post_data[key])).hexdigest() post_data[key + '_hash'] = hashlib.sha1(force_bytes(post_data[key])).hexdigest()
response = self.client.post('/file_uploads/verify/', post_data) response = self.client.post('/verify/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -87,7 +89,7 @@ class FileUploadTests(TestCase):
r = { r = {
'CONTENT_LENGTH': len(payload), 'CONTENT_LENGTH': len(payload),
'CONTENT_TYPE': client.MULTIPART_CONTENT, 'CONTENT_TYPE': client.MULTIPART_CONTENT,
'PATH_INFO': "/file_uploads/echo_content/", 'PATH_INFO': "/echo_content/",
'REQUEST_METHOD': 'POST', 'REQUEST_METHOD': 'POST',
'wsgi.input': payload, 'wsgi.input': payload,
} }
@ -115,7 +117,7 @@ class FileUploadTests(TestCase):
'file_unicode': file1, 'file_unicode': file1,
} }
response = self.client.post('/file_uploads/unicode_name/', post_data) response = self.client.post('/unicode_name/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -154,7 +156,7 @@ class FileUploadTests(TestCase):
r = { r = {
'CONTENT_LENGTH': len(payload), 'CONTENT_LENGTH': len(payload),
'CONTENT_TYPE': client.MULTIPART_CONTENT, 'CONTENT_TYPE': client.MULTIPART_CONTENT,
'PATH_INFO': "/file_uploads/echo/", 'PATH_INFO': "/echo/",
'REQUEST_METHOD': 'POST', 'REQUEST_METHOD': 'POST',
'wsgi.input': payload, 'wsgi.input': payload,
} }
@ -191,7 +193,7 @@ class FileUploadTests(TestCase):
r = { r = {
'CONTENT_LENGTH': len(payload), 'CONTENT_LENGTH': len(payload),
'CONTENT_TYPE': client.MULTIPART_CONTENT, 'CONTENT_TYPE': client.MULTIPART_CONTENT,
'PATH_INFO': "/file_uploads/echo/", 'PATH_INFO': "/echo/",
'REQUEST_METHOD': 'POST', 'REQUEST_METHOD': 'POST',
'wsgi.input': payload, 'wsgi.input': payload,
} }
@ -215,7 +217,7 @@ class FileUploadTests(TestCase):
simple_file.seek(0) simple_file.seek(0)
simple_file.content_type = 'text/plain; test-key=test_value' simple_file.content_type = 'text/plain; test-key=test_value'
response = self.client.post('/file_uploads/echo_content_type_extra/', { response = self.client.post('/echo_content_type_extra/', {
'no_content_type': no_content_type, 'no_content_type': no_content_type,
'simple_file': simple_file, 'simple_file': simple_file,
}) })
@ -242,7 +244,7 @@ class FileUploadTests(TestCase):
r = { r = {
'CONTENT_LENGTH': len(payload), 'CONTENT_LENGTH': len(payload),
'CONTENT_TYPE': client.MULTIPART_CONTENT, 'CONTENT_TYPE': client.MULTIPART_CONTENT,
'PATH_INFO': '/file_uploads/echo/', 'PATH_INFO': '/echo/',
'REQUEST_METHOD': 'POST', 'REQUEST_METHOD': 'POST',
'wsgi.input': payload, 'wsgi.input': payload,
} }
@ -257,7 +259,7 @@ class FileUploadTests(TestCase):
r = { r = {
'CONTENT_LENGTH': 0, 'CONTENT_LENGTH': 0,
'CONTENT_TYPE': client.MULTIPART_CONTENT, 'CONTENT_TYPE': client.MULTIPART_CONTENT,
'PATH_INFO': '/file_uploads/echo/', 'PATH_INFO': '/echo/',
'REQUEST_METHOD': 'POST', 'REQUEST_METHOD': 'POST',
'wsgi.input': client.FakePayload(b''), 'wsgi.input': client.FakePayload(b''),
} }
@ -276,12 +278,12 @@ class FileUploadTests(TestCase):
bigfile.seek(0) bigfile.seek(0)
# Small file posting should work. # Small file posting should work.
response = self.client.post('/file_uploads/quota/', {'f': smallfile}) response = self.client.post('/quota/', {'f': smallfile})
got = json.loads(response.content.decode('utf-8')) got = json.loads(response.content.decode('utf-8'))
self.assertTrue('f' in got) self.assertTrue('f' in got)
# Large files don't go through. # Large files don't go through.
response = self.client.post("/file_uploads/quota/", {'f': bigfile}) response = self.client.post("/quota/", {'f': bigfile})
got = json.loads(response.content.decode('utf-8')) got = json.loads(response.content.decode('utf-8'))
self.assertTrue('f' not in got) self.assertTrue('f' not in got)
@ -294,7 +296,7 @@ class FileUploadTests(TestCase):
self.assertRaises( self.assertRaises(
AttributeError, AttributeError,
self.client.post, self.client.post,
'/file_uploads/quota/broken/', '/quota/broken/',
{'f': f} {'f': f}
) )
@ -311,7 +313,7 @@ class FileUploadTests(TestCase):
file2a.write(b'a' * (5 * 2 ** 20)) file2a.write(b'a' * (5 * 2 ** 20))
file2a.seek(0) file2a.seek(0)
response = self.client.post('/file_uploads/getlist_count/', { response = self.client.post('/getlist_count/', {
'file1': file1, 'file1': file1,
'field1': 'test', 'field1': 'test',
'field2': 'test3', 'field2': 'test3',
@ -357,7 +359,7 @@ class FileUploadTests(TestCase):
'file_field': fp, 'file_field': fp,
} }
try: try:
self.client.post('/file_uploads/upload_errors/', post_data) self.client.post('/upload_errors/', post_data)
except reference_error.__class__ as err: except reference_error.__class__ as err:
self.assertFalse( self.assertFalse(
str(err) == str(reference_error), str(err) == str(reference_error),
@ -386,7 +388,7 @@ class FileUploadTests(TestCase):
'--%(boundary)s--\r\n', '--%(boundary)s--\r\n',
] ]
response = self.client.post( response = self.client.post(
'/file_uploads/filename_case/', '/filename_case/',
'\r\n'.join(post_data) % vars, '\r\n'.join(post_data) % vars,
'multipart/form-data; boundary=%(boundary)s' % vars 'multipart/form-data; boundary=%(boundary)s' % vars
) )

View File

@ -1,7 +1,7 @@
from django.conf.urls import patterns from django.conf.urls import patterns
urlpatterns = patterns('', urlpatterns = patterns('',
(r'^middleware/customurlconf/noslash$', 'view'), (r'^customurlconf/noslash$', 'view'),
(r'^middleware/customurlconf/slash/$', 'view'), (r'^customurlconf/slash/$', 'view'),
(r'^middleware/customurlconf/needsquoting#/$', 'view'), (r'^customurlconf/needsquoting#/$', 'view'),
) )

View File

@ -28,6 +28,7 @@ from .models import Band
class CommonMiddlewareTest(TestCase): class CommonMiddlewareTest(TestCase):
urls = 'middleware.urls'
def _get_request(self, path): def _get_request(self, path):
request = HttpRequest() request = HttpRequest()
@ -35,7 +36,7 @@ class CommonMiddlewareTest(TestCase):
'SERVER_NAME': 'testserver', 'SERVER_NAME': 'testserver',
'SERVER_PORT': 80, 'SERVER_PORT': 80,
} }
request.path = request.path_info = "/middleware/%s" % path request.path = request.path_info = "/%s" % path
return request return request
@override_settings(APPEND_SLASH=True) @override_settings(APPEND_SLASH=True)
@ -70,7 +71,7 @@ class CommonMiddlewareTest(TestCase):
request = self._get_request('slash') request = self._get_request('slash')
r = CommonMiddleware().process_request(request) r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301) self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, 'http://testserver/middleware/slash/') self.assertEqual(r.url, 'http://testserver/slash/')
@override_settings(APPEND_SLASH=True, DEBUG=True) @override_settings(APPEND_SLASH=True, DEBUG=True)
def test_append_slash_no_redirect_on_POST_in_DEBUG(self): def test_append_slash_no_redirect_on_POST_in_DEBUG(self):
@ -103,7 +104,7 @@ class CommonMiddlewareTest(TestCase):
self.assertEqual(r.status_code, 301) self.assertEqual(r.status_code, 301)
self.assertEqual( self.assertEqual(
r.url, r.url,
'http://testserver/middleware/needsquoting%23/') 'http://testserver/needsquoting%23/')
@override_settings(APPEND_SLASH=False, PREPEND_WWW=True) @override_settings(APPEND_SLASH=False, PREPEND_WWW=True)
def test_prepend_www(self): def test_prepend_www(self):
@ -112,7 +113,7 @@ class CommonMiddlewareTest(TestCase):
self.assertEqual(r.status_code, 301) self.assertEqual(r.status_code, 301)
self.assertEqual( self.assertEqual(
r.url, r.url,
'http://www.testserver/middleware/path/') 'http://www.testserver/path/')
@override_settings(APPEND_SLASH=True, PREPEND_WWW=True) @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_have_slash(self): def test_prepend_www_append_slash_have_slash(self):
@ -120,7 +121,7 @@ class CommonMiddlewareTest(TestCase):
r = CommonMiddleware().process_request(request) r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301) self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, self.assertEqual(r.url,
'http://www.testserver/middleware/slash/') 'http://www.testserver/slash/')
@override_settings(APPEND_SLASH=True, PREPEND_WWW=True) @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_slashless(self): def test_prepend_www_append_slash_slashless(self):
@ -128,7 +129,7 @@ class CommonMiddlewareTest(TestCase):
r = CommonMiddleware().process_request(request) r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301) self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, self.assertEqual(r.url,
'http://www.testserver/middleware/slash/') 'http://www.testserver/slash/')
# The following tests examine expected behavior given a custom urlconf that # The following tests examine expected behavior given a custom urlconf that
# overrides the default one through the request object. # overrides the default one through the request object.
@ -171,7 +172,7 @@ class CommonMiddlewareTest(TestCase):
self.assertFalse(r is None, self.assertFalse(r is None,
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf") "CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
self.assertEqual(r.status_code, 301) self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, 'http://testserver/middleware/customurlconf/slash/') self.assertEqual(r.url, 'http://testserver/customurlconf/slash/')
@override_settings(APPEND_SLASH=True, DEBUG=True) @override_settings(APPEND_SLASH=True, DEBUG=True)
def test_append_slash_no_redirect_on_POST_in_DEBUG_custom_urlconf(self): def test_append_slash_no_redirect_on_POST_in_DEBUG_custom_urlconf(self):
@ -209,7 +210,7 @@ class CommonMiddlewareTest(TestCase):
self.assertEqual(r.status_code, 301) self.assertEqual(r.status_code, 301)
self.assertEqual( self.assertEqual(
r.url, r.url,
'http://testserver/middleware/customurlconf/needsquoting%23/') 'http://testserver/customurlconf/needsquoting%23/')
@override_settings(APPEND_SLASH=False, PREPEND_WWW=True) @override_settings(APPEND_SLASH=False, PREPEND_WWW=True)
def test_prepend_www_custom_urlconf(self): def test_prepend_www_custom_urlconf(self):
@ -219,7 +220,7 @@ class CommonMiddlewareTest(TestCase):
self.assertEqual(r.status_code, 301) self.assertEqual(r.status_code, 301)
self.assertEqual( self.assertEqual(
r.url, r.url,
'http://www.testserver/middleware/customurlconf/path/') 'http://www.testserver/customurlconf/path/')
@override_settings(APPEND_SLASH=True, PREPEND_WWW=True) @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_have_slash_custom_urlconf(self): def test_prepend_www_append_slash_have_slash_custom_urlconf(self):
@ -228,7 +229,7 @@ class CommonMiddlewareTest(TestCase):
r = CommonMiddleware().process_request(request) r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301) self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, self.assertEqual(r.url,
'http://www.testserver/middleware/customurlconf/slash/') 'http://www.testserver/customurlconf/slash/')
@override_settings(APPEND_SLASH=True, PREPEND_WWW=True) @override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_slashless_custom_urlconf(self): def test_prepend_www_append_slash_slashless_custom_urlconf(self):
@ -237,7 +238,7 @@ class CommonMiddlewareTest(TestCase):
r = CommonMiddleware().process_request(request) r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301) self.assertEqual(r.status_code, 301)
self.assertEqual(r.url, self.assertEqual(r.url,
'http://www.testserver/middleware/customurlconf/slash/') 'http://www.testserver/customurlconf/slash/')
# Legacy tests for the 404 error reporting via email (to be removed in 1.8) # Legacy tests for the 404 error reporting via email (to be removed in 1.8)

View File

@ -1,10 +1,9 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from unittest import TestCase
from django.core.urlresolvers import NoReverseMatch from django.core.urlresolvers import NoReverseMatch
from django.contrib.auth.views import logout from django.contrib.auth.views import logout
from django.shortcuts import resolve_url from django.shortcuts import resolve_url
from django.test import TestCase
from .models import UnimportantThing from .models import UnimportantThing
@ -13,6 +12,7 @@ class ResolveUrlTests(TestCase):
""" """
Tests for the ``resolve_url`` function. Tests for the ``resolve_url`` function.
""" """
urls = 'resolve_url.urls'
def test_url_path(self): def test_url_path(self):
""" """

View File

@ -0,0 +1,6 @@
from django.conf.urls import patterns
urlpatterns = patterns('',
(r'^accounts/logout/$', 'django.contrib.auth.views.logout')
)

View File

@ -550,6 +550,8 @@ class TemplateRegressionTests(TestCase):
os.path.dirname(os.path.abspath(upath(__file__))),), os.path.dirname(os.path.abspath(upath(__file__))),),
) )
class TemplateTests(TransRealMixin, TestCase): class TemplateTests(TransRealMixin, TestCase):
urls = 'template_tests.urls'
def test_templates(self): def test_templates(self):
template_tests = self.get_template_tests() template_tests = self.get_template_tests()
filter_tests = filters.get_filter_tests() filter_tests = filters.get_filter_tests()
@ -1701,28 +1703,28 @@ class TemplateTests(TransRealMixin, TestCase):
### URL TAG ######################################################## ### URL TAG ########################################################
# Successes # Successes
'url01': ('{% url "template_tests.views.client" client.id %}', {'client': {'id': 1}}, '/url_tag/client/1/'), 'url01': ('{% url "template_tests.views.client" client.id %}', {'client': {'id': 1}}, '/client/1/'),
'url02': ('{% url "template_tests.views.client_action" id=client.id action="update" %}', {'client': {'id': 1}}, '/url_tag/client/1/update/'), 'url02': ('{% url "template_tests.views.client_action" id=client.id action="update" %}', {'client': {'id': 1}}, '/client/1/update/'),
'url02a': ('{% url "template_tests.views.client_action" client.id "update" %}', {'client': {'id': 1}}, '/url_tag/client/1/update/'), 'url02a': ('{% url "template_tests.views.client_action" client.id "update" %}', {'client': {'id': 1}}, '/client/1/update/'),
'url02b': ("{% url 'template_tests.views.client_action' id=client.id action='update' %}", {'client': {'id': 1}}, '/url_tag/client/1/update/'), 'url02b': ("{% url 'template_tests.views.client_action' id=client.id action='update' %}", {'client': {'id': 1}}, '/client/1/update/'),
'url02c': ("{% url 'template_tests.views.client_action' client.id 'update' %}", {'client': {'id': 1}}, '/url_tag/client/1/update/'), 'url02c': ("{% url 'template_tests.views.client_action' client.id 'update' %}", {'client': {'id': 1}}, '/client/1/update/'),
'url03': ('{% url "template_tests.views.index" %}', {}, '/url_tag/'), 'url03': ('{% url "template_tests.views.index" %}', {}, '/'),
'url04': ('{% url "named.client" client.id %}', {'client': {'id': 1}}, '/url_tag/named-client/1/'), 'url04': ('{% url "named.client" client.id %}', {'client': {'id': 1}}, '/named-client/1/'),
'url05': ('{% url "метка_оператора" v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'), 'url05': ('{% url "метка_оператора" v %}', {'v': 'Ω'}, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
'url06': ('{% url "метка_оператора_2" tag=v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'), 'url06': ('{% url "метка_оператора_2" tag=v %}', {'v': 'Ω'}, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
'url07': ('{% url "template_tests.views.client2" tag=v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'), 'url07': ('{% url "template_tests.views.client2" tag=v %}', {'v': 'Ω'}, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
'url08': ('{% url "метка_оператора" v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'), 'url08': ('{% url "метка_оператора" v %}', {'v': 'Ω'}, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
'url09': ('{% url "метка_оператора_2" tag=v %}', {'v': 'Ω'}, '/url_tag/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'), 'url09': ('{% url "метка_оператора_2" tag=v %}', {'v': 'Ω'}, '/%D0%AE%D0%BD%D0%B8%D0%BA%D0%BE%D0%B4/%CE%A9/'),
'url10': ('{% url "template_tests.views.client_action" id=client.id action="two words" %}', {'client': {'id': 1}}, '/url_tag/client/1/two%20words/'), 'url10': ('{% url "template_tests.views.client_action" id=client.id action="two words" %}', {'client': {'id': 1}}, '/client/1/two%20words/'),
'url11': ('{% url "template_tests.views.client_action" id=client.id action="==" %}', {'client': {'id': 1}}, '/url_tag/client/1/%3D%3D/'), 'url11': ('{% url "template_tests.views.client_action" id=client.id action="==" %}', {'client': {'id': 1}}, '/client/1/%3D%3D/'),
'url12': ('{% url "template_tests.views.client_action" id=client.id action="," %}', {'client': {'id': 1}}, '/url_tag/client/1/%2C/'), 'url12': ('{% url "template_tests.views.client_action" id=client.id action="," %}', {'client': {'id': 1}}, '/client/1/%2C/'),
'url13': ('{% url "template_tests.views.client_action" id=client.id action=arg|join:"-" %}', {'client': {'id': 1}, 'arg': ['a', 'b']}, '/url_tag/client/1/a-b/'), 'url13': ('{% url "template_tests.views.client_action" id=client.id action=arg|join:"-" %}', {'client': {'id': 1}, 'arg': ['a', 'b']}, '/client/1/a-b/'),
'url14': ('{% url "template_tests.views.client_action" client.id arg|join:"-" %}', {'client': {'id': 1}, 'arg': ['a', 'b']}, '/url_tag/client/1/a-b/'), 'url14': ('{% url "template_tests.views.client_action" client.id arg|join:"-" %}', {'client': {'id': 1}, 'arg': ['a', 'b']}, '/client/1/a-b/'),
'url15': ('{% url "template_tests.views.client_action" 12 "test" %}', {}, '/url_tag/client/12/test/'), 'url15': ('{% url "template_tests.views.client_action" 12 "test" %}', {}, '/client/12/test/'),
'url18': ('{% url "template_tests.views.client" "1,2" %}', {}, '/url_tag/client/1%2C2/'), 'url18': ('{% url "template_tests.views.client" "1,2" %}', {}, '/client/1%2C2/'),
'url19': ('{% url named_url client.id %}', {'named_url': 'template_tests.views.client', 'client': {'id': 1}}, '/url_tag/client/1/'), 'url19': ('{% url named_url client.id %}', {'named_url': 'template_tests.views.client', 'client': {'id': 1}}, '/client/1/'),
'url20': ('{% url url_name_in_var client.id %}', {'url_name_in_var': 'named.client', 'client': {'id': 1}}, '/url_tag/named-client/1/'), 'url20': ('{% url url_name_in_var client.id %}', {'url_name_in_var': 'named.client', 'client': {'id': 1}}, '/named-client/1/'),
# Failures # Failures
'url-fail01': ('{% url %}', {}, template.TemplateSyntaxError), 'url-fail01': ('{% url %}', {}, template.TemplateSyntaxError),
@ -1747,7 +1749,7 @@ class TemplateTests(TransRealMixin, TestCase):
# {% url ... as var %} # {% url ... as var %}
'url-asvar01': ('{% url "template_tests.views.index" as url %}', {}, ''), 'url-asvar01': ('{% url "template_tests.views.index" as url %}', {}, ''),
'url-asvar02': ('{% url "template_tests.views.index" as url %}{{ url }}', {}, '/url_tag/'), 'url-asvar02': ('{% url "template_tests.views.index" as url %}{{ url }}', {}, '/'),
'url-asvar03': ('{% url "no_such_view" as url %}{{ url }}', {}, ''), 'url-asvar03': ('{% url "no_such_view" as url %}{{ url }}', {}, ''),
### CACHE TAG ###################################################### ### CACHE TAG ######################################################

View File

@ -32,13 +32,14 @@ from .views import get_view
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class ClientTest(TestCase): class ClientTest(TestCase):
fixtures = ['testdata.json'] fixtures = ['testdata.json']
urls = 'test_client.urls'
def test_get_view(self): def test_get_view(self):
"GET a view" "GET a view"
# The data is ignored, but let's check it doesn't crash the system # The data is ignored, but let's check it doesn't crash the system
# anyway. # anyway.
data = {'var': '\xf2'} data = {'var': '\xf2'}
response = self.client.get('/test_client/get_view/', data) response = self.client.get('/get_view/', data)
# Check some response details # Check some response details
self.assertContains(response, 'This is a test') self.assertContains(response, 'This is a test')
@ -47,7 +48,7 @@ class ClientTest(TestCase):
def test_get_post_view(self): def test_get_post_view(self):
"GET a view that normally expects POSTs" "GET a view that normally expects POSTs"
response = self.client.get('/test_client/post_view/', {}) response = self.client.get('/post_view/', {})
# Check some response details # Check some response details
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -57,7 +58,7 @@ class ClientTest(TestCase):
def test_empty_post(self): def test_empty_post(self):
"POST an empty dictionary to a view" "POST an empty dictionary to a view"
response = self.client.post('/test_client/post_view/', {}) response = self.client.post('/post_view/', {})
# Check some response details # Check some response details
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -70,7 +71,7 @@ class ClientTest(TestCase):
post_data = { post_data = {
'value': 37 'value': 37
} }
response = self.client.post('/test_client/post_view/', post_data) response = self.client.post('/post_view/', post_data)
# Check some response details # Check some response details
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -80,7 +81,7 @@ class ClientTest(TestCase):
def test_response_headers(self): def test_response_headers(self):
"Check the value of HTTP headers returned in a response" "Check the value of HTTP headers returned in a response"
response = self.client.get("/test_client/header_view/") response = self.client.get("/header_view/")
self.assertEqual(response['X-DJANGO-TEST'], 'Slartibartfast') self.assertEqual(response['X-DJANGO-TEST'], 'Slartibartfast')
@ -90,7 +91,7 @@ class ClientTest(TestCase):
originating environ dict and a ``wsgi_request`` with the originating originating environ dict and a ``wsgi_request`` with the originating
``WSGIRequest`` instance. ``WSGIRequest`` instance.
""" """
response = self.client.get("/test_client/header_view/") response = self.client.get("/header_view/")
self.assertTrue(hasattr(response, 'request')) self.assertTrue(hasattr(response, 'request'))
self.assertTrue(hasattr(response, 'wsgi_request')) self.assertTrue(hasattr(response, 'wsgi_request'))
@ -101,7 +102,7 @@ class ClientTest(TestCase):
def test_raw_post(self): def test_raw_post(self):
"POST raw data (with a content type) to a view" "POST raw data (with a content type) to a view"
test_doc = """<?xml version="1.0" encoding="utf-8"?><library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>""" test_doc = """<?xml version="1.0" encoding="utf-8"?><library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>"""
response = self.client.post("/test_client/raw_post_view/", test_doc, response = self.client.post("/raw_post_view/", test_doc,
content_type="text/xml") content_type="text/xml")
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.templates[0].name, "Book template") self.assertEqual(response.templates[0].name, "Book template")
@ -109,81 +110,81 @@ class ClientTest(TestCase):
def test_insecure(self): def test_insecure(self):
"GET a URL through http" "GET a URL through http"
response = self.client.get('/test_client/secure_view/', secure=False) response = self.client.get('/secure_view/', secure=False)
self.assertFalse(response.test_was_secure_request) self.assertFalse(response.test_was_secure_request)
self.assertEqual(response.test_server_port, '80') self.assertEqual(response.test_server_port, '80')
def test_secure(self): def test_secure(self):
"GET a URL through https" "GET a URL through https"
response = self.client.get('/test_client/secure_view/', secure=True) response = self.client.get('/secure_view/', secure=True)
self.assertTrue(response.test_was_secure_request) self.assertTrue(response.test_was_secure_request)
self.assertEqual(response.test_server_port, '443') self.assertEqual(response.test_server_port, '443')
def test_redirect(self): def test_redirect(self):
"GET a URL that redirects elsewhere" "GET a URL that redirects elsewhere"
response = self.client.get('/test_client/redirect_view/') response = self.client.get('/redirect_view/')
# Check that the response was a 302 (redirect) and that # Check that the response was a 302 (redirect) and that
# assertRedirect() understands to put an implicit http://testserver/ in # assertRedirect() understands to put an implicit http://testserver/ in
# front of non-absolute URLs. # front of non-absolute URLs.
self.assertRedirects(response, '/test_client/get_view/') self.assertRedirects(response, '/get_view/')
host = 'django.testserver' host = 'django.testserver'
client_providing_host = Client(HTTP_HOST=host) client_providing_host = Client(HTTP_HOST=host)
response = client_providing_host.get('/test_client/redirect_view/') response = client_providing_host.get('/redirect_view/')
# Check that the response was a 302 (redirect) with absolute URI # Check that the response was a 302 (redirect) with absolute URI
self.assertRedirects(response, '/test_client/get_view/', host=host) self.assertRedirects(response, '/get_view/', host=host)
def test_redirect_with_query(self): def test_redirect_with_query(self):
"GET a URL that redirects with given GET parameters" "GET a URL that redirects with given GET parameters"
response = self.client.get('/test_client/redirect_view/', {'var': 'value'}) response = self.client.get('/redirect_view/', {'var': 'value'})
# Check if parameters are intact # Check if parameters are intact
self.assertRedirects(response, 'http://testserver/test_client/get_view/?var=value') self.assertRedirects(response, 'http://testserver/get_view/?var=value')
def test_permanent_redirect(self): def test_permanent_redirect(self):
"GET a URL that redirects permanently elsewhere" "GET a URL that redirects permanently elsewhere"
response = self.client.get('/test_client/permanent_redirect_view/') response = self.client.get('/permanent_redirect_view/')
# Check that the response was a 301 (permanent redirect) # Check that the response was a 301 (permanent redirect)
self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=301) self.assertRedirects(response, 'http://testserver/get_view/', status_code=301)
client_providing_host = Client(HTTP_HOST='django.testserver') client_providing_host = Client(HTTP_HOST='django.testserver')
response = client_providing_host.get('/test_client/permanent_redirect_view/') response = client_providing_host.get('/permanent_redirect_view/')
# Check that the response was a 301 (permanent redirect) with absolute URI # Check that the response was a 301 (permanent redirect) with absolute URI
self.assertRedirects(response, 'http://django.testserver/test_client/get_view/', status_code=301) self.assertRedirects(response, 'http://django.testserver/get_view/', status_code=301)
def test_temporary_redirect(self): def test_temporary_redirect(self):
"GET a URL that does a non-permanent redirect" "GET a URL that does a non-permanent redirect"
response = self.client.get('/test_client/temporary_redirect_view/') response = self.client.get('/temporary_redirect_view/')
# Check that the response was a 302 (non-permanent redirect) # Check that the response was a 302 (non-permanent redirect)
self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302) self.assertRedirects(response, 'http://testserver/get_view/', status_code=302)
def test_redirect_to_strange_location(self): def test_redirect_to_strange_location(self):
"GET a URL that redirects to a non-200 page" "GET a URL that redirects to a non-200 page"
response = self.client.get('/test_client/double_redirect_view/') response = self.client.get('/double_redirect_view/')
# Check that the response was a 302, and that # Check that the response was a 302, and that
# the attempt to get the redirection location returned 301 when retrieved # the attempt to get the redirection location returned 301 when retrieved
self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', target_status_code=301) self.assertRedirects(response, 'http://testserver/permanent_redirect_view/', target_status_code=301)
def test_follow_redirect(self): def test_follow_redirect(self):
"A URL that redirects can be followed to termination." "A URL that redirects can be followed to termination."
response = self.client.get('/test_client/double_redirect_view/', follow=True) response = self.client.get('/double_redirect_view/', follow=True)
self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302, target_status_code=200) self.assertRedirects(response, 'http://testserver/get_view/', status_code=302, target_status_code=200)
self.assertEqual(len(response.redirect_chain), 2) self.assertEqual(len(response.redirect_chain), 2)
def test_redirect_http(self): def test_redirect_http(self):
"GET a URL that redirects to an http URI" "GET a URL that redirects to an http URI"
response = self.client.get('/test_client/http_redirect_view/', follow=True) response = self.client.get('/http_redirect_view/', follow=True)
self.assertFalse(response.test_was_secure_request) self.assertFalse(response.test_was_secure_request)
def test_redirect_https(self): def test_redirect_https(self):
"GET a URL that redirects to an https URI" "GET a URL that redirects to an https URI"
response = self.client.get('/test_client/https_redirect_view/', follow=True) response = self.client.get('/https_redirect_view/', follow=True)
self.assertTrue(response.test_was_secure_request) self.assertTrue(response.test_was_secure_request)
def test_notfound_response(self): def test_notfound_response(self):
"GET a URL that responds as '404:Not Found'" "GET a URL that responds as '404:Not Found'"
response = self.client.get('/test_client/bad_view/') response = self.client.get('/bad_view/')
# Check that the response was a 404, and that the content contains MAGIC # Check that the response was a 404, and that the content contains MAGIC
self.assertContains(response, 'MAGIC', status_code=404) self.assertContains(response, 'MAGIC', status_code=404)
@ -197,7 +198,7 @@ class ClientTest(TestCase):
'single': 'b', 'single': 'b',
'multi': ('b', 'c', 'e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Valid POST Template") self.assertTemplateUsed(response, "Valid POST Template")
@ -207,7 +208,7 @@ class ClientTest(TestCase):
'text': 'Hello World', 'text': 'Hello World',
'multi': ('b', 'c', 'e') 'multi': ('b', 'c', 'e')
} }
response = self.client.get('/test_client/form_view/', data=hints) response = self.client.get('/form_view/', data=hints)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Form GET Template") self.assertTemplateUsed(response, "Form GET Template")
# Check that the multi-value data has been rolled out ok # Check that the multi-value data has been rolled out ok
@ -219,7 +220,7 @@ class ClientTest(TestCase):
'text': 'Hello World', 'text': 'Hello World',
'value': 37 'value': 37
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/form_view/', post_data)
self.assertContains(response, 'This field is required.', 3) self.assertContains(response, 'This field is required.', 3)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Invalid POST Template") self.assertTemplateUsed(response, "Invalid POST Template")
@ -237,7 +238,7 @@ class ClientTest(TestCase):
'single': 'b', 'single': 'b',
'multi': ('b', 'c', 'e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Invalid POST Template") self.assertTemplateUsed(response, "Invalid POST Template")
@ -252,7 +253,7 @@ class ClientTest(TestCase):
'single': 'b', 'single': 'b',
'multi': ('b', 'c', 'e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view_with_template/', post_data) response = self.client.post('/form_view_with_template/', post_data)
self.assertContains(response, 'POST data OK') self.assertContains(response, 'POST data OK')
self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, "form_view.html")
self.assertTemplateUsed(response, 'base.html') self.assertTemplateUsed(response, 'base.html')
@ -264,7 +265,7 @@ class ClientTest(TestCase):
'text': 'Hello World', 'text': 'Hello World',
'value': 37 'value': 37
} }
response = self.client.post('/test_client/form_view_with_template/', post_data) response = self.client.post('/form_view_with_template/', post_data)
self.assertContains(response, 'POST data has errors') self.assertContains(response, 'POST data has errors')
self.assertTemplateUsed(response, 'form_view.html') self.assertTemplateUsed(response, 'form_view.html')
self.assertTemplateUsed(response, 'base.html') self.assertTemplateUsed(response, 'base.html')
@ -283,7 +284,7 @@ class ClientTest(TestCase):
'single': 'b', 'single': 'b',
'multi': ('b', 'c', 'e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view_with_template/', post_data) response = self.client.post('/form_view_with_template/', post_data)
self.assertContains(response, 'POST data has errors') self.assertContains(response, 'POST data has errors')
self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, "form_view.html")
self.assertTemplateUsed(response, 'base.html') self.assertTemplateUsed(response, 'base.html')
@ -293,31 +294,31 @@ class ClientTest(TestCase):
def test_unknown_page(self): def test_unknown_page(self):
"GET an invalid URL" "GET an invalid URL"
response = self.client.get('/test_client/unknown_view/') response = self.client.get('/unknown_view/')
# Check that the response was a 404 # Check that the response was a 404
self.assertEqual(response.status_code, 404) self.assertEqual(response.status_code, 404)
def test_url_parameters(self): def test_url_parameters(self):
"Make sure that URL ;-parameters are not stripped." "Make sure that URL ;-parameters are not stripped."
response = self.client.get('/test_client/unknown_view/;some-parameter') response = self.client.get('/unknown_view/;some-parameter')
# Check that the path in the response includes it (ignore that it's a 404) # Check that the path in the response includes it (ignore that it's a 404)
self.assertEqual(response.request['PATH_INFO'], '/test_client/unknown_view/;some-parameter') self.assertEqual(response.request['PATH_INFO'], '/unknown_view/;some-parameter')
def test_view_with_login(self): def test_view_with_login(self):
"Request a page that is protected with @login_required" "Request a page that is protected with @login_required"
# Get the page without logging in. Should result in 302. # Get the page without logging in. Should result in 302.
response = self.client.get('/test_client/login_protected_view/') response = self.client.get('/login_protected_view/')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/login_protected_view/')
# Log in # Log in
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Request a page that requires a login # Request a page that requires a login
response = self.client.get('/test_client/login_protected_view/') response = self.client.get('/login_protected_view/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['user'].username, 'testclient') self.assertEqual(response.context['user'].username, 'testclient')
@ -325,15 +326,15 @@ class ClientTest(TestCase):
"Request a page that is protected with a @login_required method" "Request a page that is protected with a @login_required method"
# Get the page without logging in. Should result in 302. # Get the page without logging in. Should result in 302.
response = self.client.get('/test_client/login_protected_method_view/') response = self.client.get('/login_protected_method_view/')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_method_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/login_protected_method_view/')
# Log in # Log in
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Request a page that requires a login # Request a page that requires a login
response = self.client.get('/test_client/login_protected_method_view/') response = self.client.get('/login_protected_method_view/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['user'].username, 'testclient') self.assertEqual(response.context['user'].username, 'testclient')
@ -341,15 +342,15 @@ class ClientTest(TestCase):
"Request a page that is protected with @login_required(redirect_field_name='redirect_to')" "Request a page that is protected with @login_required(redirect_field_name='redirect_to')"
# Get the page without logging in. Should result in 302. # Get the page without logging in. Should result in 302.
response = self.client.get('/test_client/login_protected_view_custom_redirect/') response = self.client.get('/login_protected_view_custom_redirect/')
self.assertRedirects(response, 'http://testserver/accounts/login/?redirect_to=/test_client/login_protected_view_custom_redirect/') self.assertRedirects(response, 'http://testserver/accounts/login/?redirect_to=/login_protected_view_custom_redirect/')
# Log in # Log in
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Request a page that requires a login # Request a page that requires a login
response = self.client.get('/test_client/login_protected_view_custom_redirect/') response = self.client.get('/login_protected_view_custom_redirect/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['user'].username, 'testclient') self.assertEqual(response.context['user'].username, 'testclient')
@ -371,7 +372,7 @@ class ClientTest(TestCase):
self.client.login(username='testclient', password='password') self.client.login(username='testclient', password='password')
# Request a page that requires a login # Request a page that requires a login
response = self.client.get('/test_client/login_protected_view/') response = self.client.get('/login_protected_view/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['user'].username, 'testclient') self.assertEqual(response.context['user'].username, 'testclient')
@ -379,8 +380,8 @@ class ClientTest(TestCase):
self.client.logout() self.client.logout()
# Request a page that requires a login # Request a page that requires a login
response = self.client.get('/test_client/login_protected_view/') response = self.client.get('/login_protected_view/')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/login_protected_view/')
@override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies") @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies")
def test_logout_cookie_sessions(self): def test_logout_cookie_sessions(self):
@ -390,16 +391,16 @@ class ClientTest(TestCase):
"Request a page that is protected with @permission_required" "Request a page that is protected with @permission_required"
# Get the page without logging in. Should result in 302. # Get the page without logging in. Should result in 302.
response = self.client.get('/test_client/permission_protected_view/') response = self.client.get('/permission_protected_view/')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/permission_protected_view/')
# Log in # Log in
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Log in with wrong permissions. Should result in 302. # Log in with wrong permissions. Should result in 302.
response = self.client.get('/test_client/permission_protected_view/') response = self.client.get('/permission_protected_view/')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/permission_protected_view/')
# TODO: Log in with right permissions and request the page again # TODO: Log in with right permissions and request the page again
@ -407,7 +408,7 @@ class ClientTest(TestCase):
"Request a page that is protected with @permission_required but raises a exception" "Request a page that is protected with @permission_required but raises a exception"
# Get the page without logging in. Should result in 403. # Get the page without logging in. Should result in 403.
response = self.client.get('/test_client/permission_protected_view_exception/') response = self.client.get('/permission_protected_view_exception/')
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
# Log in # Log in
@ -415,28 +416,28 @@ class ClientTest(TestCase):
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Log in with wrong permissions. Should result in 403. # Log in with wrong permissions. Should result in 403.
response = self.client.get('/test_client/permission_protected_view_exception/') response = self.client.get('/permission_protected_view_exception/')
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
def test_view_with_method_permissions(self): def test_view_with_method_permissions(self):
"Request a page that is protected with a @permission_required method" "Request a page that is protected with a @permission_required method"
# Get the page without logging in. Should result in 302. # Get the page without logging in. Should result in 302.
response = self.client.get('/test_client/permission_protected_method_view/') response = self.client.get('/permission_protected_method_view/')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/permission_protected_method_view/')
# Log in # Log in
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Log in with wrong permissions. Should result in 302. # Log in with wrong permissions. Should result in 302.
response = self.client.get('/test_client/permission_protected_method_view/') response = self.client.get('/permission_protected_method_view/')
self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/') self.assertRedirects(response, 'http://testserver/accounts/login/?next=/permission_protected_method_view/')
# TODO: Log in with right permissions and request the page again # TODO: Log in with right permissions and request the page again
def test_external_redirect(self): def test_external_redirect(self):
response = self.client.get('/test_client/django_project_redirect/') response = self.client.get('/django_project_redirect/')
self.assertRedirects(response, 'https://www.djangoproject.com/', fetch_redirect_response=False) self.assertRedirects(response, 'https://www.djangoproject.com/', fetch_redirect_response=False)
def test_session_modifying_view(self): def test_session_modifying_view(self):
@ -448,18 +449,18 @@ class ClientTest(TestCase):
except KeyError: except KeyError:
pass pass
self.client.post('/test_client/session_view/') self.client.post('/session_view/')
# Check that the session was modified # Check that the session was modified
self.assertEqual(self.client.session['tobacconist'], 'hovercraft') self.assertEqual(self.client.session['tobacconist'], 'hovercraft')
def test_view_with_exception(self): def test_view_with_exception(self):
"Request a page that is known to throw an error" "Request a page that is known to throw an error"
self.assertRaises(KeyError, self.client.get, "/test_client/broken_view/") self.assertRaises(KeyError, self.client.get, "/broken_view/")
# Try the same assertion, a different way # Try the same assertion, a different way
try: try:
self.client.get('/test_client/broken_view/') self.client.get('/broken_view/')
self.fail('Should raise an error') self.fail('Should raise an error')
except KeyError: except KeyError:
pass pass
@ -467,7 +468,7 @@ class ClientTest(TestCase):
def test_mail_sending(self): def test_mail_sending(self):
"Test that mail is redirected to a dummy outbox during test setup" "Test that mail is redirected to a dummy outbox during test setup"
response = self.client.get('/test_client/mail_sending_view/') response = self.client.get('/mail_sending_view/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(len(mail.outbox), 1) self.assertEqual(len(mail.outbox), 1)
@ -480,7 +481,7 @@ class ClientTest(TestCase):
def test_mass_mail_sending(self): def test_mass_mail_sending(self):
"Test that mass mail is redirected to a dummy outbox during test setup" "Test that mass mail is redirected to a dummy outbox during test setup"
response = self.client.get('/test_client/mass_mail_sending_view/') response = self.client.get('/mass_mail_sending_view/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(len(mail.outbox), 2) self.assertEqual(len(mail.outbox), 2)
@ -501,16 +502,18 @@ class ClientTest(TestCase):
MIDDLEWARE_CLASSES=('django.middleware.csrf.CsrfViewMiddleware',) MIDDLEWARE_CLASSES=('django.middleware.csrf.CsrfViewMiddleware',)
) )
class CSRFEnabledClientTests(TestCase): class CSRFEnabledClientTests(TestCase):
urls = 'test_client.urls'
def test_csrf_enabled_client(self): def test_csrf_enabled_client(self):
"A client can be instantiated with CSRF checks enabled" "A client can be instantiated with CSRF checks enabled"
csrf_client = Client(enforce_csrf_checks=True) csrf_client = Client(enforce_csrf_checks=True)
# The normal client allows the post # The normal client allows the post
response = self.client.post('/test_client/post_view/', {}) response = self.client.post('/post_view/', {})
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
# The CSRF-enabled client rejects it # The CSRF-enabled client rejects it
response = csrf_client.post('/test_client/post_view/', {}) response = csrf_client.post('/post_view/', {})
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
@ -527,6 +530,8 @@ class CustomTestClientTest(TestCase):
class RequestFactoryTest(TestCase): class RequestFactoryTest(TestCase):
urls = 'test_client.urls'
def test_request_factory(self): def test_request_factory(self):
factory = RequestFactory() factory = RequestFactory()
request = factory.get('/somewhere/') request = factory.get('/somewhere/')

View File

@ -11,10 +11,10 @@ urlpatterns = patterns('',
(r'^raw_post_view/$', views.raw_post_view), (r'^raw_post_view/$', views.raw_post_view),
(r'^redirect_view/$', views.redirect_view), (r'^redirect_view/$', views.redirect_view),
(r'^secure_view/$', views.view_with_secure), (r'^secure_view/$', views.view_with_secure),
(r'^permanent_redirect_view/$', RedirectView.as_view(url='/test_client/get_view/')), (r'^permanent_redirect_view/$', RedirectView.as_view(url='/get_view/')),
(r'^temporary_redirect_view/$', RedirectView.as_view(url='/test_client/get_view/', permanent=False)), (r'^temporary_redirect_view/$', RedirectView.as_view(url='/get_view/', permanent=False)),
(r'^http_redirect_view/$', RedirectView.as_view(url='/test_client/secure_view/')), (r'^http_redirect_view/$', RedirectView.as_view(url='/secure_view/')),
(r'^https_redirect_view/$', RedirectView.as_view(url='https://testserver/test_client/secure_view/')), (r'^https_redirect_view/$', RedirectView.as_view(url='https://testserver/secure_view/')),
(r'^double_redirect_view/$', views.double_redirect_view), (r'^double_redirect_view/$', views.double_redirect_view),
(r'^bad_view/$', views.bad_view), (r'^bad_view/$', views.bad_view),
(r'^form_view/$', views.form_view), (r'^form_view/$', views.form_view),
@ -31,4 +31,7 @@ urlpatterns = patterns('',
(r'^mail_sending_view/$', views.mail_sending_view), (r'^mail_sending_view/$', views.mail_sending_view),
(r'^mass_mail_sending_view/$', views.mass_mail_sending_view), (r'^mass_mail_sending_view/$', views.mass_mail_sending_view),
(r'^django_project_redirect/$', views.django_project_redirect), (r'^django_project_redirect/$', views.django_project_redirect),
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
) )

View File

@ -67,7 +67,7 @@ def redirect_view(request):
query = '?' + urlencode(request.GET, True) query = '?' + urlencode(request.GET, True)
else: else:
query = '' query = ''
return HttpResponseRedirect('/test_client/get_view/' + query) return HttpResponseRedirect('/get_view/' + query)
def view_with_secure(request): def view_with_secure(request):
@ -80,7 +80,7 @@ def view_with_secure(request):
def double_redirect_view(request): def double_redirect_view(request):
"A view that redirects all requests to a redirection view" "A view that redirects all requests to a redirection view"
return HttpResponseRedirect('/test_client/permanent_redirect_view/') return HttpResponseRedirect('/permanent_redirect_view/')
def bad_view(request): def bad_view(request):

View File

@ -8,7 +8,7 @@ import os
import itertools import itertools
from django.conf import settings from django.conf import settings
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse, NoReverseMatch
from django.template import (TemplateSyntaxError, from django.template import (TemplateSyntaxError,
Context, Template, loader) Context, Template, loader)
import django.template.context import django.template.context
@ -30,9 +30,11 @@ from .views import CustomTestException
TEMPLATE_DIRS=(os.path.join(os.path.dirname(upath(__file__)), 'templates'),) TEMPLATE_DIRS=(os.path.join(os.path.dirname(upath(__file__)), 'templates'),)
) )
class AssertContainsTests(TestCase): class AssertContainsTests(TestCase):
urls = 'test_client_regress.urls'
def test_contains(self): def test_contains(self):
"Responses can be inspected for content, including counting repeated substrings" "Responses can be inspected for content, including counting repeated substrings"
response = self.client.get('/test_client_regress/no_template_view/') response = self.client.get('/no_template_view/')
self.assertNotContains(response, 'never') self.assertNotContains(response, 'never')
self.assertContains(response, 'never', 0) self.assertContains(response, 'never', 0)
@ -125,35 +127,35 @@ class AssertContainsTests(TestCase):
def test_unicode_contains(self): def test_unicode_contains(self):
"Unicode characters can be found in template context" "Unicode characters can be found in template context"
# Regression test for #10183 # Regression test for #10183
r = self.client.get('/test_client_regress/check_unicode/') r = self.client.get('/check_unicode/')
self.assertContains(r, 'さかき') self.assertContains(r, 'さかき')
self.assertContains(r, b'\xe5\xb3\xa0'.decode('utf-8')) self.assertContains(r, b'\xe5\xb3\xa0'.decode('utf-8'))
def test_unicode_not_contains(self): def test_unicode_not_contains(self):
"Unicode characters can be searched for, and not found in template context" "Unicode characters can be searched for, and not found in template context"
# Regression test for #10183 # Regression test for #10183
r = self.client.get('/test_client_regress/check_unicode/') r = self.client.get('/check_unicode/')
self.assertNotContains(r, 'はたけ') self.assertNotContains(r, 'はたけ')
self.assertNotContains(r, b'\xe3\x81\xaf\xe3\x81\x9f\xe3\x81\x91'.decode('utf-8')) self.assertNotContains(r, b'\xe3\x81\xaf\xe3\x81\x9f\xe3\x81\x91'.decode('utf-8'))
def test_binary_contains(self): def test_binary_contains(self):
r = self.client.get('/test_client_regress/check_binary/') r = self.client.get('/check_binary/')
self.assertContains(r, b'%PDF-1.4\r\n%\x93\x8c\x8b\x9e') self.assertContains(r, b'%PDF-1.4\r\n%\x93\x8c\x8b\x9e')
with self.assertRaises(AssertionError): with self.assertRaises(AssertionError):
self.assertContains(r, b'%PDF-1.4\r\n%\x93\x8c\x8b\x9e', count=2) self.assertContains(r, b'%PDF-1.4\r\n%\x93\x8c\x8b\x9e', count=2)
def test_binary_not_contains(self): def test_binary_not_contains(self):
r = self.client.get('/test_client_regress/check_binary/') r = self.client.get('/check_binary/')
self.assertNotContains(r, b'%ODF-1.4\r\n%\x93\x8c\x8b\x9e') self.assertNotContains(r, b'%ODF-1.4\r\n%\x93\x8c\x8b\x9e')
with self.assertRaises(AssertionError): with self.assertRaises(AssertionError):
self.assertNotContains(r, b'%PDF-1.4\r\n%\x93\x8c\x8b\x9e') self.assertNotContains(r, b'%PDF-1.4\r\n%\x93\x8c\x8b\x9e')
def test_nontext_contains(self): def test_nontext_contains(self):
r = self.client.get('/test_client_regress/no_template_view/') r = self.client.get('/no_template_view/')
self.assertContains(r, ugettext_lazy('once')) self.assertContains(r, ugettext_lazy('once'))
def test_nontext_not_contains(self): def test_nontext_not_contains(self):
r = self.client.get('/test_client_regress/no_template_view/') r = self.client.get('/no_template_view/')
self.assertNotContains(r, ugettext_lazy('never')) self.assertNotContains(r, ugettext_lazy('never'))
def test_assert_contains_renders_template_response(self): def test_assert_contains_renders_template_response(self):
@ -191,11 +193,12 @@ class AssertContainsTests(TestCase):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class AssertTemplateUsedTests(TestCase): class AssertTemplateUsedTests(TestCase):
urls = 'test_client_regress.urls'
fixtures = ['testdata.json'] fixtures = ['testdata.json']
def test_no_context(self): def test_no_context(self):
"Template usage assertions work then templates aren't in use" "Template usage assertions work then templates aren't in use"
response = self.client.get('/test_client_regress/no_template_view/') response = self.client.get('/no_template_view/')
# Check that the no template case doesn't mess with the template assertions # Check that the no template case doesn't mess with the template assertions
self.assertTemplateNotUsed(response, 'GET Template') self.assertTemplateNotUsed(response, 'GET Template')
@ -212,7 +215,7 @@ class AssertTemplateUsedTests(TestCase):
def test_single_context(self): def test_single_context(self):
"Template assertions work when there is a single context" "Template assertions work when there is a single context"
response = self.client.get('/test_client/post_view/', {}) response = self.client.get('/post_view/', {})
try: try:
self.assertTemplateNotUsed(response, 'Empty GET Template') self.assertTemplateNotUsed(response, 'Empty GET Template')
@ -243,7 +246,7 @@ class AssertTemplateUsedTests(TestCase):
'single': 'b', 'single': 'b',
'multi': ('b', 'c', 'e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view_with_template/', post_data) response = self.client.post('/form_view_with_template/', post_data)
self.assertContains(response, 'POST data OK') self.assertContains(response, 'POST data OK')
try: try:
self.assertTemplateNotUsed(response, "form_view.html") self.assertTemplateNotUsed(response, "form_view.html")
@ -262,144 +265,146 @@ class AssertTemplateUsedTests(TestCase):
class AssertRedirectsTests(TestCase): class AssertRedirectsTests(TestCase):
urls = 'test_client_regress.urls'
def test_redirect_page(self): def test_redirect_page(self):
"An assertion is raised if the original page couldn't be retrieved as expected" "An assertion is raised if the original page couldn't be retrieved as expected"
# This page will redirect with code 301, not 302 # This page will redirect with code 301, not 302
response = self.client.get('/test_client/permanent_redirect_view/') response = self.client.get('/permanent_redirect_view/')
try: try:
self.assertRedirects(response, '/test_client/get_view/') self.assertRedirects(response, '/get_view/')
except AssertionError as e: except AssertionError as e:
self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
try: try:
self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') self.assertRedirects(response, '/get_view/', msg_prefix='abc')
except AssertionError as e: except AssertionError as e:
self.assertIn("abc: Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) self.assertIn("abc: Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
def test_lost_query(self): def test_lost_query(self):
"An assertion is raised if the redirect location doesn't preserve GET parameters" "An assertion is raised if the redirect location doesn't preserve GET parameters"
response = self.client.get('/test_client/redirect_view/', {'var': 'value'}) response = self.client.get('/redirect_view/', {'var': 'value'})
try: try:
self.assertRedirects(response, '/test_client/get_view/') self.assertRedirects(response, '/get_view/')
except AssertionError as e: except AssertionError as e:
self.assertIn("Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e)) self.assertIn("Response redirected to 'http://testserver/get_view/?var=value', expected 'http://testserver/get_view/'", str(e))
try: try:
self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') self.assertRedirects(response, '/get_view/', msg_prefix='abc')
except AssertionError as e: except AssertionError as e:
self.assertIn("abc: Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e)) self.assertIn("abc: Response redirected to 'http://testserver/get_view/?var=value', expected 'http://testserver/get_view/'", str(e))
def test_incorrect_target(self): def test_incorrect_target(self):
"An assertion is raised if the response redirects to another target" "An assertion is raised if the response redirects to another target"
response = self.client.get('/test_client/permanent_redirect_view/') response = self.client.get('/permanent_redirect_view/')
try: try:
# Should redirect to get_view # Should redirect to get_view
self.assertRedirects(response, '/test_client/some_view/') self.assertRedirects(response, '/some_view/')
except AssertionError as e: except AssertionError as e:
self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e)) self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
def test_target_page(self): def test_target_page(self):
"An assertion is raised if the response redirect target cannot be retrieved as expected" "An assertion is raised if the response redirect target cannot be retrieved as expected"
response = self.client.get('/test_client/double_redirect_view/') response = self.client.get('/double_redirect_view/')
try: try:
# The redirect target responds with a 301 code, not 200 # The redirect target responds with a 301 code, not 200
self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/') self.assertRedirects(response, 'http://testserver/permanent_redirect_view/')
except AssertionError as e: except AssertionError as e:
self.assertIn("Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e)) self.assertIn("Couldn't retrieve redirection page '/permanent_redirect_view/': response code was 301 (expected 200)", str(e))
try: try:
# The redirect target responds with a 301 code, not 200 # The redirect target responds with a 301 code, not 200
self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', msg_prefix='abc') self.assertRedirects(response, 'http://testserver/permanent_redirect_view/', msg_prefix='abc')
except AssertionError as e: except AssertionError as e:
self.assertIn("abc: Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e)) self.assertIn("abc: Couldn't retrieve redirection page '/permanent_redirect_view/': response code was 301 (expected 200)", str(e))
def test_redirect_chain(self): def test_redirect_chain(self):
"You can follow a redirect chain of multiple redirects" "You can follow a redirect chain of multiple redirects"
response = self.client.get('/test_client_regress/redirects/further/more/', {}, follow=True) response = self.client.get('/redirects/further/more/', {}, follow=True)
self.assertRedirects(response, '/test_client_regress/no_template_view/', self.assertRedirects(response, '/no_template_view/',
status_code=301, target_status_code=200) status_code=301, target_status_code=200)
self.assertEqual(len(response.redirect_chain), 1) self.assertEqual(len(response.redirect_chain), 1)
self.assertEqual(response.redirect_chain[0], ('http://testserver/test_client_regress/no_template_view/', 301)) self.assertEqual(response.redirect_chain[0], ('http://testserver/no_template_view/', 301))
def test_multiple_redirect_chain(self): def test_multiple_redirect_chain(self):
"You can follow a redirect chain of multiple redirects" "You can follow a redirect chain of multiple redirects"
response = self.client.get('/test_client_regress/redirects/', {}, follow=True) response = self.client.get('/redirects/', {}, follow=True)
self.assertRedirects(response, '/test_client_regress/no_template_view/', self.assertRedirects(response, '/no_template_view/',
status_code=301, target_status_code=200) status_code=301, target_status_code=200)
self.assertEqual(len(response.redirect_chain), 3) self.assertEqual(len(response.redirect_chain), 3)
self.assertEqual(response.redirect_chain[0], ('http://testserver/test_client_regress/redirects/further/', 301)) self.assertEqual(response.redirect_chain[0], ('http://testserver/redirects/further/', 301))
self.assertEqual(response.redirect_chain[1], ('http://testserver/test_client_regress/redirects/further/more/', 301)) self.assertEqual(response.redirect_chain[1], ('http://testserver/redirects/further/more/', 301))
self.assertEqual(response.redirect_chain[2], ('http://testserver/test_client_regress/no_template_view/', 301)) self.assertEqual(response.redirect_chain[2], ('http://testserver/no_template_view/', 301))
def test_redirect_chain_to_non_existent(self): def test_redirect_chain_to_non_existent(self):
"You can follow a chain to a non-existent view" "You can follow a chain to a non-existent view"
response = self.client.get('/test_client_regress/redirect_to_non_existent_view2/', {}, follow=True) response = self.client.get('/redirect_to_non_existent_view2/', {}, follow=True)
self.assertRedirects(response, '/test_client_regress/non_existent_view/', self.assertRedirects(response, '/non_existent_view/',
status_code=301, target_status_code=404) status_code=301, target_status_code=404)
def test_redirect_chain_to_self(self): def test_redirect_chain_to_self(self):
"Redirections to self are caught and escaped" "Redirections to self are caught and escaped"
response = self.client.get('/test_client_regress/redirect_to_self/', {}, follow=True) response = self.client.get('/redirect_to_self/', {}, follow=True)
# The chain of redirects stops once the cycle is detected. # The chain of redirects stops once the cycle is detected.
self.assertRedirects(response, '/test_client_regress/redirect_to_self/', self.assertRedirects(response, '/redirect_to_self/',
status_code=301, target_status_code=301) status_code=301, target_status_code=301)
self.assertEqual(len(response.redirect_chain), 2) self.assertEqual(len(response.redirect_chain), 2)
def test_circular_redirect(self): def test_circular_redirect(self):
"Circular redirect chains are caught and escaped" "Circular redirect chains are caught and escaped"
response = self.client.get('/test_client_regress/circular_redirect_1/', {}, follow=True) response = self.client.get('/circular_redirect_1/', {}, follow=True)
# The chain of redirects will get back to the starting point, but stop there. # The chain of redirects will get back to the starting point, but stop there.
self.assertRedirects(response, '/test_client_regress/circular_redirect_2/', self.assertRedirects(response, '/circular_redirect_2/',
status_code=301, target_status_code=301) status_code=301, target_status_code=301)
self.assertEqual(len(response.redirect_chain), 4) self.assertEqual(len(response.redirect_chain), 4)
def test_redirect_chain_post(self): def test_redirect_chain_post(self):
"A redirect chain will be followed from an initial POST post" "A redirect chain will be followed from an initial POST post"
response = self.client.post('/test_client_regress/redirects/', response = self.client.post('/redirects/',
{'nothing': 'to_send'}, follow=True) {'nothing': 'to_send'}, follow=True)
self.assertRedirects(response, self.assertRedirects(response,
'/test_client_regress/no_template_view/', 301, 200) '/no_template_view/', 301, 200)
self.assertEqual(len(response.redirect_chain), 3) self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_head(self): def test_redirect_chain_head(self):
"A redirect chain will be followed from an initial HEAD request" "A redirect chain will be followed from an initial HEAD request"
response = self.client.head('/test_client_regress/redirects/', response = self.client.head('/redirects/',
{'nothing': 'to_send'}, follow=True) {'nothing': 'to_send'}, follow=True)
self.assertRedirects(response, self.assertRedirects(response,
'/test_client_regress/no_template_view/', 301, 200) '/no_template_view/', 301, 200)
self.assertEqual(len(response.redirect_chain), 3) self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_options(self): def test_redirect_chain_options(self):
"A redirect chain will be followed from an initial OPTIONS request" "A redirect chain will be followed from an initial OPTIONS request"
response = self.client.options('/test_client_regress/redirects/', response = self.client.options('/redirects/',
follow=True) follow=True)
self.assertRedirects(response, self.assertRedirects(response,
'/test_client_regress/no_template_view/', 301, 200) '/no_template_view/', 301, 200)
self.assertEqual(len(response.redirect_chain), 3) self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_put(self): def test_redirect_chain_put(self):
"A redirect chain will be followed from an initial PUT request" "A redirect chain will be followed from an initial PUT request"
response = self.client.put('/test_client_regress/redirects/', response = self.client.put('/redirects/',
follow=True) follow=True)
self.assertRedirects(response, self.assertRedirects(response,
'/test_client_regress/no_template_view/', 301, 200) '/no_template_view/', 301, 200)
self.assertEqual(len(response.redirect_chain), 3) self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_delete(self): def test_redirect_chain_delete(self):
"A redirect chain will be followed from an initial DELETE request" "A redirect chain will be followed from an initial DELETE request"
response = self.client.delete('/test_client_regress/redirects/', response = self.client.delete('/redirects/',
follow=True) follow=True)
self.assertRedirects(response, self.assertRedirects(response,
'/test_client_regress/no_template_view/', 301, 200) '/no_template_view/', 301, 200)
self.assertEqual(len(response.redirect_chain), 3) self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_to_different_host(self): def test_redirect_to_different_host(self):
"The test client will preserve scheme, host and port changes" "The test client will preserve scheme, host and port changes"
response = self.client.get('/test_client_regress/redirect_other_host/', follow=True) response = self.client.get('/redirect_other_host/', follow=True)
self.assertRedirects(response, self.assertRedirects(response,
'https://otherserver:8443/test_client_regress/no_template_view/', 'https://otherserver:8443/no_template_view/',
status_code=301, target_status_code=200) status_code=301, target_status_code=200)
# We can't use is_secure() or get_host() # We can't use is_secure() or get_host()
# because response.request is a dictionary, not an HttpRequest # because response.request is a dictionary, not an HttpRequest
@ -410,28 +415,28 @@ class AssertRedirectsTests(TestCase):
def test_redirect_chain_on_non_redirect_page(self): def test_redirect_chain_on_non_redirect_page(self):
"An assertion is raised if the original page couldn't be retrieved as expected" "An assertion is raised if the original page couldn't be retrieved as expected"
# This page will redirect with code 301, not 302 # This page will redirect with code 301, not 302
response = self.client.get('/test_client/get_view/', follow=True) response = self.client.get('/get_view/', follow=True)
try: try:
self.assertRedirects(response, '/test_client/get_view/') self.assertRedirects(response, '/get_view/')
except AssertionError as e: except AssertionError as e:
self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
try: try:
self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') self.assertRedirects(response, '/get_view/', msg_prefix='abc')
except AssertionError as e: except AssertionError as e:
self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
def test_redirect_on_non_redirect_page(self): def test_redirect_on_non_redirect_page(self):
"An assertion is raised if the original page couldn't be retrieved as expected" "An assertion is raised if the original page couldn't be retrieved as expected"
# This page will redirect with code 301, not 302 # This page will redirect with code 301, not 302
response = self.client.get('/test_client/get_view/') response = self.client.get('/get_view/')
try: try:
self.assertRedirects(response, '/test_client/get_view/') self.assertRedirects(response, '/get_view/')
except AssertionError as e: except AssertionError as e:
self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
try: try:
self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc') self.assertRedirects(response, '/get_view/', msg_prefix='abc')
except AssertionError as e: except AssertionError as e:
self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e)) self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
@ -439,22 +444,24 @@ class AssertRedirectsTests(TestCase):
"An assertion is raised if the response doesn't have the scheme specified in expected_url" "An assertion is raised if the response doesn't have the scheme specified in expected_url"
# Assure that original request scheme is preserved if no scheme specified in the redirect location # Assure that original request scheme is preserved if no scheme specified in the redirect location
response = self.client.get('/test_client/redirect_view/', secure=True) response = self.client.get('/redirect_view/', secure=True)
self.assertRedirects(response, 'https://testserver/test_client/get_view/') self.assertRedirects(response, 'https://testserver/get_view/')
# For all possible True/False combinations of follow and secure # For all possible True/False combinations of follow and secure
for follow, secure in itertools.product([True, False], repeat=2): for follow, secure in itertools.product([True, False], repeat=2):
# always redirects to https # always redirects to https
response = self.client.get('/test_client/https_redirect_view/', follow=follow, secure=secure) response = self.client.get('/https_redirect_view/', follow=follow, secure=secure)
# no scheme to compare too, always succeeds # no scheme to compare too, always succeeds
self.assertRedirects(response, '/test_client/secure_view/', status_code=301) self.assertRedirects(response, '/secure_view/', status_code=301)
# the goal scheme is https # the goal scheme is https
self.assertRedirects(response, 'https://testserver/test_client/secure_view/', status_code=301) self.assertRedirects(response, 'https://testserver/secure_view/', status_code=301)
with self.assertRaises(AssertionError): with self.assertRaises(AssertionError):
self.assertRedirects(response, 'http://testserver/test_client/secure_view/', status_code=301) self.assertRedirects(response, 'http://testserver/secure_view/', status_code=301)
class AssertFormErrorTests(TestCase): class AssertFormErrorTests(TestCase):
urls = 'test_client_regress.urls'
def test_unknown_form(self): def test_unknown_form(self):
"An assertion is raised if the form name is unknown" "An assertion is raised if the form name is unknown"
post_data = { post_data = {
@ -464,7 +471,7 @@ class AssertFormErrorTests(TestCase):
'single': 'b', 'single': 'b',
'multi': ('b', 'c', 'e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Invalid POST Template") self.assertTemplateUsed(response, "Invalid POST Template")
@ -486,7 +493,7 @@ class AssertFormErrorTests(TestCase):
'single': 'b', 'single': 'b',
'multi': ('b', 'c', 'e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Invalid POST Template") self.assertTemplateUsed(response, "Invalid POST Template")
@ -508,7 +515,7 @@ class AssertFormErrorTests(TestCase):
'single': 'b', 'single': 'b',
'multi': ('b', 'c', 'e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Invalid POST Template") self.assertTemplateUsed(response, "Invalid POST Template")
@ -530,7 +537,7 @@ class AssertFormErrorTests(TestCase):
'single': 'b', 'single': 'b',
'multi': ('b', 'c', 'e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Invalid POST Template") self.assertTemplateUsed(response, "Invalid POST Template")
@ -555,7 +562,7 @@ class AssertFormErrorTests(TestCase):
'single': 'b', 'single': 'b',
'multi': ('b', 'c', 'e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Invalid POST Template") self.assertTemplateUsed(response, "Invalid POST Template")
@ -570,6 +577,7 @@ class AssertFormErrorTests(TestCase):
class AssertFormsetErrorTests(TestCase): class AssertFormsetErrorTests(TestCase):
urls = 'test_client_regress.urls'
msg_prefixes = [("", {}), ("abc: ", {"msg_prefix": "abc"})] msg_prefixes = [("", {}), ("abc: ", {"msg_prefix": "abc"})]
def setUp(self): def setUp(self):
@ -606,7 +614,7 @@ class AssertFormsetErrorTests(TestCase):
}) })
def getResponse(self, post_data): def getResponse(self, post_data):
response = self.client.post('/test_client/formset_view/', post_data) response = self.client.post('/formset_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Invalid POST Template") self.assertTemplateUsed(response, "Invalid POST Template")
return response return response
@ -769,6 +777,7 @@ class ProcessedMiddleware(object):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class LoginTests(TestCase): class LoginTests(TestCase):
urls = 'test_client_regress.urls'
fixtures = ['testdata'] fixtures = ['testdata']
def test_login_different_client(self): def test_login_different_client(self):
@ -780,12 +789,12 @@ class LoginTests(TestCase):
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Get a redirection page with the second client. # Get a redirection page with the second client.
response = c.get("/test_client_regress/login_protected_redirect_view/") response = c.get("/login_protected_redirect_view/")
# At this points, the self.client isn't logged in. # At this points, the self.client isn't logged in.
# Check that assertRedirects uses the original client, not the # Check that assertRedirects uses the original client, not the
# default client. # default client.
self.assertRedirects(response, "http://testserver/test_client_regress/get_view/") self.assertRedirects(response, "http://testserver/get_view/")
@override_settings( @override_settings(
MIDDLEWARE_CLASSES=list(settings.MIDDLEWARE_CLASSES) + MIDDLEWARE_CLASSES=list(settings.MIDDLEWARE_CLASSES) +
@ -811,6 +820,7 @@ class LoginTests(TestCase):
SESSION_ENGINE='test_client_regress.session' SESSION_ENGINE='test_client_regress.session'
) )
class SessionEngineTests(TestCase): class SessionEngineTests(TestCase):
urls = 'test_client_regress.urls'
fixtures = ['testdata'] fixtures = ['testdata']
def test_login(self): def test_login(self):
@ -819,12 +829,14 @@ class SessionEngineTests(TestCase):
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Try to access a login protected page. # Try to access a login protected page.
response = self.client.get("/test_client/login_protected_view/") response = self.client.get("/login_protected_view/")
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['user'].username, 'testclient') self.assertEqual(response.context['user'].username, 'testclient')
class URLEscapingTests(TestCase): class URLEscapingTests(TestCase):
urls = 'test_client_regress.urls'
def test_simple_argument_get(self): def test_simple_argument_get(self):
"Get a view that has a simple string argument" "Get a view that has a simple string argument"
response = self.client.get(reverse('arg_view', args=['Slartibartfast'])) response = self.client.get(reverse('arg_view', args=['Slartibartfast']))
@ -852,6 +864,7 @@ class URLEscapingTests(TestCase):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class ExceptionTests(TestCase): class ExceptionTests(TestCase):
urls = 'test_client_regress.urls'
fixtures = ['testdata.json'] fixtures = ['testdata.json']
def test_exception_cleared(self): def test_exception_cleared(self):
@ -860,7 +873,7 @@ class ExceptionTests(TestCase):
login = self.client.login(username='testclient', password='password') login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
try: try:
self.client.get("/test_client_regress/staff_only/") self.client.get("/staff_only/")
self.fail("General users should not be able to visit this page") self.fail("General users should not be able to visit this page")
except CustomTestException: except CustomTestException:
pass pass
@ -871,12 +884,14 @@ class ExceptionTests(TestCase):
login = self.client.login(username='staff', password='password') login = self.client.login(username='staff', password='password')
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
try: try:
self.client.get("/test_client_regress/staff_only/") self.client.get("/staff_only/")
except CustomTestException: except CustomTestException:
self.fail("Staff should be able to visit this page") self.fail("Staff should be able to visit this page")
class TemplateExceptionTests(TestCase): class TemplateExceptionTests(TestCase):
urls = 'test_client_regress.urls'
def setUp(self): def setUp(self):
# Reset the loaders so they don't try to render cached templates. # Reset the loaders so they don't try to render cached templates.
if loader.template_source_loaders is not None: if loader.template_source_loaders is not None:
@ -911,19 +926,24 @@ class UrlconfSubstitutionTests(TestCase):
# This test needs to run *after* UrlconfSubstitutionTests; the zz prefix in the # This test needs to run *after* UrlconfSubstitutionTests; the zz prefix in the
# name is to ensure alphabetical ordering. # name is to ensure alphabetical ordering.
class zzUrlconfSubstitutionTests(TestCase): class zzUrlconfSubstitutionTests(TestCase):
def test_urlconf_was_reverted(self): def test_urlconf_was_reverted(self):
"URLconf is reverted to original value after modification in a TestCase" """URLconf is reverted to original value after modification in a TestCase
url = reverse('arg_view', args=['somename'])
self.assertEqual(url, '/test_client_regress/arg_view/somename/') This will not find a match as the default ROOT_URLCONF is empty.
"""
with self.assertRaises(NoReverseMatch):
reverse('arg_view', args=['somename'])
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class ContextTests(TestCase): class ContextTests(TestCase):
urls = 'test_client_regress.urls'
fixtures = ['testdata'] fixtures = ['testdata']
def test_single_context(self): def test_single_context(self):
"Context variables can be retrieved from a single context" "Context variables can be retrieved from a single context"
response = self.client.get("/test_client_regress/request_data/", data={'foo': 'whiz'}) response = self.client.get("/request_data/", data={'foo': 'whiz'})
self.assertEqual(response.context.__class__, Context) self.assertEqual(response.context.__class__, Context)
self.assertTrue('get-foo' in response.context) self.assertTrue('get-foo' in response.context)
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
@ -938,7 +958,7 @@ class ContextTests(TestCase):
def test_inherited_context(self): def test_inherited_context(self):
"Context variables can be retrieved from a list of contexts" "Context variables can be retrieved from a list of contexts"
response = self.client.get("/test_client_regress/request_data_extended/", data={'foo': 'whiz'}) response = self.client.get("/request_data_extended/", data={'foo': 'whiz'})
self.assertEqual(response.context.__class__, ContextList) self.assertEqual(response.context.__class__, ContextList)
self.assertEqual(len(response.context), 2) self.assertEqual(len(response.context), 2)
self.assertTrue('get-foo' in response.context) self.assertTrue('get-foo' in response.context)
@ -973,8 +993,8 @@ class ContextTests(TestCase):
# copying RequestContext. # copying RequestContext.
try: try:
django.template.context._standard_context_processors = (lambda request: {'path': request.special_path},) django.template.context._standard_context_processors = (lambda request: {'path': request.special_path},)
response = self.client.get("/test_client_regress/request_context_view/") response = self.client.get("/request_context_view/")
self.assertContains(response, 'Path: /test_client_regress/request_context_view/') self.assertContains(response, 'Path: /request_context_view/')
finally: finally:
django.template.context._standard_context_processors = None django.template.context._standard_context_processors = None
@ -982,29 +1002,30 @@ class ContextTests(TestCase):
""" """
response.context is not lost when view call another view. response.context is not lost when view call another view.
""" """
response = self.client.get("/test_client_regress/nested_view/") response = self.client.get("/nested_view/")
self.assertEqual(response.context.__class__, Context) self.assertEqual(response.context.__class__, Context)
self.assertEqual(response.context['nested'], 'yes') self.assertEqual(response.context['nested'], 'yes')
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class SessionTests(TestCase): class SessionTests(TestCase):
urls = 'test_client_regress.urls'
fixtures = ['testdata.json'] fixtures = ['testdata.json']
def test_session(self): def test_session(self):
"The session isn't lost if a user logs in" "The session isn't lost if a user logs in"
# The session doesn't exist to start. # The session doesn't exist to start.
response = self.client.get('/test_client_regress/check_session/') response = self.client.get('/check_session/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'NO') self.assertEqual(response.content, b'NO')
# This request sets a session variable. # This request sets a session variable.
response = self.client.get('/test_client_regress/set_session/') response = self.client.get('/set_session/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'set_session') self.assertEqual(response.content, b'set_session')
# Check that the session has been modified # Check that the session has been modified
response = self.client.get('/test_client_regress/check_session/') response = self.client.get('/check_session/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'YES') self.assertEqual(response.content, b'YES')
@ -1013,7 +1034,7 @@ class SessionTests(TestCase):
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Session should still contain the modified value # Session should still contain the modified value
response = self.client.get('/test_client_regress/check_session/') response = self.client.get('/check_session/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'YES') self.assertEqual(response.content, b'YES')
@ -1096,21 +1117,23 @@ class SessionTests(TestCase):
class RequestMethodTests(TestCase): class RequestMethodTests(TestCase):
urls = 'test_client_regress.urls'
def test_get(self): def test_get(self):
"Request a view via request method GET" "Request a view via request method GET"
response = self.client.get('/test_client_regress/request_methods/') response = self.client.get('/request_methods/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'request method: GET') self.assertEqual(response.content, b'request method: GET')
def test_post(self): def test_post(self):
"Request a view via request method POST" "Request a view via request method POST"
response = self.client.post('/test_client_regress/request_methods/') response = self.client.post('/request_methods/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'request method: POST') self.assertEqual(response.content, b'request method: POST')
def test_head(self): def test_head(self):
"Request a view via request method HEAD" "Request a view via request method HEAD"
response = self.client.head('/test_client_regress/request_methods/') response = self.client.head('/request_methods/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
# A HEAD request doesn't return any content. # A HEAD request doesn't return any content.
self.assertNotEqual(response.content, b'request method: HEAD') self.assertNotEqual(response.content, b'request method: HEAD')
@ -1118,35 +1141,37 @@ class RequestMethodTests(TestCase):
def test_options(self): def test_options(self):
"Request a view via request method OPTIONS" "Request a view via request method OPTIONS"
response = self.client.options('/test_client_regress/request_methods/') response = self.client.options('/request_methods/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'request method: OPTIONS') self.assertEqual(response.content, b'request method: OPTIONS')
def test_put(self): def test_put(self):
"Request a view via request method PUT" "Request a view via request method PUT"
response = self.client.put('/test_client_regress/request_methods/') response = self.client.put('/request_methods/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'request method: PUT') self.assertEqual(response.content, b'request method: PUT')
def test_delete(self): def test_delete(self):
"Request a view via request method DELETE" "Request a view via request method DELETE"
response = self.client.delete('/test_client_regress/request_methods/') response = self.client.delete('/request_methods/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'request method: DELETE') self.assertEqual(response.content, b'request method: DELETE')
def test_patch(self): def test_patch(self):
"Request a view via request method PATCH" "Request a view via request method PATCH"
response = self.client.patch('/test_client_regress/request_methods/') response = self.client.patch('/request_methods/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'request method: PATCH') self.assertEqual(response.content, b'request method: PATCH')
class RequestMethodStringDataTests(TestCase): class RequestMethodStringDataTests(TestCase):
urls = 'test_client_regress.urls'
def test_post(self): def test_post(self):
"Request a view with string data via request method POST" "Request a view with string data via request method POST"
# Regression test for #11371 # Regression test for #11371
data = '{"test": "json"}' data = '{"test": "json"}'
response = self.client.post('/test_client_regress/request_methods/', data=data, content_type='application/json') response = self.client.post('/request_methods/', data=data, content_type='application/json')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'request method: POST') self.assertEqual(response.content, b'request method: POST')
@ -1154,7 +1179,7 @@ class RequestMethodStringDataTests(TestCase):
"Request a view with string data via request method PUT" "Request a view with string data via request method PUT"
# Regression test for #11371 # Regression test for #11371
data = '{"test": "json"}' data = '{"test": "json"}'
response = self.client.put('/test_client_regress/request_methods/', data=data, content_type='application/json') response = self.client.put('/request_methods/', data=data, content_type='application/json')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'request method: PUT') self.assertEqual(response.content, b'request method: PUT')
@ -1162,32 +1187,34 @@ class RequestMethodStringDataTests(TestCase):
"Request a view with string data via request method PATCH" "Request a view with string data via request method PATCH"
# Regression test for #17797 # Regression test for #17797
data = '{"test": "json"}' data = '{"test": "json"}'
response = self.client.patch('/test_client_regress/request_methods/', data=data, content_type='application/json') response = self.client.patch('/request_methods/', data=data, content_type='application/json')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, b'request method: PATCH') self.assertEqual(response.content, b'request method: PATCH')
class QueryStringTests(TestCase): class QueryStringTests(TestCase):
urls = 'test_client_regress.urls'
def test_get_like_requests(self): def test_get_like_requests(self):
# See: https://code.djangoproject.com/ticket/10571. # See: https://code.djangoproject.com/ticket/10571.
for method_name in ('get', 'head'): for method_name in ('get', 'head'):
# A GET-like request can pass a query string as data # A GET-like request can pass a query string as data
method = getattr(self.client, method_name) method = getattr(self.client, method_name)
response = method("/test_client_regress/request_data/", data={'foo': 'whiz'}) response = method("/request_data/", data={'foo': 'whiz'})
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['request-foo'], 'whiz') self.assertEqual(response.context['request-foo'], 'whiz')
# A GET-like request can pass a query string as part of the URL # A GET-like request can pass a query string as part of the URL
response = method("/test_client_regress/request_data/?foo=whiz") response = method("/request_data/?foo=whiz")
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['request-foo'], 'whiz') self.assertEqual(response.context['request-foo'], 'whiz')
# Data provided in the URL to a GET-like request is overridden by actual form data # Data provided in the URL to a GET-like request is overridden by actual form data
response = method("/test_client_regress/request_data/?foo=whiz", data={'foo': 'bang'}) response = method("/request_data/?foo=whiz", data={'foo': 'bang'})
self.assertEqual(response.context['get-foo'], 'bang') self.assertEqual(response.context['get-foo'], 'bang')
self.assertEqual(response.context['request-foo'], 'bang') self.assertEqual(response.context['request-foo'], 'bang')
response = method("/test_client_regress/request_data/?foo=whiz", data={'bar': 'bang'}) response = method("/request_data/?foo=whiz", data={'bar': 'bang'})
self.assertEqual(response.context['get-foo'], None) self.assertEqual(response.context['get-foo'], None)
self.assertEqual(response.context['get-bar'], 'bang') self.assertEqual(response.context['get-bar'], 'bang')
self.assertEqual(response.context['request-foo'], None) self.assertEqual(response.context['request-foo'], None)
@ -1195,23 +1222,23 @@ class QueryStringTests(TestCase):
def test_post_like_requests(self): def test_post_like_requests(self):
# A POST-like request can pass a query string as data # A POST-like request can pass a query string as data
response = self.client.post("/test_client_regress/request_data/", data={'foo': 'whiz'}) response = self.client.post("/request_data/", data={'foo': 'whiz'})
self.assertEqual(response.context['get-foo'], None) self.assertEqual(response.context['get-foo'], None)
self.assertEqual(response.context['post-foo'], 'whiz') self.assertEqual(response.context['post-foo'], 'whiz')
# A POST-like request can pass a query string as part of the URL # A POST-like request can pass a query string as part of the URL
response = self.client.post("/test_client_regress/request_data/?foo=whiz") response = self.client.post("/request_data/?foo=whiz")
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['post-foo'], None) self.assertEqual(response.context['post-foo'], None)
self.assertEqual(response.context['request-foo'], 'whiz') self.assertEqual(response.context['request-foo'], 'whiz')
# POST data provided in the URL augments actual form data # POST data provided in the URL augments actual form data
response = self.client.post("/test_client_regress/request_data/?foo=whiz", data={'foo': 'bang'}) response = self.client.post("/request_data/?foo=whiz", data={'foo': 'bang'})
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['post-foo'], 'bang') self.assertEqual(response.context['post-foo'], 'bang')
self.assertEqual(response.context['request-foo'], 'bang') self.assertEqual(response.context['request-foo'], 'bang')
response = self.client.post("/test_client_regress/request_data/?foo=whiz", data={'bar': 'bang'}) response = self.client.post("/request_data/?foo=whiz", data={'bar': 'bang'})
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['get-bar'], None) self.assertEqual(response.context['get-bar'], None)
self.assertEqual(response.context['post-foo'], None) self.assertEqual(response.context['post-foo'], None)
@ -1221,11 +1248,13 @@ class QueryStringTests(TestCase):
class UnicodePayloadTests(TestCase): class UnicodePayloadTests(TestCase):
urls = 'test_client_regress.urls'
def test_simple_unicode_payload(self): def test_simple_unicode_payload(self):
"A simple ASCII-only unicode JSON document can be POSTed" "A simple ASCII-only unicode JSON document can be POSTed"
# Regression test for #10571 # Regression test for #10571
json = '{"english": "mountain pass"}' json = '{"english": "mountain pass"}'
response = self.client.post("/test_client_regress/parse_unicode_json/", json, response = self.client.post("/parse_unicode_json/", json,
content_type="application/json") content_type="application/json")
self.assertEqual(response.content, json.encode()) self.assertEqual(response.content, json.encode())
@ -1233,7 +1262,7 @@ class UnicodePayloadTests(TestCase):
"A non-ASCII unicode data encoded as UTF-8 can be POSTed" "A non-ASCII unicode data encoded as UTF-8 can be POSTed"
# Regression test for #10571 # Regression test for #10571
json = '{"dog": "собака"}' json = '{"dog": "собака"}'
response = self.client.post("/test_client_regress/parse_unicode_json/", json, response = self.client.post("/parse_unicode_json/", json,
content_type="application/json; charset=utf-8") content_type="application/json; charset=utf-8")
self.assertEqual(response.content, json.encode('utf-8')) self.assertEqual(response.content, json.encode('utf-8'))
@ -1241,7 +1270,7 @@ class UnicodePayloadTests(TestCase):
"A non-ASCII unicode data encoded as UTF-16 can be POSTed" "A non-ASCII unicode data encoded as UTF-16 can be POSTed"
# Regression test for #10571 # Regression test for #10571
json = '{"dog": "собака"}' json = '{"dog": "собака"}'
response = self.client.post("/test_client_regress/parse_unicode_json/", json, response = self.client.post("/parse_unicode_json/", json,
content_type="application/json; charset=utf-16") content_type="application/json; charset=utf-16")
self.assertEqual(response.content, json.encode('utf-16')) self.assertEqual(response.content, json.encode('utf-16'))
@ -1249,7 +1278,7 @@ class UnicodePayloadTests(TestCase):
"A non-ASCII unicode data as a non-UTF based encoding can be POSTed" "A non-ASCII unicode data as a non-UTF based encoding can be POSTed"
# Regression test for #10571 # Regression test for #10571
json = '{"dog": "собака"}' json = '{"dog": "собака"}'
response = self.client.post("/test_client_regress/parse_unicode_json/", json, response = self.client.post("/parse_unicode_json/", json,
content_type="application/json; charset=koi8-r") content_type="application/json; charset=koi8-r")
self.assertEqual(response.content, json.encode('koi8-r')) self.assertEqual(response.content, json.encode('koi8-r'))
@ -1284,11 +1313,12 @@ class UploadedFileEncodingTest(TestCase):
class RequestHeadersTest(TestCase): class RequestHeadersTest(TestCase):
urls = 'test_client_regress.urls'
fixtures = ['testdata'] fixtures = ['testdata']
def test_client_headers(self): def test_client_headers(self):
"A test client can receive custom headers" "A test client can receive custom headers"
response = self.client.get("/test_client_regress/check_headers/", HTTP_X_ARG_CHECK='Testing 123') response = self.client.get("/check_headers/", HTTP_X_ARG_CHECK='Testing 123')
self.assertEqual(response.content, b"HTTP_X_ARG_CHECK: Testing 123") self.assertEqual(response.content, b"HTTP_X_ARG_CHECK: Testing 123")
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -1312,9 +1342,9 @@ class RequestHeadersTest(TestCase):
def test_client_headers_redirect(self): def test_client_headers_redirect(self):
"Test client headers are preserved through redirects" "Test client headers are preserved through redirects"
response = self.client.get("/test_client_regress/check_headers_redirect/", follow=True, HTTP_X_ARG_CHECK='Testing 123') response = self.client.get("/check_headers_redirect/", follow=True, HTTP_X_ARG_CHECK='Testing 123')
self.assertEqual(response.content, b"HTTP_X_ARG_CHECK: Testing 123") self.assertEqual(response.content, b"HTTP_X_ARG_CHECK: Testing 123")
self.assertRedirects(response, '/test_client_regress/check_headers/', self.assertRedirects(response, '/check_headers/',
status_code=301, target_status_code=200) status_code=301, target_status_code=200)
@ -1325,28 +1355,29 @@ class ReadLimitedStreamTest(TestCase):
Refs #14753, #15785 Refs #14753, #15785
""" """
urls = 'test_client_regress.urls'
def test_body_from_empty_request(self): def test_body_from_empty_request(self):
"""HttpRequest.body on a test client GET request should return """HttpRequest.body on a test client GET request should return
the empty string.""" the empty string."""
self.assertEqual(self.client.get("/test_client_regress/body/").content, b'') self.assertEqual(self.client.get("/body/").content, b'')
def test_read_from_empty_request(self): def test_read_from_empty_request(self):
"""HttpRequest.read() on a test client GET request should return the """HttpRequest.read() on a test client GET request should return the
empty string.""" empty string."""
self.assertEqual(self.client.get("/test_client_regress/read_all/").content, b'') self.assertEqual(self.client.get("/read_all/").content, b'')
def test_read_numbytes_from_empty_request(self): def test_read_numbytes_from_empty_request(self):
"""HttpRequest.read(LARGE_BUFFER) on a test client GET request should """HttpRequest.read(LARGE_BUFFER) on a test client GET request should
return the empty string.""" return the empty string."""
self.assertEqual(self.client.get("/test_client_regress/read_buffer/").content, b'') self.assertEqual(self.client.get("/read_buffer/").content, b'')
def test_read_from_nonempty_request(self): def test_read_from_nonempty_request(self):
"""HttpRequest.read() on a test client PUT request with some payload """HttpRequest.read() on a test client PUT request with some payload
should return that payload.""" should return that payload."""
payload = b'foobar' payload = b'foobar'
self.assertEqual(self.client.put( self.assertEqual(self.client.put(
"/test_client_regress/read_all/", "/read_all/",
data=payload, data=payload,
content_type='text/plain').content, payload) content_type='text/plain').content, payload)
@ -1355,7 +1386,7 @@ class ReadLimitedStreamTest(TestCase):
some payload should return that payload.""" some payload should return that payload."""
payload = b'foobar' payload = b'foobar'
self.assertEqual( self.assertEqual(
self.client.put("/test_client_regress/read_buffer/", self.client.put("/read_buffer/",
data=payload, data=payload,
content_type='text/plain').content, payload) content_type='text/plain').content, payload)
@ -1367,6 +1398,7 @@ class RequestFactoryStateTest(TestCase):
# ensuring test isolation behavior. So, unusually, it doesn't make sense to # ensuring test isolation behavior. So, unusually, it doesn't make sense to
# run the tests individually, and if any are failing it is confusing to run # run the tests individually, and if any are failing it is confusing to run
# them with any other set of tests. # them with any other set of tests.
urls = 'test_client_regress.urls'
def common_test_that_should_always_pass(self): def common_test_that_should_always_pass(self):
request = RequestFactory().get('/') request = RequestFactory().get('/')
@ -1391,6 +1423,7 @@ class RequestFactoryEnvironmentTests(TestCase):
Regression tests for #8551 and #17067: ensure that environment variables Regression tests for #8551 and #17067: ensure that environment variables
are set correctly in RequestFactory. are set correctly in RequestFactory.
""" """
urls = 'test_client_regress.urls'
def test_should_set_correct_env_variables(self): def test_should_set_correct_env_variables(self):
request = RequestFactory().get('/path/') request = RequestFactory().get('/path/')

View File

@ -1,10 +1,12 @@
from django.conf.urls import patterns, url from django.conf.urls import patterns, url, include
from django.views.generic import RedirectView from django.views.generic import RedirectView
from . import views from . import views
urlpatterns = patterns('', urlpatterns = patterns('',
(r'', include('test_client.urls')),
(r'^no_template_view/$', views.no_template_view), (r'^no_template_view/$', views.no_template_view),
(r'^staff_only/$', views.staff_only_view), (r'^staff_only/$', views.staff_only_view),
(r'^get_view/$', views.get_view), (r'^get_view/$', views.get_view),
@ -13,16 +15,16 @@ urlpatterns = patterns('',
url(r'^arg_view/(?P<name>.+)/$', views.view_with_argument, name='arg_view'), url(r'^arg_view/(?P<name>.+)/$', views.view_with_argument, name='arg_view'),
url(r'^nested_view/$', views.nested_view, name='nested_view'), url(r'^nested_view/$', views.nested_view, name='nested_view'),
(r'^login_protected_redirect_view/$', views.login_protected_redirect_view), (r'^login_protected_redirect_view/$', views.login_protected_redirect_view),
(r'^redirects/$', RedirectView.as_view(url='/test_client_regress/redirects/further/')), (r'^redirects/$', RedirectView.as_view(url='/redirects/further/')),
(r'^redirects/further/$', RedirectView.as_view(url='/test_client_regress/redirects/further/more/')), (r'^redirects/further/$', RedirectView.as_view(url='/redirects/further/more/')),
(r'^redirects/further/more/$', RedirectView.as_view(url='/test_client_regress/no_template_view/')), (r'^redirects/further/more/$', RedirectView.as_view(url='/no_template_view/')),
(r'^redirect_to_non_existent_view/$', RedirectView.as_view(url='/test_client_regress/non_existent_view/')), (r'^redirect_to_non_existent_view/$', RedirectView.as_view(url='/non_existent_view/')),
(r'^redirect_to_non_existent_view2/$', RedirectView.as_view(url='/test_client_regress/redirect_to_non_existent_view/')), (r'^redirect_to_non_existent_view2/$', RedirectView.as_view(url='/redirect_to_non_existent_view/')),
(r'^redirect_to_self/$', RedirectView.as_view(url='/test_client_regress/redirect_to_self/')), (r'^redirect_to_self/$', RedirectView.as_view(url='/redirect_to_self/')),
(r'^circular_redirect_1/$', RedirectView.as_view(url='/test_client_regress/circular_redirect_2/')), (r'^circular_redirect_1/$', RedirectView.as_view(url='/circular_redirect_2/')),
(r'^circular_redirect_2/$', RedirectView.as_view(url='/test_client_regress/circular_redirect_3/')), (r'^circular_redirect_2/$', RedirectView.as_view(url='/circular_redirect_3/')),
(r'^circular_redirect_3/$', RedirectView.as_view(url='/test_client_regress/circular_redirect_1/')), (r'^circular_redirect_3/$', RedirectView.as_view(url='/circular_redirect_1/')),
(r'^redirect_other_host/$', RedirectView.as_view(url='https://otherserver:8443/test_client_regress/no_template_view/')), (r'^redirect_other_host/$', RedirectView.as_view(url='https://otherserver:8443/no_template_view/')),
(r'^set_session/$', views.set_session_view), (r'^set_session/$', views.set_session_view),
(r'^check_session/$', views.check_session_view), (r'^check_session/$', views.check_session_view),
(r'^request_methods/$', views.request_methods_view), (r'^request_methods/$', views.request_methods_view),
@ -30,7 +32,7 @@ urlpatterns = patterns('',
(r'^check_binary/$', views.return_undecodable_binary), (r'^check_binary/$', views.return_undecodable_binary),
(r'^parse_unicode_json/$', views.return_json_file), (r'^parse_unicode_json/$', views.return_json_file),
(r'^check_headers/$', views.check_headers), (r'^check_headers/$', views.check_headers),
(r'^check_headers_redirect/$', RedirectView.as_view(url='/test_client_regress/check_headers/')), (r'^check_headers_redirect/$', RedirectView.as_view(url='/check_headers/')),
(r'^body/$', views.body), (r'^body/$', views.body),
(r'^read_all/$', views.read_all), (r'^read_all/$', views.read_all),
(r'^read_buffer/$', views.read_buffer), (r'^read_buffer/$', views.read_buffer),

View File

@ -74,13 +74,13 @@ def nested_view(request):
""" """
setup_test_environment() setup_test_environment()
c = Client() c = Client()
c.get("/test_client_regress/no_template_view") c.get("/no_template_view")
return render_to_response('base.html', {'nested': 'yes'}) return render_to_response('base.html', {'nested': 'yes'})
def login_protected_redirect_view(request): def login_protected_redirect_view(request):
"A view that redirects all requests to the GET view" "A view that redirects all requests to the GET view"
return HttpResponseRedirect('/test_client_regress/get_view/') return HttpResponseRedirect('/get_view/')
login_protected_redirect_view = login_required(login_protected_redirect_view) login_protected_redirect_view = login_required(login_protected_redirect_view)

View File

@ -1,33 +1,8 @@
from django.conf.urls import patterns, include """This urlconf exists because Django expects ROOT_URLCONF to exist. URLs
should be added within the test folders, and use TestCase.urls to set them.
This helps the tests remain isolated.
"""
from django.conf.urls import patterns
urlpatterns = patterns('',
# test_client urls
(r'^test_client/', include('test_client.urls')),
(r'^test_client_regress/', include('test_client_regress.urls')),
# File upload test views urlpatterns = patterns('')
(r'^file_uploads/', include('file_uploads.urls')),
# Always provide the auth system login and logout views
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
# test urlconf for {% url %} template tag
(r'^url_tag/', include('template_tests.urls')),
# django built-in views
(r'^views/', include('view_tests.urls')),
# test urlconf for middleware tests
(r'^middleware/', include('middleware.urls')),
# admin widget tests
(r'widget_admin/', include('admin_widgets.urls')),
# admin custom URL tests
(r'^custom_urls/', include('admin_custom_urls.urls')),
# admin scripts tests
(r'^admin_scripts/', include('admin_scripts.urls')),
)

View File

@ -14,7 +14,7 @@ class Author(models.Model):
return self.name return self.name
def get_absolute_url(self): def get_absolute_url(self):
return '/views/authors/%s/' % self.id return '/authors/%s/' % self.id
@python_2_unicode_compatible @python_2_unicode_compatible

View File

@ -49,7 +49,7 @@ class DebugViewTests(TestCase):
# Ensure no 403.html template exists to test the default case. # Ensure no 403.html template exists to test the default case.
setup_test_template_loader({}) setup_test_template_loader({})
try: try:
response = self.client.get('/views/raises403/') response = self.client.get('/raises403/')
self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403) self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403)
finally: finally:
restore_template_loaders() restore_template_loaders()
@ -60,13 +60,13 @@ class DebugViewTests(TestCase):
{'403.html': 'This is a test template for a 403 Forbidden error.'} {'403.html': 'This is a test template for a 403 Forbidden error.'}
) )
try: try:
response = self.client.get('/views/raises403/') response = self.client.get('/raises403/')
self.assertContains(response, 'test template', status_code=403) self.assertContains(response, 'test template', status_code=403)
finally: finally:
restore_template_loaders() restore_template_loaders()
def test_404(self): def test_404(self):
response = self.client.get('/views/raises404/') response = self.client.get('/raises404/')
self.assertEqual(response.status_code, 404) self.assertEqual(response.status_code, 404)
def test_view_exceptions(self): def test_view_exceptions(self):
@ -79,7 +79,7 @@ class DebugViewTests(TestCase):
Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized. Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized.
""" """
with self.settings(DEBUG=True, USE_L10N=True): with self.settings(DEBUG=True, USE_L10N=True):
response = self.client.get('/views/raises500/') response = self.client.get('/raises500/')
# We look for a HTML fragment of the form # We look for a HTML fragment of the form
# '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"' # '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"'
self.assertContains(response, '<div class="context" id="', status_code=500) self.assertContains(response, '<div class="context" id="', status_code=500)
@ -518,6 +518,7 @@ class ExceptionReporterFilterTests(TestCase, ExceptionReportTestMixin):
Ensure that sensitive information can be filtered out of error reports. Ensure that sensitive information can be filtered out of error reports.
Refs #14614. Refs #14614.
""" """
urls = 'view_tests.urls'
rf = RequestFactory() rf = RequestFactory()
def test_non_sensitive_request(self): def test_non_sensitive_request(self):
@ -640,7 +641,7 @@ class ExceptionReporterFilterTests(TestCase, ExceptionReportTestMixin):
def callable_setting(): def callable_setting():
return "This should not be displayed" return "This should not be displayed"
with self.settings(DEBUG=True, FOOBAR=callable_setting): with self.settings(DEBUG=True, FOOBAR=callable_setting):
response = self.client.get('/views/raises500/') response = self.client.get('/raises500/')
self.assertNotContains(response, "This should not be displayed", status_code=500) self.assertNotContains(response, "This should not be displayed", status_code=500)
def test_dict_setting_with_non_str_key(self): def test_dict_setting_with_non_str_key(self):
@ -649,7 +650,7 @@ class ExceptionReporterFilterTests(TestCase, ExceptionReportTestMixin):
debug page (#12744). debug page (#12744).
""" """
with self.settings(DEBUG=True, FOOBAR={42: None}): with self.settings(DEBUG=True, FOOBAR={42: None}):
response = self.client.get('/views/raises500/') response = self.client.get('/raises500/')
self.assertContains(response, 'FOOBAR', status_code=500) self.assertContains(response, 'FOOBAR', status_code=500)
def test_sensitive_settings(self): def test_sensitive_settings(self):
@ -665,7 +666,7 @@ class ExceptionReporterFilterTests(TestCase, ExceptionReportTestMixin):
] ]
for setting in sensitive_settings: for setting in sensitive_settings:
with self.settings(DEBUG=True, **{setting: "should not be displayed"}): with self.settings(DEBUG=True, **{setting: "should not be displayed"}):
response = self.client.get('/views/raises500/') response = self.client.get('/raises500/')
self.assertNotContains(response, 'should not be displayed', status_code=500) self.assertNotContains(response, 'should not be displayed', status_code=500)
def test_settings_with_sensitive_keys(self): def test_settings_with_sensitive_keys(self):
@ -685,7 +686,7 @@ class ExceptionReporterFilterTests(TestCase, ExceptionReportTestMixin):
'recursive': {setting: "should not be displayed"}, 'recursive': {setting: "should not be displayed"},
} }
with self.settings(DEBUG=True, FOOBAR=FOOBAR): with self.settings(DEBUG=True, FOOBAR=FOOBAR):
response = self.client.get('/views/raises500/') response = self.client.get('/raises500/')
self.assertNotContains(response, 'should not be displayed', status_code=500) self.assertNotContains(response, 'should not be displayed', status_code=500)

View File

@ -9,9 +9,10 @@ from ..models import UrlArticle
class DefaultsTests(TestCase): class DefaultsTests(TestCase):
"""Test django views in django/views/defaults.py""" """Test django views in django/views/defaults.py"""
urls = 'view_tests.urls'
fixtures = ['testdata.json'] fixtures = ['testdata.json']
non_existing_urls = ['/views/non_existing_url/', # this is in urls.py non_existing_urls = ['/non_existing_url/', # this is in urls.py
'/views/other_non_existing_url/'] # this NOT in urls.py '/other_non_existing_url/'] # this NOT in urls.py
def test_page_not_found(self): def test_page_not_found(self):
"A 404 status is returned by the page_not_found view" "A 404 status is returned by the page_not_found view"
@ -32,7 +33,7 @@ class DefaultsTests(TestCase):
def test_server_error(self): def test_server_error(self):
"The server_error view raises a 500 status" "The server_error view raises a 500 status"
response = self.client.get('/views/server_error/') response = self.client.get('/server_error/')
self.assertEqual(response.status_code, 500) self.assertEqual(response.status_code, 500)
def test_custom_templates(self): def test_custom_templates(self):
@ -45,7 +46,7 @@ class DefaultsTests(TestCase):
'500.html': 'This is a test template for a 500 error.'} '500.html': 'This is a test template for a 500 error.'}
) )
try: try:
for code, url in ((404, '/views/non_existing_url/'), (500, '/views/server_error/')): for code, url in ((404, '/non_existing_url/'), (500, '/server_error/')):
response = self.client.get(url) response = self.client.get(url)
self.assertContains(response, "test template for a %d error" % code, self.assertContains(response, "test template for a %d error" % code,
status_code=code) status_code=code)
@ -65,14 +66,14 @@ class DefaultsTests(TestCase):
""" """
Content-Type of the default error responses is text/html. Refs #20822. Content-Type of the default error responses is text/html. Refs #20822.
""" """
response = self.client.get('/views/raises400/') response = self.client.get('/raises400/')
self.assertEqual(response['Content-Type'], 'text/html') self.assertEqual(response['Content-Type'], 'text/html')
response = self.client.get('/views/raises403/') response = self.client.get('/raises403/')
self.assertEqual(response['Content-Type'], 'text/html') self.assertEqual(response['Content-Type'], 'text/html')
response = self.client.get('/views/non_existing_url/') response = self.client.get('/non_existing_url/')
self.assertEqual(response['Content-Type'], 'text/html') self.assertEqual(response['Content-Type'], 'text/html')
response = self.client.get('/views/server_error/') response = self.client.get('/server_error/')
self.assertEqual(response['Content-Type'], 'text/html') self.assertEqual(response['Content-Type'], 'text/html')

View File

@ -23,6 +23,7 @@ from ..urls import locale_dir
class I18NTests(TestCase): class I18NTests(TestCase):
""" Tests django views in django/views/i18n.py """ """ Tests django views in django/views/i18n.py """
urls = 'view_tests.urls'
def test_setlang(self): def test_setlang(self):
""" """
@ -31,9 +32,9 @@ class I18NTests(TestCase):
The user is redirected to the 'next' argument if provided. The user is redirected to the 'next' argument if provided.
""" """
for lang_code, lang_name in settings.LANGUAGES: for lang_code, lang_name in settings.LANGUAGES:
post_data = dict(language=lang_code, next='/views/') post_data = dict(language=lang_code, next='/')
response = self.client.post('/views/i18n/setlang/', data=post_data) response = self.client.post('/i18n/setlang/', data=post_data)
self.assertRedirects(response, 'http://testserver/views/') self.assertRedirects(response, 'http://testserver/')
self.assertEqual(self.client.session['_language'], lang_code) self.assertEqual(self.client.session['_language'], lang_code)
def test_setlang_unsafe_next(self): def test_setlang_unsafe_next(self):
@ -43,12 +44,12 @@ class I18NTests(TestCase):
""" """
lang_code, lang_name = settings.LANGUAGES[0] lang_code, lang_name = settings.LANGUAGES[0]
post_data = dict(language=lang_code, next='//unsafe/redirection/') post_data = dict(language=lang_code, next='//unsafe/redirection/')
response = self.client.post('/views/i18n/setlang/', data=post_data) response = self.client.post('/i18n/setlang/', data=post_data)
self.assertEqual(response.url, 'http://testserver/') self.assertEqual(response.url, 'http://testserver/')
self.assertEqual(self.client.session['_language'], lang_code) self.assertEqual(self.client.session['_language'], lang_code)
def test_setlang_reversal(self): def test_setlang_reversal(self):
self.assertEqual(reverse('set_language'), '/views/i18n/setlang/') self.assertEqual(reverse('set_language'), '/i18n/setlang/')
def test_jsi18n(self): def test_jsi18n(self):
"""The javascript_catalog can be deployed with language settings""" """The javascript_catalog can be deployed with language settings"""
@ -59,7 +60,7 @@ class I18NTests(TestCase):
trans_txt = catalog.gettext('this is to be translated') trans_txt = catalog.gettext('this is to be translated')
else: else:
trans_txt = catalog.ugettext('this is to be translated') trans_txt = catalog.ugettext('this is to be translated')
response = self.client.get('/views/jsi18n/') response = self.client.get('/jsi18n/')
# response content must include a line like: # response content must include a line like:
# "this is to be translated": <value of trans_txt Python variable> # "this is to be translated": <value of trans_txt Python variable>
# javascript_quote is used to be able to check unicode strings # javascript_quote is used to be able to check unicode strings
@ -74,6 +75,7 @@ class JsI18NTests(TestCase):
Tests django views in django/views/i18n.py that need to change Tests django views in django/views/i18n.py that need to change
settings.LANGUAGE_CODE. settings.LANGUAGE_CODE.
""" """
urls = 'view_tests.urls'
def test_jsi18n_with_missing_en_files(self): def test_jsi18n_with_missing_en_files(self):
""" """
@ -86,7 +88,7 @@ class JsI18NTests(TestCase):
than English. than English.
""" """
with self.settings(LANGUAGE_CODE='es'), override('en-us'): with self.settings(LANGUAGE_CODE='es'), override('en-us'):
response = self.client.get('/views/jsi18n/') response = self.client.get('/jsi18n/')
self.assertNotContains(response, 'esto tiene que ser traducido') self.assertNotContains(response, 'esto tiene que ser traducido')
def test_jsi18n_fallback_language(self): def test_jsi18n_fallback_language(self):
@ -95,7 +97,7 @@ class JsI18NTests(TestCase):
in cases where the selected language cannot be found. in cases where the selected language cannot be found.
""" """
with self.settings(LANGUAGE_CODE='fr'), override('fi'): with self.settings(LANGUAGE_CODE='fr'), override('fi'):
response = self.client.get('/views/jsi18n/') response = self.client.get('/jsi18n/')
self.assertContains(response, 'il faut le traduire') self.assertContains(response, 'il faut le traduire')
def testI18NLanguageNonEnglishDefault(self): def testI18NLanguageNonEnglishDefault(self):
@ -106,7 +108,7 @@ class JsI18NTests(TestCase):
#3594 and #13726 for more details. #3594 and #13726 for more details.
""" """
with self.settings(LANGUAGE_CODE='fr'), override('en-us'): with self.settings(LANGUAGE_CODE='fr'), override('en-us'):
response = self.client.get('/views/jsi18n/') response = self.client.get('/jsi18n/')
self.assertNotContains(response, 'Choisir une heure') self.assertNotContains(response, 'Choisir une heure')
@modify_settings(INSTALLED_APPS={'append': 'view_tests.app0'}) @modify_settings(INSTALLED_APPS={'append': 'view_tests.app0'})
@ -117,7 +119,7 @@ class JsI18NTests(TestCase):
with the proper English translations. See #13726 for more details. with the proper English translations. See #13726 for more details.
""" """
with self.settings(LANGUAGE_CODE='fr'), override('en-us'): with self.settings(LANGUAGE_CODE='fr'), override('en-us'):
response = self.client.get('/views/jsi18n_english_translation/') response = self.client.get('/jsi18n_english_translation/')
self.assertContains(response, javascript_quote('this app0 string is to be translated')) self.assertContains(response, javascript_quote('this app0 string is to be translated'))
def testI18NLanguageNonEnglishFallback(self): def testI18NLanguageNonEnglishFallback(self):
@ -126,16 +128,17 @@ class JsI18NTests(TestCase):
in cases where the selected language cannot be found. in cases where the selected language cannot be found.
""" """
with self.settings(LANGUAGE_CODE='fr'), override('none'): with self.settings(LANGUAGE_CODE='fr'), override('none'):
response = self.client.get('/views/jsi18n/') response = self.client.get('/jsi18n/')
self.assertContains(response, 'Choisir une heure') self.assertContains(response, 'Choisir une heure')
def test_escaping(self): def test_escaping(self):
# Force a language via GET otherwise the gettext functions are a noop! # Force a language via GET otherwise the gettext functions are a noop!
response = self.client.get('/views/jsi18n_admin/?language=de') response = self.client.get('/jsi18n_admin/?language=de')
self.assertContains(response, '\\x04') self.assertContains(response, '\\x04')
class JsI18NTestsMultiPackage(TestCase): class JsI18NTestsMultiPackage(TestCase):
urls = 'view_tests.urls'
""" """
Tests for django views in django/views/i18n.py that need to change Tests for django views in django/views/i18n.py that need to change
settings.LANGUAGE_CODE and merge JS translation from several packages. settings.LANGUAGE_CODE and merge JS translation from several packages.
@ -150,7 +153,7 @@ class JsI18NTestsMultiPackage(TestCase):
#3594 and #13514 for more details. #3594 and #13514 for more details.
""" """
with self.settings(LANGUAGE_CODE='en-us'), override('fr'): with self.settings(LANGUAGE_CODE='en-us'), override('fr'):
response = self.client.get('/views/jsi18n_multi_packages1/') response = self.client.get('/jsi18n_multi_packages1/')
self.assertContains(response, javascript_quote('il faut traduire cette chaîne de caractères de app1')) self.assertContains(response, javascript_quote('il faut traduire cette chaîne de caractères de app1'))
@modify_settings(INSTALLED_APPS={'append': ['view_tests.app3', 'view_tests.app4']}) @modify_settings(INSTALLED_APPS={'append': ['view_tests.app3', 'view_tests.app4']})
@ -160,7 +163,7 @@ class JsI18NTestsMultiPackage(TestCase):
English. English.
""" """
with self.settings(LANGUAGE_CODE='fr'), override('es-ar'): with self.settings(LANGUAGE_CODE='fr'), override('es-ar'):
response = self.client.get('/views/jsi18n_multi_packages2/') response = self.client.get('/jsi18n_multi_packages2/')
self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido')) self.assertContains(response, javascript_quote('este texto de app3 debe ser traducido'))
def testI18NWithLocalePaths(self): def testI18NWithLocalePaths(self):
@ -169,7 +172,7 @@ class JsI18NTestsMultiPackage(TestCase):
path.dirname(path.abspath(upath(__file__)))), 'app3', 'locale'),) path.dirname(path.abspath(upath(__file__)))), 'app3', 'locale'),)
with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths): with self.settings(LANGUAGE_CODE='es-ar', LOCALE_PATHS=extended_locale_paths):
with override('es-ar'): with override('es-ar'):
response = self.client.get('/views/jsi18n/') response = self.client.get('/jsi18n/')
self.assertContains(response, self.assertContains(response,
javascript_quote('este texto de app3 debe ser traducido')) javascript_quote('este texto de app3 debe ser traducido'))

View File

@ -18,13 +18,14 @@ from ..urls import media_dir
class StaticTests(SimpleTestCase): class StaticTests(SimpleTestCase):
"""Tests django views in django/views/static.py""" """Tests django views in django/views/static.py"""
urls = 'view_tests.urls'
prefix = 'site_media' prefix = 'site_media'
def test_serve(self): def test_serve(self):
"The static view can serve static media" "The static view can serve static media"
media_files = ['file.txt', 'file.txt.gz'] media_files = ['file.txt', 'file.txt.gz']
for filename in media_files: for filename in media_files:
response = self.client.get('/views/%s/%s' % (self.prefix, filename)) response = self.client.get('/%s/%s' % (self.prefix, filename))
response_content = b''.join(response) response_content = b''.join(response)
file_path = path.join(media_dir, filename) file_path = path.join(media_dir, filename)
with open(file_path, 'rb') as fp: with open(file_path, 'rb') as fp:
@ -33,19 +34,19 @@ class StaticTests(SimpleTestCase):
self.assertEqual(mimetypes.guess_type(file_path)[1], response.get('Content-Encoding', None)) self.assertEqual(mimetypes.guess_type(file_path)[1], response.get('Content-Encoding', None))
def test_unknown_mime_type(self): def test_unknown_mime_type(self):
response = self.client.get('/views/%s/file.unknown' % self.prefix) response = self.client.get('/%s/file.unknown' % self.prefix)
self.assertEqual('application/octet-stream', response['Content-Type']) self.assertEqual('application/octet-stream', response['Content-Type'])
def test_copes_with_empty_path_component(self): def test_copes_with_empty_path_component(self):
file_name = 'file.txt' file_name = 'file.txt'
response = self.client.get('/views/%s//%s' % (self.prefix, file_name)) response = self.client.get('/%s//%s' % (self.prefix, file_name))
response_content = b''.join(response) response_content = b''.join(response)
with open(path.join(media_dir, file_name), 'rb') as fp: with open(path.join(media_dir, file_name), 'rb') as fp:
self.assertEqual(fp.read(), response_content) self.assertEqual(fp.read(), response_content)
def test_is_modified_since(self): def test_is_modified_since(self):
file_name = 'file.txt' file_name = 'file.txt'
response = self.client.get('/views/%s/%s' % (self.prefix, file_name), response = self.client.get('/%s/%s' % (self.prefix, file_name),
HTTP_IF_MODIFIED_SINCE='Thu, 1 Jan 1970 00:00:00 GMT') HTTP_IF_MODIFIED_SINCE='Thu, 1 Jan 1970 00:00:00 GMT')
response_content = b''.join(response) response_content = b''.join(response)
with open(path.join(media_dir, file_name), 'rb') as fp: with open(path.join(media_dir, file_name), 'rb') as fp:
@ -54,7 +55,7 @@ class StaticTests(SimpleTestCase):
def test_not_modified_since(self): def test_not_modified_since(self):
file_name = 'file.txt' file_name = 'file.txt'
response = self.client.get( response = self.client.get(
'/views/%s/%s' % (self.prefix, file_name), '/%s/%s' % (self.prefix, file_name),
HTTP_IF_MODIFIED_SINCE='Mon, 18 Jan 2038 05:14:07 GMT' HTTP_IF_MODIFIED_SINCE='Mon, 18 Jan 2038 05:14:07 GMT'
# This is 24h before max Unix time. Remember to fix Django and # This is 24h before max Unix time. Remember to fix Django and
# update this test well before 2038 :) # update this test well before 2038 :)
@ -69,7 +70,7 @@ class StaticTests(SimpleTestCase):
""" """
file_name = 'file.txt' file_name = 'file.txt'
invalid_date = 'Mon, 28 May 999999999999 28:25:26 GMT' invalid_date = 'Mon, 28 May 999999999999 28:25:26 GMT'
response = self.client.get('/views/%s/%s' % (self.prefix, file_name), response = self.client.get('/%s/%s' % (self.prefix, file_name),
HTTP_IF_MODIFIED_SINCE=invalid_date) HTTP_IF_MODIFIED_SINCE=invalid_date)
response_content = b''.join(response) response_content = b''.join(response)
with open(path.join(media_dir, file_name), 'rb') as fp: with open(path.join(media_dir, file_name), 'rb') as fp:
@ -84,7 +85,7 @@ class StaticTests(SimpleTestCase):
""" """
file_name = 'file.txt' file_name = 'file.txt'
invalid_date = ': 1291108438, Wed, 20 Oct 2010 14:05:00 GMT' invalid_date = ': 1291108438, Wed, 20 Oct 2010 14:05:00 GMT'
response = self.client.get('/views/%s/%s' % (self.prefix, file_name), response = self.client.get('/%s/%s' % (self.prefix, file_name),
HTTP_IF_MODIFIED_SINCE=invalid_date) HTTP_IF_MODIFIED_SINCE=invalid_date)
response_content = b''.join(response) response_content = b''.join(response)
with open(path.join(media_dir, file_name), 'rb') as fp: with open(path.join(media_dir, file_name), 'rb') as fp:
@ -92,7 +93,7 @@ class StaticTests(SimpleTestCase):
self.assertEqual(len(response_content), int(response['Content-Length'])) self.assertEqual(len(response_content), int(response['Content-Length']))
def test_404(self): def test_404(self):
response = self.client.get('/views/%s/non_existing_resource' % self.prefix) response = self.client.get('/%s/non_existing_resource' % self.prefix)
self.assertEqual(404, response.status_code) self.assertEqual(404, response.status_code)