Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

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.
  • Loading branch information...
commit 2607fa901699916c4825f145fa8a84f49b8524ff 1 parent ac8d0a4
Marc Tamlyn mjtamlyn authored
1  django/contrib/auth/tests/test_templates.py
View
@@ -17,6 +17,7 @@
PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',),
)
class AuthTemplateTests(TestCase):
+ urls = 'django.contrib.auth.tests.urls'
def test_titles(self):
rf = RequestFactory()
6 django/contrib/auth/tests/urls.py
View
@@ -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.forms import AuthenticationForm
from django.contrib.auth.urls import urlpatterns
@@ -98,4 +99,7 @@ def custom_request_auth_login(request):
(r'^auth_processor_messages/$', auth_processor_messages),
(r'^custom_request_auth_login/$', custom_request_auth_login),
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)),
)
10 tests/admin_custom_urls/tests.py
View
@@ -16,6 +16,7 @@ class AdminCustomUrlsTest(TestCase):
* The ModelAdmin for Action customizes the add_view URL, it's
'<app name>/<model name>/!add/'
"""
+ urls = 'admin_custom_urls.urls'
fixtures = ['users.json', 'actions.json']
def setUp(self):
@@ -28,7 +29,7 @@ def testBasicAddGet(self):
"""
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.assertEqual(response.status_code, 200)
@@ -37,7 +38,7 @@ def testAddWithGETArgs(self):
Ensure GET on the add_view plus specifying a field value in the query
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.assertContains(response, 'value="My Action"')
@@ -50,7 +51,7 @@ def testBasicAddPost(self):
"name": 'Action added through a popup',
"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.assertContains(response, 'dismissAddAnotherPopup')
self.assertContains(response, 'Action added through a popup')
@@ -61,7 +62,7 @@ def testAdminUrlsNoClash(self):
"""
# Should get the change_view for model instance with PK 'add', not show
# 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.assertContains(response, 'Change action')
@@ -84,6 +85,7 @@ def testAdminUrlsNoClash(self):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class CustomRedirects(TestCase):
+ urls = 'admin_custom_urls.urls'
fixtures = ['users.json', 'actions.json']
def setUp(self):
5 tests/admin_scripts/tests.py
View
@@ -1542,6 +1542,7 @@ def test_option_then_setting_then_option(self):
class StartProject(LiveServerTestCase, AdminScriptTestCase):
+ urls = 'admin_scripts.urls'
available_apps = [
'admin_scripts',
'django.contrib.auth',
@@ -1649,7 +1650,7 @@ def test_custom_project_template_from_tarball_to_alternative_location(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"
- 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']
testproject_dir = os.path.join(test_dir, 'urltestproject')
@@ -1662,7 +1663,7 @@ def test_custom_project_template_from_tarball_by_url(self):
def test_project_template_tarball_url(self):
"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']
testproject_dir = os.path.join(test_dir, 'urltestproject')
30 tests/admin_widgets/tests.py
View
@@ -184,13 +184,14 @@ class AdvisorAdmin(admin.ModelAdmin):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class AdminFormfieldForDBFieldWithRequestTests(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"]
+ urls = 'admin_widgets.urls'
def testFilterChoicesByRequestUser(self):
"""
Ensure the user can only see their own cars in the foreign key dropdown.
"""
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.assertContains(response, "Volkswagon Passat")
@@ -198,7 +199,7 @@ def testFilterChoicesByRequestUser(self):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class AdminForeignKeyWidgetChangeList(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"]
- admin_root = '/widget_admin'
+ urls = 'admin_widgets.urls'
def setUp(self):
self.client.login(username="super", password="secret")
@@ -207,14 +208,14 @@ def tearDown(self):
self.client.logout()
def test_changelist_foreignkey(self):
- response = self.client.get('%s/admin_widgets/car/' % self.admin_root)
- self.assertContains(response, '%s/auth/user/add/' % self.admin_root)
+ response = self.client.get('/admin_widgets/car/')
+ self.assertContains(response, '/auth/user/add/')
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class AdminForeignKeyRawIdWidget(DjangoTestCase):
fixtures = ["admin-widgets-users.xml"]
- admin_root = '/widget_admin'
+ urls = 'admin_widgets.urls'
def setUp(self):
self.client.login(username="super", password="secret")
@@ -231,8 +232,7 @@ def test_nonexistent_target_id(self):
}
# Try posting with a non-existent pk in a raw id field: this
# should result in an error message, not a server exception.
- response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root,
- post_data)
+ response = self.client.post('/admin_widgets/event/add/', post_data)
self.assertContains(response,
'Select a valid choice. That choice is not one of the available choices.')
@@ -240,7 +240,7 @@ def test_invalid_target_id(self):
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.
- response = self.client.post('%s/admin_widgets/event/add/' % self.admin_root,
+ response = self.client.post('/admin_widgets/event/add/',
{"main_band": test_str})
self.assertContains(response,
@@ -392,6 +392,8 @@ def test_render(self):
class ForeignKeyRawIdWidgetTest(DjangoTestCase):
+ urls = 'admin_widgets.urls'
+
def test_render(self):
band = models.Band.objects.create(name='Linkin Park')
band.album_set.create(
@@ -402,7 +404,7 @@ def test_render(self):
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
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):
@@ -417,7 +419,7 @@ def test_relations_to_non_primary_key(self):
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
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):
@@ -459,11 +461,13 @@ def test_proper_manager_for_label_lookup(self):
)
self.assertHTMLEqual(
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):
+ urls = 'admin_widgets.urls'
+
def test_render(self):
band = models.Band.objects.create(name='Linkin Park')
@@ -475,12 +479,12 @@ def test_render(self):
w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
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(
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):
2  tests/contenttypes_tests/models.py
View
@@ -12,7 +12,7 @@ def __str__(self):
return self.name
def get_absolute_url(self):
- return '/views/authors/%s/' % self.id
+ return '/authors/%s/' % self.id
@python_2_unicode_compatible
32 tests/file_uploads/tests.py
View
@@ -29,6 +29,8 @@
@override_settings(MEDIA_ROOT=MEDIA_ROOT)
class FileUploadTests(TestCase):
+ urls = 'file_uploads.urls'
+
@classmethod
def setUpClass(cls):
if not os.path.isdir(MEDIA_ROOT):
@@ -44,7 +46,7 @@ def test_simple_upload(self):
'name': 'Ringo',
'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)
def test_large_upload(self):
@@ -71,7 +73,7 @@ def test_large_upload(self):
except AttributeError:
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)
@@ -87,7 +89,7 @@ def _test_base64_upload(self, content):
r = {
'CONTENT_LENGTH': len(payload),
'CONTENT_TYPE': client.MULTIPART_CONTENT,
- 'PATH_INFO': "/file_uploads/echo_content/",
+ 'PATH_INFO': "/echo_content/",
'REQUEST_METHOD': 'POST',
'wsgi.input': payload,
}
@@ -115,7 +117,7 @@ def test_unicode_file_name(self):
'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)
@@ -154,7 +156,7 @@ def test_dangerous_file_names(self):
r = {
'CONTENT_LENGTH': len(payload),
'CONTENT_TYPE': client.MULTIPART_CONTENT,
- 'PATH_INFO': "/file_uploads/echo/",
+ 'PATH_INFO': "/echo/",
'REQUEST_METHOD': 'POST',
'wsgi.input': payload,
}
@@ -191,7 +193,7 @@ def test_filename_overflow(self):
r = {
'CONTENT_LENGTH': len(payload),
'CONTENT_TYPE': client.MULTIPART_CONTENT,
- 'PATH_INFO': "/file_uploads/echo/",
+ 'PATH_INFO': "/echo/",
'REQUEST_METHOD': 'POST',
'wsgi.input': payload,
}
@@ -215,7 +217,7 @@ def test_content_type_extra(self):
simple_file.seek(0)
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,
'simple_file': simple_file,
})
@@ -242,7 +244,7 @@ def test_truncated_multipart_handled_gracefully(self):
r = {
'CONTENT_LENGTH': len(payload),
'CONTENT_TYPE': client.MULTIPART_CONTENT,
- 'PATH_INFO': '/file_uploads/echo/',
+ 'PATH_INFO': '/echo/',
'REQUEST_METHOD': 'POST',
'wsgi.input': payload,
}
@@ -257,7 +259,7 @@ def test_empty_multipart_handled_gracefully(self):
r = {
'CONTENT_LENGTH': 0,
'CONTENT_TYPE': client.MULTIPART_CONTENT,
- 'PATH_INFO': '/file_uploads/echo/',
+ 'PATH_INFO': '/echo/',
'REQUEST_METHOD': 'POST',
'wsgi.input': client.FakePayload(b''),
}
@@ -276,12 +278,12 @@ def test_custom_upload_handler(self):
bigfile.seek(0)
# 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'))
self.assertTrue('f' in got)
# 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'))
self.assertTrue('f' not in got)
@@ -294,7 +296,7 @@ def test_broken_custom_upload_handler(self):
self.assertRaises(
AttributeError,
self.client.post,
- '/file_uploads/quota/broken/',
+ '/quota/broken/',
{'f': f}
)
@@ -311,7 +313,7 @@ def test_fileupload_getlist(self):
file2a.write(b'a' * (5 * 2 ** 20))
file2a.seek(0)
- response = self.client.post('/file_uploads/getlist_count/', {
+ response = self.client.post('/getlist_count/', {
'file1': file1,
'field1': 'test',
'field2': 'test3',
@@ -357,7 +359,7 @@ def handle_uncaught_exception(self, request, resolver, exc_info):
'file_field': fp,
}
try:
- self.client.post('/file_uploads/upload_errors/', post_data)
+ self.client.post('/upload_errors/', post_data)
except reference_error.__class__ as err:
self.assertFalse(
str(err) == str(reference_error),
@@ -386,7 +388,7 @@ def test_filename_case_preservation(self):
'--%(boundary)s--\r\n',
]
response = self.client.post(
- '/file_uploads/filename_case/',
+ '/filename_case/',
'\r\n'.join(post_data) % vars,
'multipart/form-data; boundary=%(boundary)s' % vars
)
6 tests/middleware/extra_urls.py
View
@@ -1,7 +1,7 @@
from django.conf.urls import patterns
urlpatterns = patterns('',
- (r'^middleware/customurlconf/noslash$', 'view'),
- (r'^middleware/customurlconf/slash/$', 'view'),
- (r'^middleware/customurlconf/needsquoting#/$', 'view'),
+ (r'^customurlconf/noslash$', 'view'),
+ (r'^customurlconf/slash/$', 'view'),
+ (r'^customurlconf/needsquoting#/$', 'view'),
)
23 tests/middleware/tests.py
View
@@ -28,6 +28,7 @@
class CommonMiddlewareTest(TestCase):
+ urls = 'middleware.urls'
def _get_request(self, path):
request = HttpRequest()
@@ -35,7 +36,7 @@ def _get_request(self, path):
'SERVER_NAME': 'testserver',
'SERVER_PORT': 80,
}
- request.path = request.path_info = "/middleware/%s" % path
+ request.path = request.path_info = "/%s" % path
return request
@override_settings(APPEND_SLASH=True)
@@ -70,7 +71,7 @@ def test_append_slash_redirect(self):
request = self._get_request('slash')
r = CommonMiddleware().process_request(request)
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)
def test_append_slash_no_redirect_on_POST_in_DEBUG(self):
@@ -103,7 +104,7 @@ def test_append_slash_quoted(self):
self.assertEqual(r.status_code, 301)
self.assertEqual(
r.url,
- 'http://testserver/middleware/needsquoting%23/')
+ 'http://testserver/needsquoting%23/')
@override_settings(APPEND_SLASH=False, PREPEND_WWW=True)
def test_prepend_www(self):
@@ -112,7 +113,7 @@ def test_prepend_www(self):
self.assertEqual(r.status_code, 301)
self.assertEqual(
r.url,
- 'http://www.testserver/middleware/path/')
+ 'http://www.testserver/path/')
@override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_have_slash(self):
@@ -120,7 +121,7 @@ def test_prepend_www_append_slash_have_slash(self):
r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301)
self.assertEqual(r.url,
- 'http://www.testserver/middleware/slash/')
+ 'http://www.testserver/slash/')
@override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_slashless(self):
@@ -128,7 +129,7 @@ def test_prepend_www_append_slash_slashless(self):
r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301)
self.assertEqual(r.url,
- 'http://www.testserver/middleware/slash/')
+ 'http://www.testserver/slash/')
# The following tests examine expected behavior given a custom urlconf that
# overrides the default one through the request object.
@@ -171,7 +172,7 @@ def test_append_slash_redirect_custom_urlconf(self):
self.assertFalse(r is None,
"CommonMiddlware failed to return APPEND_SLASH redirect using request.urlconf")
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)
def test_append_slash_no_redirect_on_POST_in_DEBUG_custom_urlconf(self):
@@ -209,7 +210,7 @@ def test_append_slash_quoted_custom_urlconf(self):
self.assertEqual(r.status_code, 301)
self.assertEqual(
r.url,
- 'http://testserver/middleware/customurlconf/needsquoting%23/')
+ 'http://testserver/customurlconf/needsquoting%23/')
@override_settings(APPEND_SLASH=False, PREPEND_WWW=True)
def test_prepend_www_custom_urlconf(self):
@@ -219,7 +220,7 @@ def test_prepend_www_custom_urlconf(self):
self.assertEqual(r.status_code, 301)
self.assertEqual(
r.url,
- 'http://www.testserver/middleware/customurlconf/path/')
+ 'http://www.testserver/customurlconf/path/')
@override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_have_slash_custom_urlconf(self):
@@ -228,7 +229,7 @@ def test_prepend_www_append_slash_have_slash_custom_urlconf(self):
r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301)
self.assertEqual(r.url,
- 'http://www.testserver/middleware/customurlconf/slash/')
+ 'http://www.testserver/customurlconf/slash/')
@override_settings(APPEND_SLASH=True, PREPEND_WWW=True)
def test_prepend_www_append_slash_slashless_custom_urlconf(self):
@@ -237,7 +238,7 @@ def test_prepend_www_append_slash_slashless_custom_urlconf(self):
r = CommonMiddleware().process_request(request)
self.assertEqual(r.status_code, 301)
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)
4 tests/resolve_url/tests.py
View
@@ -1,10 +1,9 @@
from __future__ import unicode_literals
-from unittest import TestCase
-
from django.core.urlresolvers import NoReverseMatch
from django.contrib.auth.views import logout
from django.shortcuts import resolve_url
+from django.test import TestCase
from .models import UnimportantThing
@@ -13,6 +12,7 @@ class ResolveUrlTests(TestCase):
"""
Tests for the ``resolve_url`` function.
"""
+ urls = 'resolve_url.urls'
def test_url_path(self):
"""
6 tests/resolve_url/urls.py
View
@@ -0,0 +1,6 @@
+from django.conf.urls import patterns
+
+
+urlpatterns = patterns('',
+ (r'^accounts/logout/$', 'django.contrib.auth.views.logout')
+)
48 tests/template_tests/tests.py
View
@@ -550,6 +550,8 @@ def test_super_errors(self):
os.path.dirname(os.path.abspath(upath(__file__))),),
)
class TemplateTests(TransRealMixin, TestCase):
+ urls = 'template_tests.urls'
+
def test_templates(self):
template_tests = self.get_template_tests()
filter_tests = filters.get_filter_tests()
@@ -1701,28 +1703,28 @@ def get_template_tests(self):
### URL TAG ########################################################
# Successes
- 'url01': ('{% url "template_tests.views.client" client.id %}', {'client': {'id': 1}}, '/url_tag/client/1/'),
- 'url02': ('{% url "template_tests.views.client_action" id=client.id action="update" %}', {'client': {'id': 1}}, '/url_tag/client/1/update/'),
- 'url02a': ('{% url "template_tests.views.client_action" client.id "update" %}', {'client': {'id': 1}}, '/url_tag/client/1/update/'),
- 'url02b': ("{% url 'template_tests.views.client_action' id=client.id action='update' %}", {'client': {'id': 1}}, '/url_tag/client/1/update/'),
- 'url02c': ("{% url 'template_tests.views.client_action' client.id 'update' %}", {'client': {'id': 1}}, '/url_tag/client/1/update/'),
- 'url03': ('{% url "template_tests.views.index" %}', {}, '/url_tag/'),
- 'url04': ('{% url "named.client" client.id %}', {'client': {'id': 1}}, '/url_tag/named-client/1/'),
- 'url05': ('{% url "метка_оператора" v %}', {'v': 'Ω'}, '/url_tag/%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/'),
- '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/'),
- 'url08': ('{% url "метка_оператора" v %}', {'v': 'Ω'}, '/url_tag/%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/'),
- 'url10': ('{% url "template_tests.views.client_action" id=client.id action="two words" %}', {'client': {'id': 1}}, '/url_tag/client/1/two%20words/'),
- 'url11': ('{% url "template_tests.views.client_action" id=client.id action="==" %}', {'client': {'id': 1}}, '/url_tag/client/1/%3D%3D/'),
- 'url12': ('{% url "template_tests.views.client_action" id=client.id action="," %}', {'client': {'id': 1}}, '/url_tag/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/'),
- 'url14': ('{% url "template_tests.views.client_action" client.id arg|join:"-" %}', {'client': {'id': 1}, 'arg': ['a', 'b']}, '/url_tag/client/1/a-b/'),
- 'url15': ('{% url "template_tests.views.client_action" 12 "test" %}', {}, '/url_tag/client/12/test/'),
- 'url18': ('{% url "template_tests.views.client" "1,2" %}', {}, '/url_tag/client/1%2C2/'),
-
- 'url19': ('{% url named_url client.id %}', {'named_url': 'template_tests.views.client', 'client': {'id': 1}}, '/url_tag/client/1/'),
- 'url20': ('{% url url_name_in_var client.id %}', {'url_name_in_var': 'named.client', 'client': {'id': 1}}, '/url_tag/named-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}}, '/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}}, '/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" %}', {}, '/'),
+ 'url04': ('{% url "named.client" client.id %}', {'client': {'id': 1}}, '/named-client/1/'),
+ 'url05': ('{% url "метка_оператора" v %}', {'v': 'Ω'}, '/%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': 'Ω'}, '/%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': 'Ω'}, '/%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}}, '/client/1/two%20words/'),
+ '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}}, '/client/1/%2C/'),
+ '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']}, '/client/1/a-b/'),
+ 'url15': ('{% url "template_tests.views.client_action" 12 "test" %}', {}, '/client/12/test/'),
+ '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}}, '/client/1/'),
+ 'url20': ('{% url url_name_in_var client.id %}', {'url_name_in_var': 'named.client', 'client': {'id': 1}}, '/named-client/1/'),
# Failures
'url-fail01': ('{% url %}', {}, template.TemplateSyntaxError),
@@ -1747,7 +1749,7 @@ def get_template_tests(self):
# {% url ... as var %}
'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 }}', {}, ''),
### CACHE TAG ######################################################
141 tests/test_client/tests.py
View
@@ -32,13 +32,14 @@
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class ClientTest(TestCase):
fixtures = ['testdata.json']
+ urls = 'test_client.urls'
def test_get_view(self):
"GET a view"
# The data is ignored, but let's check it doesn't crash the system
# anyway.
data = {'var': '\xf2'}
- response = self.client.get('/test_client/get_view/', data)
+ response = self.client.get('/get_view/', data)
# Check some response details
self.assertContains(response, 'This is a test')
@@ -47,7 +48,7 @@ def test_get_view(self):
def test_get_post_view(self):
"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
self.assertEqual(response.status_code, 200)
@@ -57,7 +58,7 @@ def test_get_post_view(self):
def test_empty_post(self):
"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
self.assertEqual(response.status_code, 200)
@@ -70,7 +71,7 @@ def test_post(self):
post_data = {
'value': 37
}
- response = self.client.post('/test_client/post_view/', post_data)
+ response = self.client.post('/post_view/', post_data)
# Check some response details
self.assertEqual(response.status_code, 200)
@@ -80,7 +81,7 @@ def test_post(self):
def test_response_headers(self):
"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')
@@ -90,7 +91,7 @@ def test_response_attached_request(self):
originating environ dict and a ``wsgi_request`` with the originating
``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, 'wsgi_request'))
@@ -101,7 +102,7 @@ def test_response_attached_request(self):
def test_raw_post(self):
"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>"""
- response = self.client.post("/test_client/raw_post_view/", test_doc,
+ response = self.client.post("/raw_post_view/", test_doc,
content_type="text/xml")
self.assertEqual(response.status_code, 200)
self.assertEqual(response.templates[0].name, "Book template")
@@ -109,81 +110,81 @@ def test_raw_post(self):
def test_insecure(self):
"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.assertEqual(response.test_server_port, '80')
def test_secure(self):
"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.assertEqual(response.test_server_port, '443')
def test_redirect(self):
"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
# assertRedirect() understands to put an implicit http://testserver/ in
# front of non-absolute URLs.
- self.assertRedirects(response, '/test_client/get_view/')
+ self.assertRedirects(response, '/get_view/')
host = 'django.testserver'
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
- self.assertRedirects(response, '/test_client/get_view/', host=host)
+ self.assertRedirects(response, '/get_view/', host=host)
def test_redirect_with_query(self):
"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
- 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):
"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)
- 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')
- 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
- 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):
"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)
- 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):
"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
# 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):
"A URL that redirects can be followed to termination."
- response = self.client.get('/test_client/double_redirect_view/', follow=True)
- self.assertRedirects(response, 'http://testserver/test_client/get_view/', status_code=302, target_status_code=200)
+ response = self.client.get('/double_redirect_view/', follow=True)
+ self.assertRedirects(response, 'http://testserver/get_view/', status_code=302, target_status_code=200)
self.assertEqual(len(response.redirect_chain), 2)
def test_redirect_http(self):
"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)
def test_redirect_https(self):
"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)
def test_notfound_response(self):
"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
self.assertContains(response, 'MAGIC', status_code=404)
@@ -197,7 +198,7 @@ def test_valid_form(self):
'single': 'b',
'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.assertTemplateUsed(response, "Valid POST Template")
@@ -207,7 +208,7 @@ def test_valid_form_with_hints(self):
'text': 'Hello World',
'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.assertTemplateUsed(response, "Form GET Template")
# Check that the multi-value data has been rolled out ok
@@ -219,7 +220,7 @@ def test_incomplete_data_form(self):
'text': 'Hello World',
'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.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, "Invalid POST Template")
@@ -237,7 +238,7 @@ def test_form_error(self):
'single': 'b',
'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.assertTemplateUsed(response, "Invalid POST Template")
@@ -252,7 +253,7 @@ def test_valid_form_with_template(self):
'single': 'b',
'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.assertTemplateUsed(response, "form_view.html")
self.assertTemplateUsed(response, 'base.html')
@@ -264,7 +265,7 @@ def test_incomplete_data_form_with_template(self):
'text': 'Hello World',
'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.assertTemplateUsed(response, 'form_view.html')
self.assertTemplateUsed(response, 'base.html')
@@ -283,7 +284,7 @@ def test_form_error_with_template(self):
'single': 'b',
'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.assertTemplateUsed(response, "form_view.html")
self.assertTemplateUsed(response, 'base.html')
@@ -293,31 +294,31 @@ def test_form_error_with_template(self):
def test_unknown_page(self):
"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
self.assertEqual(response.status_code, 404)
def test_url_parameters(self):
"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)
- 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):
"Request a page that is protected with @login_required"
# Get the page without logging in. Should result in 302.
- response = self.client.get('/test_client/login_protected_view/')
- self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_view/')
+ response = self.client.get('/login_protected_view/')
+ self.assertRedirects(response, 'http://testserver/accounts/login/?next=/login_protected_view/')
# Log in
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in')
# 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.context['user'].username, 'testclient')
@@ -325,15 +326,15 @@ def test_view_with_method_login(self):
"Request a page that is protected with a @login_required method"
# Get the page without logging in. Should result in 302.
- response = self.client.get('/test_client/login_protected_method_view/')
- self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_method_view/')
+ response = self.client.get('/login_protected_method_view/')
+ self.assertRedirects(response, 'http://testserver/accounts/login/?next=/login_protected_method_view/')
# Log in
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in')
# 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.context['user'].username, 'testclient')
@@ -341,15 +342,15 @@ def test_view_with_login_and_custom_redirect(self):
"Request a page that is protected with @login_required(redirect_field_name='redirect_to')"
# Get the page without logging in. Should result in 302.
- response = self.client.get('/test_client/login_protected_view_custom_redirect/')
- self.assertRedirects(response, 'http://testserver/accounts/login/?redirect_to=/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=/login_protected_view_custom_redirect/')
# Log in
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in')
# 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.context['user'].username, 'testclient')
@@ -371,7 +372,7 @@ def test_logout(self):
self.client.login(username='testclient', password='password')
# 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.context['user'].username, 'testclient')
@@ -379,8 +380,8 @@ def test_logout(self):
self.client.logout()
# Request a page that requires a login
- response = self.client.get('/test_client/login_protected_view/')
- self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/login_protected_view/')
+ response = self.client.get('/login_protected_view/')
+ self.assertRedirects(response, 'http://testserver/accounts/login/?next=/login_protected_view/')
@override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies")
def test_logout_cookie_sessions(self):
@@ -390,16 +391,16 @@ def test_view_with_permissions(self):
"Request a page that is protected with @permission_required"
# Get the page without logging in. Should result in 302.
- response = self.client.get('/test_client/permission_protected_view/')
- self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_view/')
+ response = self.client.get('/permission_protected_view/')
+ self.assertRedirects(response, 'http://testserver/accounts/login/?next=/permission_protected_view/')
# Log in
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in')
# Log in with wrong permissions. Should result in 302.
- response = self.client.get('/test_client/permission_protected_view/')
- self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_view/')
+ response = self.client.get('/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
@@ -407,7 +408,7 @@ def test_view_with_permissions_exception(self):
"Request a page that is protected with @permission_required but raises a exception"
# 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)
# Log in
@@ -415,28 +416,28 @@ def test_view_with_permissions_exception(self):
self.assertTrue(login, 'Could not log in')
# 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)
def test_view_with_method_permissions(self):
"Request a page that is protected with a @permission_required method"
# Get the page without logging in. Should result in 302.
- response = self.client.get('/test_client/permission_protected_method_view/')
- self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/')
+ response = self.client.get('/permission_protected_method_view/')
+ self.assertRedirects(response, 'http://testserver/accounts/login/?next=/permission_protected_method_view/')
# Log in
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in')
# Log in with wrong permissions. Should result in 302.
- response = self.client.get('/test_client/permission_protected_method_view/')
- self.assertRedirects(response, 'http://testserver/accounts/login/?next=/test_client/permission_protected_method_view/')
+ response = self.client.get('/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
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)
def test_session_modifying_view(self):
@@ -448,18 +449,18 @@ def test_session_modifying_view(self):
except KeyError:
pass
- self.client.post('/test_client/session_view/')
+ self.client.post('/session_view/')
# Check that the session was modified
self.assertEqual(self.client.session['tobacconist'], 'hovercraft')
def test_view_with_exception(self):
"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:
- self.client.get('/test_client/broken_view/')
+ self.client.get('/broken_view/')
self.fail('Should raise an error')
except KeyError:
pass
@@ -467,7 +468,7 @@ def test_view_with_exception(self):
def test_mail_sending(self):
"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(len(mail.outbox), 1)
@@ -480,7 +481,7 @@ def test_mail_sending(self):
def test_mass_mail_sending(self):
"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(len(mail.outbox), 2)
@@ -501,16 +502,18 @@ def test_mass_mail_sending(self):
MIDDLEWARE_CLASSES=('django.middleware.csrf.CsrfViewMiddleware',)
)
class CSRFEnabledClientTests(TestCase):
+ urls = 'test_client.urls'
+
def test_csrf_enabled_client(self):
"A client can be instantiated with CSRF checks enabled"
csrf_client = Client(enforce_csrf_checks=True)
# 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)
# 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)
@@ -527,6 +530,8 @@ def test_custom_test_client(self):
class RequestFactoryTest(TestCase):
+ urls = 'test_client.urls'
+
def test_request_factory(self):
factory = RequestFactory()
request = factory.get('/somewhere/')
11 tests/test_client/urls.py
View
@@ -11,10 +11,10 @@
(r'^raw_post_view/$', views.raw_post_view),
(r'^redirect_view/$', views.redirect_view),
(r'^secure_view/$', views.view_with_secure),
- (r'^permanent_redirect_view/$', RedirectView.as_view(url='/test_client/get_view/')),
- (r'^temporary_redirect_view/$', RedirectView.as_view(url='/test_client/get_view/', permanent=False)),
- (r'^http_redirect_view/$', RedirectView.as_view(url='/test_client/secure_view/')),
- (r'^https_redirect_view/$', RedirectView.as_view(url='https://testserver/test_client/secure_view/')),
+ (r'^permanent_redirect_view/$', RedirectView.as_view(url='/get_view/')),
+ (r'^temporary_redirect_view/$', RedirectView.as_view(url='/get_view/', permanent=False)),
+ (r'^http_redirect_view/$', RedirectView.as_view(url='/secure_view/')),
+ (r'^https_redirect_view/$', RedirectView.as_view(url='https://testserver/secure_view/')),
(r'^double_redirect_view/$', views.double_redirect_view),
(r'^bad_view/$', views.bad_view),
(r'^form_view/$', views.form_view),
@@ -31,4 +31,7 @@
(r'^mail_sending_view/$', views.mail_sending_view),
(r'^mass_mail_sending_view/$', views.mass_mail_sending_view),
(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'),
)
4 tests/test_client/views.py
View
@@ -67,7 +67,7 @@ def redirect_view(request):
query = '?' + urlencode(request.GET, True)
else:
query = ''
- return HttpResponseRedirect('/test_client/get_view/' + query)
+ return HttpResponseRedirect('/get_view/' + query)
def view_with_secure(request):
@@ -80,7 +80,7 @@ def view_with_secure(request):
def double_redirect_view(request):
"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):
267 tests/test_client_regress/tests.py
View
@@ -8,7 +8,7 @@
import itertools
from django.conf import settings
-from django.core.urlresolvers import reverse
+from django.core.urlresolvers import reverse, NoReverseMatch
from django.template import (TemplateSyntaxError,
Context, Template, loader)
import django.template.context
@@ -30,9 +30,11 @@
TEMPLATE_DIRS=(os.path.join(os.path.dirname(upath(__file__)), 'templates'),)
)
class AssertContainsTests(TestCase):
+ urls = 'test_client_regress.urls'
+
def test_contains(self):
"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.assertContains(response, 'never', 0)
@@ -125,35 +127,35 @@ def test_contains(self):
def test_unicode_contains(self):
"Unicode characters can be found in template context"
# 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, b'\xe5\xb3\xa0'.decode('utf-8'))
def test_unicode_not_contains(self):
"Unicode characters can be searched for, and not found in template context"
# 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, b'\xe3\x81\xaf\xe3\x81\x9f\xe3\x81\x91'.decode('utf-8'))
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')
with self.assertRaises(AssertionError):
self.assertContains(r, b'%PDF-1.4\r\n%\x93\x8c\x8b\x9e', count=2)
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')
with self.assertRaises(AssertionError):
self.assertNotContains(r, b'%PDF-1.4\r\n%\x93\x8c\x8b\x9e')
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'))
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'))
def test_assert_contains_renders_template_response(self):
@@ -191,11 +193,12 @@ def test_assert_not_contains_using_non_template_response(self):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class AssertTemplateUsedTests(TestCase):
+ urls = 'test_client_regress.urls'
fixtures = ['testdata.json']
def test_no_context(self):
"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
self.assertTemplateNotUsed(response, 'GET Template')
@@ -212,7 +215,7 @@ def test_no_context(self):
def test_single_context(self):
"Template assertions work when there is a single context"
- response = self.client.get('/test_client/post_view/', {})
+ response = self.client.get('/post_view/', {})
try:
self.assertTemplateNotUsed(response, 'Empty GET Template')
@@ -243,7 +246,7 @@ def test_multiple_context(self):
'single': 'b',
'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')
try:
self.assertTemplateNotUsed(response, "form_view.html")
@@ -262,144 +265,146 @@ def test_multiple_context(self):
class AssertRedirectsTests(TestCase):
+ urls = 'test_client_regress.urls'
+
def test_redirect_page(self):
"An assertion is raised if the original page couldn't be retrieved as expected"
# 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:
- self.assertRedirects(response, '/test_client/get_view/')
+ self.assertRedirects(response, '/get_view/')
except AssertionError as e:
self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
try:
- self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
+ self.assertRedirects(response, '/get_view/', msg_prefix='abc')
except AssertionError as e:
self.assertIn("abc: Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
def test_lost_query(self):
"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:
- self.assertRedirects(response, '/test_client/get_view/')
+ self.assertRedirects(response, '/get_view/')
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:
- self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
+ self.assertRedirects(response, '/get_view/', msg_prefix='abc')
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):
"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:
# Should redirect to get_view
- self.assertRedirects(response, '/test_client/some_view/')
+ self.assertRedirects(response, '/some_view/')
except AssertionError as e:
self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
def test_target_page(self):
"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:
# 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:
- 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:
# 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:
- 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):
"You can follow a redirect chain of multiple redirects"
- response = self.client.get('/test_client_regress/redirects/further/more/', {}, follow=True)
- self.assertRedirects(response, '/test_client_regress/no_template_view/',
+ response = self.client.get('/redirects/further/more/', {}, follow=True)
+ self.assertRedirects(response, '/no_template_view/',
status_code=301, target_status_code=200)
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):
"You can follow a redirect chain of multiple redirects"
- response = self.client.get('/test_client_regress/redirects/', {}, follow=True)
- self.assertRedirects(response, '/test_client_regress/no_template_view/',
+ response = self.client.get('/redirects/', {}, follow=True)
+ self.assertRedirects(response, '/no_template_view/',
status_code=301, target_status_code=200)
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[1], ('http://testserver/test_client_regress/redirects/further/more/', 301))
- self.assertEqual(response.redirect_chain[2], ('http://testserver/test_client_regress/no_template_view/', 301))
+ self.assertEqual(response.redirect_chain[0], ('http://testserver/redirects/further/', 301))
+ self.assertEqual(response.redirect_chain[1], ('http://testserver/redirects/further/more/', 301))
+ self.assertEqual(response.redirect_chain[2], ('http://testserver/no_template_view/', 301))
def test_redirect_chain_to_non_existent(self):
"You can follow a chain to a non-existent view"
- response = self.client.get('/test_client_regress/redirect_to_non_existent_view2/', {}, follow=True)
- self.assertRedirects(response, '/test_client_regress/non_existent_view/',
+ response = self.client.get('/redirect_to_non_existent_view2/', {}, follow=True)
+ self.assertRedirects(response, '/non_existent_view/',
status_code=301, target_status_code=404)
def test_redirect_chain_to_self(self):
"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.
- self.assertRedirects(response, '/test_client_regress/redirect_to_self/',
+ self.assertRedirects(response, '/redirect_to_self/',
status_code=301, target_status_code=301)
self.assertEqual(len(response.redirect_chain), 2)
def test_circular_redirect(self):
"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.
- self.assertRedirects(response, '/test_client_regress/circular_redirect_2/',
+ self.assertRedirects(response, '/circular_redirect_2/',
status_code=301, target_status_code=301)
self.assertEqual(len(response.redirect_chain), 4)
def test_redirect_chain_post(self):
"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)
self.assertRedirects(response,
- '/test_client_regress/no_template_view/', 301, 200)
+ '/no_template_view/', 301, 200)
self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_head(self):
"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)
self.assertRedirects(response,
- '/test_client_regress/no_template_view/', 301, 200)
+ '/no_template_view/', 301, 200)
self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_options(self):
"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)
self.assertRedirects(response,
- '/test_client_regress/no_template_view/', 301, 200)
+ '/no_template_view/', 301, 200)
self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_put(self):
"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)
self.assertRedirects(response,
- '/test_client_regress/no_template_view/', 301, 200)
+ '/no_template_view/', 301, 200)
self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_chain_delete(self):
"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)
self.assertRedirects(response,
- '/test_client_regress/no_template_view/', 301, 200)
+ '/no_template_view/', 301, 200)
self.assertEqual(len(response.redirect_chain), 3)
def test_redirect_to_different_host(self):
"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,
- 'https://otherserver:8443/test_client_regress/no_template_view/',
+ 'https://otherserver:8443/no_template_view/',
status_code=301, target_status_code=200)
# We can't use is_secure() or get_host()
# because response.request is a dictionary, not an HttpRequest
@@ -410,28 +415,28 @@ def test_redirect_to_different_host(self):
def test_redirect_chain_on_non_redirect_page(self):
"An assertion is raised if the original page couldn't be retrieved as expected"
# 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:
- self.assertRedirects(response, '/test_client/get_view/')
+ self.assertRedirects(response, '/get_view/')
except AssertionError as e:
self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
try:
- self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
+ self.assertRedirects(response, '/get_view/', msg_prefix='abc')
except AssertionError as 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):
"An assertion is raised if the original page couldn't be retrieved as expected"
# This page will redirect with code 301, not 302
- response = self.client.get('/test_client/get_view/')
+ response = self.client.get('/get_view/')
try:
- self.assertRedirects(response, '/test_client/get_view/')
+ self.assertRedirects(response, '/get_view/')
except AssertionError as e:
self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
try:
- self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
+ self.assertRedirects(response, '/get_view/', msg_prefix='abc')
except AssertionError as e:
self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
@@ -439,22 +444,24 @@ def test_redirect_scheme(self):
"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
- response = self.client.get('/test_client/redirect_view/', secure=True)
- self.assertRedirects(response, 'https://testserver/test_client/get_view/')
+ response = self.client.get('/redirect_view/', secure=True)
+ self.assertRedirects(response, 'https://testserver/get_view/')
# For all possible True/False combinations of follow and secure
for follow, secure in itertools.product([True, False], repeat=2):
# 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
- self.assertRedirects(response, '/test_client/secure_view/', status_code=301)
+ self.assertRedirects(response, '/secure_view/', status_code=301)
# 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):
- 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):
+ urls = 'test_client_regress.urls'
+
def test_unknown_form(self):
"An assertion is raised if the form name is unknown"
post_data = {
@@ -464,7 +471,7 @@ def test_unknown_form(self):
'single': 'b',
'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.assertTemplateUsed(response, "Invalid POST Template")
@@ -486,7 +493,7 @@ def test_unknown_field(self):
'single': 'b',
'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.assertTemplateUsed(response, "Invalid POST Template")
@@ -508,7 +515,7 @@ def test_noerror_field(self):
'single': 'b',
'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.assertTemplateUsed(response, "Invalid POST Template")
@@ -530,7 +537,7 @@ def test_unknown_error(self):
'single': 'b',
'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.assertTemplateUsed(response, "Invalid POST Template")
@@ -555,7 +562,7 @@ def test_unknown_nonfield_error(self):
'single': 'b',
'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.assertTemplateUsed(response, "Invalid POST Template")
@@ -570,6 +577,7 @@ def test_unknown_nonfield_error(self):
class AssertFormsetErrorTests(TestCase):
+ urls = 'test_client_regress.urls'
msg_prefixes = [("", {}), ("abc: ", {"msg_prefix": "abc"})]
def setUp(self):
@@ -606,7 +614,7 @@ def setUp(self):
})
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.assertTemplateUsed(response, "Invalid POST Template")
return response
@@ -769,6 +777,7 @@ def process_request(self, request):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class LoginTests(TestCase):
+ urls = 'test_client_regress.urls'
fixtures = ['testdata']
def test_login_different_client(self):
@@ -780,12 +789,12 @@ def test_login_different_client(self):
self.assertTrue(login, 'Could not log in')
# 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.
# Check that assertRedirects uses the original client, not the
# default client.
- self.assertRedirects(response, "http://testserver/test_client_regress/get_view/")
+ self.assertRedirects(response, "http://testserver/get_view/")
@override_settings(
MIDDLEWARE_CLASSES=list(settings.MIDDLEWARE_CLASSES) +
@@ -811,6 +820,7 @@ def listener(sender, signal, **kwargs):
SESSION_ENGINE='test_client_regress.session'
)
class SessionEngineTests(TestCase):
+ urls = 'test_client_regress.urls'
fixtures = ['testdata']
def test_login(self):
@@ -819,12 +829,14 @@ def test_login(self):
self.assertTrue(login, 'Could not log in')
# 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.context['user'].username, 'testclient')
class URLEscapingTests(TestCase):
+ urls = 'test_client_regress.urls'
+
def test_simple_argument_get(self):
"Get a view that has a simple string argument"
response = self.client.get(reverse('arg_view', args=['Slartibartfast']))
@@ -852,6 +864,7 @@ def test_argument_with_space_post(self):
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class ExceptionTests(TestCase):
+ urls = 'test_client_regress.urls'
fixtures = ['testdata.json']
def test_exception_cleared(self):
@@ -860,7 +873,7 @@ def test_exception_cleared(self):
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in')
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")
except CustomTestException:
pass
@@ -871,12 +884,14 @@ def test_exception_cleared(self):
login = self.client.login(username='staff', password='password')
self.assertTrue(login, 'Could not log in')
try:
- self.client.get("/test_client_regress/staff_only/")
+ self.client.get("/staff_only/")
except CustomTestException:
self.fail("Staff should be able to visit this page")
class TemplateExceptionTests(TestCase):
+ urls = 'test_client_regress.urls'
+
def setUp(self):
# Reset the loaders so they don't try to render cached templates.
if loader.template_source_loaders is not None:
@@ -911,19 +926,24 @@ def test_urlconf_was_changed(self):
# This test needs to run *after* UrlconfSubstitutionTests; the zz prefix in the
# name is to ensure alphabetical ordering.
class zzUrlconfSubstitutionTests(TestCase):
+
def test_urlconf_was_reverted(self):
- "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/')
+ """URLconf is reverted to original value after modification in a TestCase
+
+ 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',))
class ContextTests(TestCase):
+ urls = 'test_client_regress.urls'
fixtures = ['testdata']
def test_single_context(self):
"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.assertTrue('get-foo' in response.context)
self.assertEqual(response.context['get-foo'], 'whiz')
@@ -938,7 +958,7 @@ def test_single_context(self):
def test_inherited_context(self):
"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(len(response.context), 2)
self.assertTrue('get-foo' in response.context)
@@ -973,8 +993,8 @@ def test_15368(self):
# copying RequestContext.
try:
django.template.context._standard_context_processors = (lambda request: {'path': request.special_path},)
- response = self.client.get("/test_client_regress/request_context_view/")
- self.assertContains(response, 'Path: /test_client_regress/request_context_view/')
+ response = self.client.get("/request_context_view/")
+ self.assertContains(response, 'Path: /request_context_view/')
finally:
django.template.context._standard_context_processors = None
@@ -982,29 +1002,30 @@ def test_nested_requests(self):
"""
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['nested'], 'yes')
@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
class SessionTests(TestCase):
+ urls = 'test_client_regress.urls'
fixtures = ['testdata.json']
def test_session(self):
"The session isn't lost if a user logs in"
# 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.content, b'NO')
# 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.content, b'set_session')
# 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.content, b'YES')
@@ -1013,7 +1034,7 @@ def test_session(self):
self.assertTrue(login, 'Could not log in')
# 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.content, b'YES')
@@ -1096,21 +1117,23 @@ def listener(*args, **kwargs):
class RequestMethodTests(TestCase):
+ urls = 'test_client_regress.urls'
+
def test_get(self):
"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.content, b'request method: GET')
def test_post(self):
"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.content, b'request method: POST')
def test_head(self):
"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)
# A HEAD request doesn't return any content.
self.assertNotEqual(response.content, b'request method: HEAD')
@@ -1118,35 +1141,37 @@ def test_head(self):
def test_options(self):
"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.content, b'request method: OPTIONS')
def test_put(self):
"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.content, b'request method: PUT')
def test_delete(self):
"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.content, b'request method: DELETE')
def test_patch(self):
"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.content, b'request method: PATCH')
class RequestMethodStringDataTests(TestCase):
+ urls = 'test_client_regress.urls'
+
def test_post(self):
"Request a view with string data via request method POST"
# Regression test for #11371
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.content, b'request method: POST')
@@ -1154,7 +1179,7 @@ def test_put(self):
"Request a view with string data via request method PUT"
# Regression test for #11371
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.content, b'request method: PUT')
@@ -1162,32 +1187,34 @@ def test_patch(self):
"Request a view with string data via request method PATCH"
# Regression test for #17797
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.content, b'request method: PATCH')
class QueryStringTests(TestCase):
+ urls = 'test_client_regress.urls'
+
def test_get_like_requests(self):
# See: https://code.djangoproject.com/ticket/10571.
for method_name in ('get', 'head'):
# A GET-like request can pass a query string as data
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['request-foo'], 'whiz')
# 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['request-foo'], 'whiz')
# 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['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-bar'], 'bang')
self.assertEqual(response.context['request-foo'], None)
@@ -1195,23 +1222,23 @@ def test_get_like_requests(self):
def test_post_like_requests(self):
# 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['post-foo'], 'whiz')