Refactored views regression tests to isolate generic views from the root URL space.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16000 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Russell Keith-Magee 2011-04-02 13:27:40 +00:00
parent 3b94af8a84
commit 29642fa76f
10 changed files with 219 additions and 193 deletions

View File

@ -0,0 +1,117 @@
# -*- coding:utf-8 -*-
from django.conf.urls.defaults import patterns, url
from models import *
import views
date_based_info_dict = {
'queryset': Article.objects.all(),
'date_field': 'date_created',
'month_format': '%m',
}
object_list_dict = {
'queryset': Article.objects.all(),
'paginate_by': 2,
}
object_list_no_paginate_by = {
'queryset': Article.objects.all(),
}
numeric_days_info_dict = dict(date_based_info_dict, day_format='%d')
date_based_datefield_info_dict = dict(date_based_info_dict, queryset=DateArticle.objects.all())
urlpatterns = patterns('',
(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
(r'^accounts/logout/$', 'django.contrib.auth.views.logout'),
# Special URLs for particular regression cases.
url(u'^中文/$', 'regressiontests.views.views.redirect'),
url(u'^中文/target/$', 'regressiontests.views.views.index_page'),
)
# Date-based generic views.
urlpatterns += patterns('django.views.generic.date_based',
(r'^date_based/object_detail/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$',
'object_detail',
dict(slug_field='slug', **date_based_info_dict)),
(r'^date_based/object_detail/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/allow_future/$',
'object_detail',
dict(allow_future=True, slug_field='slug', **date_based_info_dict)),
(r'^date_based/archive_day/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$',
'archive_day',
numeric_days_info_dict),
(r'^date_based/archive_month/(?P<year>\d{4})/(?P<month>\d{1,2})/$',
'archive_month',
date_based_info_dict),
(r'^date_based/datefield/archive_month/(?P<year>\d{4})/(?P<month>\d{1,2})/$',
'archive_month',
date_based_datefield_info_dict),
)
# crud generic views.
urlpatterns += patterns('django.views.generic.create_update',
(r'^create_update/member/create/article/$', 'create_object',
dict(login_required=True, model=Article)),
(r'^create_update/create/article/$', 'create_object',
dict(post_save_redirect='/create_update/view/article/%(slug)s/',
model=Article)),
(r'^create_update/update/article/(?P<slug>[-\w]+)/$', 'update_object',
dict(post_save_redirect='/create_update/view/article/%(slug)s/',
slug_field='slug', model=Article)),
(r'^create_update/create_custom/article/$', views.custom_create),
(r'^create_update/delete/article/(?P<slug>[-\w]+)/$', 'delete_object',
dict(post_delete_redirect='/create_update/', slug_field='slug',
model=Article)),
# No post_save_redirect and no get_absolute_url on model.
(r'^create_update/no_redirect/create/article/$', 'create_object',
dict(model=Article)),
(r'^create_update/no_redirect/update/article/(?P<slug>[-\w]+)/$',
'update_object', dict(slug_field='slug', model=Article)),
# get_absolute_url on model, but no passed post_save_redirect.
(r'^create_update/no_url/create/article/$', 'create_object',
dict(model=UrlArticle)),
(r'^create_update/no_url/update/article/(?P<slug>[-\w]+)/$',
'update_object', dict(slug_field='slug', model=UrlArticle)),
)
urlpatterns += patterns('django.views.generic.list_detail',
(r'^object_list/page(?P<page>[\w]*)/$', 'object_list', object_list_dict),
(r'^object_list_no_paginate_by/page(?P<page>[0-9]+)/$', 'object_list',
object_list_no_paginate_by),
)
# rediriects, both temporary and permanent, with non-ASCII targets
urlpatterns += patterns('django.views.generic.simple',
('^nonascii_redirect/$', 'redirect_to',
{'url': u'/中文/target/', 'permanent': False}),
('^permanent_nonascii_redirect/$', 'redirect_to',
{'url': u'/中文/target/', 'permanent': True}),
)
urlpatterns += patterns('regressiontests.views.views',
(r'^shortcuts/render_to_response/$', 'render_to_response_view'),
(r'^shortcuts/render_to_response/request_context/$', 'render_to_response_view_with_request_context'),
(r'^shortcuts/render_to_response/mimetype/$', 'render_to_response_view_with_mimetype'),
(r'^shortcuts/render/$', 'render_view'),
(r'^shortcuts/render/base_context/$', 'render_view_with_base_context'),
(r'^shortcuts/render/content_type/$', 'render_view_with_content_type'),
(r'^shortcuts/render/status/$', 'render_view_with_status'),
(r'^shortcuts/render/current_app/$', 'render_view_with_current_app'),
(r'^shortcuts/render/current_app_conflict/$', 'render_view_with_current_app_conflict'),
)
# simple generic views.
urlpatterns += patterns('django.views.generic.simple',
(r'^simple/redirect_to/$', 'redirect_to', dict(url='/simple/target/')),
(r'^simple/redirect_to_temp/$', 'redirect_to', dict(url='/simple/target/', permanent=False)),
(r'^simple/redirect_to_none/$', 'redirect_to', dict(url=None)),
(r'^simple/redirect_to_arg/(?P<id>\d+)/$', 'redirect_to', dict(url='/simple/target_arg/%(id)s/')),
(r'^simple/redirect_to_query/$', 'redirect_to', dict(url='/simple/target/', query_string=True)),
)

View File

@ -1,6 +1,5 @@
import inspect import inspect
import sys import sys
import warnings
from django.conf import settings from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile from django.core.files.uploadedfile import SimpleUploadedFile
@ -14,16 +13,6 @@ from regressiontests.views import BrokenException, except_args
class DebugViewTests(TestCase): class DebugViewTests(TestCase):
def setUp(self): def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.simple')
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.create_update')
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.date_based')
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.list_detail')
self.old_debug = settings.DEBUG self.old_debug = settings.DEBUG
settings.DEBUG = True settings.DEBUG = True
self.old_template_debug = settings.TEMPLATE_DEBUG self.old_template_debug = settings.TEMPLATE_DEBUG
@ -32,7 +21,6 @@ class DebugViewTests(TestCase):
def tearDown(self): def tearDown(self):
settings.DEBUG = self.old_debug settings.DEBUG = self.old_debug
settings.TEMPLATE_DEBUG = self.old_template_debug settings.TEMPLATE_DEBUG = self.old_template_debug
self.restore_warnings_state()
def test_files(self): def test_files(self):
response = self.client.get('/views/raises/') response = self.client.get('/views/raises/')

View File

@ -6,8 +6,8 @@ from django.core.exceptions import ImproperlyConfigured
from regressiontests.views.models import Article, UrlArticle from regressiontests.views.models import Article, UrlArticle
class CreateObjectTest(TestCase): class CreateObjectTest(TestCase):
fixtures = ['testdata.json'] fixtures = ['testdata.json']
urls = 'regressiontests.views.generic_urls'
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
@ -23,7 +23,7 @@ class CreateObjectTest(TestCase):
login_required view gets redirected to the login page and that login_required view gets redirected to the login page and that
an authenticated user is let through. an authenticated user is let through.
""" """
view_url = '/views/create_update/member/create/article/' view_url = '/create_update/member/create/article/'
response = self.client.get(view_url) response = self.client.get(view_url)
self.assertRedirects(response, '/accounts/login/?next=%s' % view_url) self.assertRedirects(response, '/accounts/login/?next=%s' % view_url)
# Now login and try again. # Now login and try again.
@ -37,7 +37,7 @@ class CreateObjectTest(TestCase):
""" """
Ensures the generic view returned the page and contains a form. Ensures the generic view returned the page and contains a form.
""" """
view_url = '/views/create_update/create/article/' view_url = '/create_update/create/article/'
response = self.client.get(view_url) response = self.client.get(view_url)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'views/article_form.html') self.assertTemplateUsed(response, 'views/article_form.html')
@ -48,7 +48,7 @@ class CreateObjectTest(TestCase):
""" """
POSTs a form that contains validation errors. POSTs a form that contains validation errors.
""" """
view_url = '/views/create_update/create/article/' view_url = '/create_update/create/article/'
num_articles = Article.objects.count() num_articles = Article.objects.count()
response = self.client.post(view_url, { response = self.client.post(view_url, {
'title': 'My First Article', 'title': 'My First Article',
@ -63,7 +63,7 @@ class CreateObjectTest(TestCase):
Creates a new article using a custom form class with a save method Creates a new article using a custom form class with a save method
that alters the slug entered. that alters the slug entered.
""" """
view_url = '/views/create_update/create_custom/article/' view_url = '/create_update/create_custom/article/'
response = self.client.post(view_url, { response = self.client.post(view_url, {
'title': 'Test Article', 'title': 'Test Article',
'slug': 'this-should-get-replaced', 'slug': 'this-should-get-replaced',
@ -71,12 +71,12 @@ class CreateObjectTest(TestCase):
'date_created': datetime.datetime(2007, 6, 25), 'date_created': datetime.datetime(2007, 6, 25),
}) })
self.assertRedirects(response, self.assertRedirects(response,
'/views/create_update/view/article/some-other-slug/', '/create_update/view/article/some-other-slug/',
target_status_code=404) target_status_code=404)
class UpdateDeleteObjectTest(TestCase): class UpdateDeleteObjectTest(TestCase):
fixtures = ['testdata.json'] fixtures = ['testdata.json']
urls = 'regressiontests.views.generic_urls'
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
@ -90,7 +90,7 @@ class UpdateDeleteObjectTest(TestCase):
""" """
Verifies that the form was created properly and with initial values. Verifies that the form was created properly and with initial values.
""" """
response = self.client.get('/views/create_update/update/article/old_article/') response = self.client.get('/create_update/update/article/old_article/')
self.assertTemplateUsed(response, 'views/article_form.html') self.assertTemplateUsed(response, 'views/article_form.html')
self.assertEqual(unicode(response.context['form']['title']), self.assertEqual(unicode(response.context['form']['title']),
u'<input id="id_title" type="text" name="title" value="Old Article" maxlength="100" />') u'<input id="id_title" type="text" name="title" value="Old Article" maxlength="100" />')
@ -99,7 +99,7 @@ class UpdateDeleteObjectTest(TestCase):
""" """
Verifies the updating of an Article. Verifies the updating of an Article.
""" """
response = self.client.post('/views/create_update/update/article/old_article/', { response = self.client.post('/create_update/update/article/old_article/', {
'title': 'Another Article', 'title': 'Another Article',
'slug': 'another-article-slug', 'slug': 'another-article-slug',
'author': 1, 'author': 1,
@ -112,14 +112,14 @@ class UpdateDeleteObjectTest(TestCase):
""" """
Verifies the confirm deletion page is displayed using a GET. Verifies the confirm deletion page is displayed using a GET.
""" """
response = self.client.get('/views/create_update/delete/article/old_article/') response = self.client.get('/create_update/delete/article/old_article/')
self.assertTemplateUsed(response, 'views/article_confirm_delete.html') self.assertTemplateUsed(response, 'views/article_confirm_delete.html')
def test_delete_object(self): def test_delete_object(self):
""" """
Verifies the object actually gets deleted on a POST. Verifies the object actually gets deleted on a POST.
""" """
view_url = '/views/create_update/delete/article/old_article/' view_url = '/create_update/delete/article/old_article/'
response = self.client.post(view_url) response = self.client.post(view_url)
try: try:
Article.objects.get(slug='old_article') Article.objects.get(slug='old_article')
@ -137,14 +137,15 @@ class PostSaveRedirectTests(TestCase):
fixtures = ['testdata.json'] fixtures = ['testdata.json']
article_model = Article article_model = Article
urls = 'regressiontests.views.generic_urls'
create_url = '/views/create_update/create/article/' create_url = '/create_update/create/article/'
update_url = '/views/create_update/update/article/old_article/' update_url = '/create_update/update/article/old_article/'
delete_url = '/views/create_update/delete/article/old_article/' delete_url = '/create_update/delete/article/old_article/'
create_redirect = '/views/create_update/view/article/my-first-article/' create_redirect = '/create_update/view/article/my-first-article/'
update_redirect = '/views/create_update/view/article/another-article-slug/' update_redirect = '/create_update/view/article/another-article-slug/'
delete_redirect = '/views/create_update/' delete_redirect = '/create_update/'
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
@ -194,9 +195,10 @@ class NoPostSaveNoAbsoluteUrl(PostSaveRedirectTests):
method exists on the Model that the view raises an ImproperlyConfigured method exists on the Model that the view raises an ImproperlyConfigured
error. error.
""" """
urls = 'regressiontests.views.generic_urls'
create_url = '/views/create_update/no_redirect/create/article/' create_url = '/create_update/no_redirect/create/article/'
update_url = '/views/create_update/no_redirect/update/article/old_article/' update_url = '/create_update/no_redirect/update/article/old_article/'
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
@ -226,12 +228,13 @@ class AbsoluteUrlNoPostSave(PostSaveRedirectTests):
Tests that the views redirect to the Model's get_absolute_url when no Tests that the views redirect to the Model's get_absolute_url when no
post_save_redirect is passed. post_save_redirect is passed.
""" """
urls = 'regressiontests.views.generic_urls'
# Article model with get_absolute_url method. # Article model with get_absolute_url method.
article_model = UrlArticle article_model = UrlArticle
create_url = '/views/create_update/no_url/create/article/' create_url = '/create_update/no_url/create/article/'
update_url = '/views/create_update/no_url/update/article/old_article/' update_url = '/create_update/no_url/update/article/old_article/'
create_redirect = '/urlarticles/my-first-article/' create_redirect = '/urlarticles/my-first-article/'
update_redirect = '/urlarticles/another-article-slug/' update_redirect = '/urlarticles/another-article-slug/'

View File

@ -8,6 +8,8 @@ from regressiontests.views.models import Article, Author, DateArticle
class ObjectDetailTest(TestCase): class ObjectDetailTest(TestCase):
fixtures = ['testdata.json'] fixtures = ['testdata.json']
urls = 'regressiontests.views.generic_urls'
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning, warnings.filterwarnings('ignore', category=DeprecationWarning,
@ -22,29 +24,31 @@ class ObjectDetailTest(TestCase):
def test_finds_past(self): def test_finds_past(self):
"date_based.object_detail can view a page in the past" "date_based.object_detail can view a page in the past"
response = self.client.get('/views/date_based/object_detail/2001/01/01/old_article/') response = self.client.get('/date_based/object_detail/2001/01/01/old_article/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['object'].title, "Old Article") self.assertEqual(response.context['object'].title, "Old Article")
def test_object_detail_finds_today(self): def test_object_detail_finds_today(self):
"date_based.object_detail can view a page from today" "date_based.object_detail can view a page from today"
today_url = datetime.now().strftime('%Y/%m/%d') today_url = datetime.now().strftime('%Y/%m/%d')
response = self.client.get('/views/date_based/object_detail/%s/current_article/' % today_url) response = self.client.get('/date_based/object_detail/%s/current_article/' % today_url)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['object'].title, "Current Article") self.assertEqual(response.context['object'].title, "Current Article")
def test_object_detail_ignores_future(self): def test_object_detail_ignores_future(self):
"date_based.object_detail can view a page from the future, but only if allowed." "date_based.object_detail can view a page from the future, but only if allowed."
response = self.client.get('/views/date_based/object_detail/3000/01/01/future_article/') response = self.client.get('/date_based/object_detail/3000/01/01/future_article/')
self.assertEqual(response.status_code, 404) self.assertEqual(response.status_code, 404)
def test_object_detail_allowed_future_if_enabled(self): def test_object_detail_allowed_future_if_enabled(self):
"date_based.object_detail can view a page from the future if explicitly allowed." "date_based.object_detail can view a page from the future if explicitly allowed."
response = self.client.get('/views/date_based/object_detail/3000/01/01/future_article/allow_future/') response = self.client.get('/date_based/object_detail/3000/01/01/future_article/allow_future/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['object'].title, "Future Article") self.assertEqual(response.context['object'].title, "Future Article")
class MonthArchiveTest(TestCase): class MonthArchiveTest(TestCase):
urls = 'regressiontests.views.generic_urls'
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning, warnings.filterwarnings('ignore', category=DeprecationWarning,
@ -66,52 +70,52 @@ class MonthArchiveTest(TestCase):
article.date_created = first_second_of_feb article.date_created = first_second_of_feb
article.save() article.save()
response = self.client.get('/views/date_based/archive_month/2004/02/') response = self.client.get('/date_based/archive_month/2004/02/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['next_month'], date(2004, 3, 1)) self.assertEqual(response.context['next_month'], date(2004, 3, 1))
self.assertEqual(response.context['previous_month'], date(2004, 1, 1)) self.assertEqual(response.context['previous_month'], date(2004, 1, 1))
article.date_created = first_second_of_feb-two_seconds article.date_created = first_second_of_feb-two_seconds
article.save() article.save()
response = self.client.get('/views/date_based/archive_month/2004/02/') response = self.client.get('/date_based/archive_month/2004/02/')
self.assertEqual(response.status_code, 404) self.assertEqual(response.status_code, 404)
article.date_created = first_second_of_mar-two_seconds article.date_created = first_second_of_mar-two_seconds
article.save() article.save()
response = self.client.get('/views/date_based/archive_month/2004/02/') response = self.client.get('/date_based/archive_month/2004/02/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['next_month'], date(2004, 3, 1)) self.assertEqual(response.context['next_month'], date(2004, 3, 1))
self.assertEqual(response.context['previous_month'], date(2004, 1, 1)) self.assertEqual(response.context['previous_month'], date(2004, 1, 1))
article.date_created = first_second_of_mar article.date_created = first_second_of_mar
article.save() article.save()
response = self.client.get('/views/date_based/archive_month/2004/02/') response = self.client.get('/date_based/archive_month/2004/02/')
self.assertEqual(response.status_code, 404) self.assertEqual(response.status_code, 404)
article2 = DateArticle(title="example", author=author) article2 = DateArticle(title="example", author=author)
article2.date_created = first_second_of_feb.date() article2.date_created = first_second_of_feb.date()
article2.save() article2.save()
response = self.client.get('/views/date_based/datefield/archive_month/2004/02/') response = self.client.get('/date_based/datefield/archive_month/2004/02/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['next_month'], date(2004, 3, 1)) self.assertEqual(response.context['next_month'], date(2004, 3, 1))
self.assertEqual(response.context['previous_month'], date(2004, 1, 1)) self.assertEqual(response.context['previous_month'], date(2004, 1, 1))
article2.date_created = (first_second_of_feb-two_seconds).date() article2.date_created = (first_second_of_feb-two_seconds).date()
article2.save() article2.save()
response = self.client.get('/views/date_based/datefield/archive_month/2004/02/') response = self.client.get('/date_based/datefield/archive_month/2004/02/')
self.assertEqual(response.status_code, 404) self.assertEqual(response.status_code, 404)
article2.date_created = (first_second_of_mar-two_seconds).date() article2.date_created = (first_second_of_mar-two_seconds).date()
article2.save() article2.save()
response = self.client.get('/views/date_based/datefield/archive_month/2004/02/') response = self.client.get('/date_based/datefield/archive_month/2004/02/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['next_month'], date(2004, 3, 1)) self.assertEqual(response.context['next_month'], date(2004, 3, 1))
self.assertEqual(response.context['previous_month'], date(2004, 1, 1)) self.assertEqual(response.context['previous_month'], date(2004, 1, 1))
article2.date_created = first_second_of_mar.date() article2.date_created = first_second_of_mar.date()
article2.save() article2.save()
response = self.client.get('/views/date_based/datefield/archive_month/2004/02/') response = self.client.get('/date_based/datefield/archive_month/2004/02/')
self.assertEqual(response.status_code, 404) self.assertEqual(response.status_code, 404)
now = datetime.now() now = datetime.now()
@ -122,7 +126,7 @@ class MonthArchiveTest(TestCase):
prev_month = prev_month.replace(month=prev_month.month-1) prev_month = prev_month.replace(month=prev_month.month-1)
article2.date_created = now article2.date_created = now
article2.save() article2.save()
response = self.client.get('/views/date_based/datefield/archive_month/%s/' % now.strftime('%Y/%m')) response = self.client.get('/date_based/datefield/archive_month/%s/' % now.strftime('%Y/%m'))
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['next_month'], None) self.assertEqual(response.context['next_month'], None)
self.assertEqual(response.context['previous_month'], prev_month) self.assertEqual(response.context['previous_month'], prev_month)
@ -134,16 +138,18 @@ class MonthArchiveTest(TestCase):
date2 = datetime(2010, 1, 2, 0, 0, 0) date2 = datetime(2010, 1, 2, 0, 0, 0)
Article.objects.create(title='example1', author=author, date_created=date1) Article.objects.create(title='example1', author=author, date_created=date1)
Article.objects.create(title='example2', author=author, date_created=date2) Article.objects.create(title='example2', author=author, date_created=date2)
response = self.client.get('/views/date_based/archive_month/2010/1/') response = self.client.get('/date_based/archive_month/2010/1/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(len(response.context['date_list']), 2) self.assertEqual(len(response.context['date_list']), 2)
self.assertEqual(response.context['date_list'][0], date1) self.assertEqual(response.context['date_list'][0], date1)
# Checks that the same date is not included more than once in the list # Checks that the same date is not included more than once in the list
Article.objects.create(title='example2', author=author, date_created=date2) Article.objects.create(title='example2', author=author, date_created=date2)
response = self.client.get('/views/date_based/archive_month/2010/1/') response = self.client.get('/date_based/archive_month/2010/1/')
self.assertEqual(len(response.context['date_list']), 2) self.assertEqual(len(response.context['date_list']), 2)
class DayArchiveTests(TestCase): class DayArchiveTests(TestCase):
urls = 'regressiontests.views.generic_urls'
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning, warnings.filterwarnings('ignore', category=DeprecationWarning,
@ -160,6 +166,6 @@ class DayArchiveTests(TestCase):
""" """
author = Author.objects.create(name="John Smith") author = Author.objects.create(name="John Smith")
article = Article.objects.create(title="example", author=author, date_created=datetime(2004, 1, 21, 0, 0, 1)) article = Article.objects.create(title="example", author=author, date_created=datetime(2004, 1, 21, 0, 0, 1))
response = self.client.get('/views/date_based/archive_day/2004/1/21/') response = self.client.get('/date_based/archive_day/2004/1/21/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['object_list'][0], article) self.assertEqual(response.context['object_list'][0], article)

View File

@ -5,10 +5,12 @@ from django.test import TestCase
class ObjectListTest(TestCase): class ObjectListTest(TestCase):
fixtures = ['testdata.json'] fixtures = ['testdata.json']
urls = 'regressiontests.views.generic_urls'
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning, warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.object_list') module='django.views.generic.list_detail')
def tearDown(self): def tearDown(self):
self.restore_warnings_state() self.restore_warnings_state()
@ -26,20 +28,20 @@ class ObjectListTest(TestCase):
def test_finds_pages(self): def test_finds_pages(self):
# Check page count doesn't start at 0. # Check page count doesn't start at 0.
self.check_pagination('/views/object_list/page0/', 404) self.check_pagination('/object_list/page0/', 404)
# Check basic pages. # Check basic pages.
self.check_pagination('/views/object_list/page/', 200, 2) self.check_pagination('/object_list/page/', 200, 2)
self.check_pagination('/views/object_list/page1/', 200, 2) self.check_pagination('/object_list/page1/', 200, 2)
self.check_pagination('/views/object_list/page2/', 200, 1) self.check_pagination('/object_list/page2/', 200, 1)
self.check_pagination('/views/object_list/page3/', 404) self.check_pagination('/object_list/page3/', 404)
# Check the special "last" page. # Check the special "last" page.
self.check_pagination('/views/object_list/pagelast/', 200, 1) self.check_pagination('/object_list/pagelast/', 200, 1)
self.check_pagination('/views/object_list/pagenotlast/', 404) self.check_pagination('/object_list/pagenotlast/', 404)
def test_no_paginate_by(self): def test_no_paginate_by(self):
# Ensure that the view isn't paginated by default. # Ensure that the view isn't paginated by default.
url = '/views/object_list_no_paginate_by/page1/' url = '/object_list_no_paginate_by/page1/'
response = self.check_pagination(url, 200) response = self.check_pagination(url, 200)
self.assertEqual(response.context['is_paginated'], False) self.assertEqual(response.context['is_paginated'], False)

View File

@ -4,6 +4,8 @@ import warnings
from django.test import TestCase from django.test import TestCase
class RedirectToTest(TestCase): class RedirectToTest(TestCase):
urls = 'regressiontests.views.generic_urls'
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning, warnings.filterwarnings('ignore', category=DeprecationWarning,
@ -14,34 +16,34 @@ class RedirectToTest(TestCase):
def test_redirect_to_returns_permanent_redirect(self): def test_redirect_to_returns_permanent_redirect(self):
"simple.redirect_to returns a permanent redirect (301) by default" "simple.redirect_to returns a permanent redirect (301) by default"
response = self.client.get('/views/simple/redirect_to/') response = self.client.get('/simple/redirect_to/')
self.assertEqual(response.status_code, 301) self.assertEqual(response.status_code, 301)
self.assertEqual('http://testserver/views/simple/target/', response['Location']) self.assertEqual('http://testserver/simple/target/', response['Location'])
def test_redirect_to_can_return_a_temporary_redirect(self): def test_redirect_to_can_return_a_temporary_redirect(self):
"simple.redirect_to returns a temporary redirect (302) when explicitely asked to" "simple.redirect_to returns a temporary redirect (302) when explicitely asked to"
response = self.client.get('/views/simple/redirect_to_temp/') response = self.client.get('/simple/redirect_to_temp/')
self.assertEqual(response.status_code, 302) self.assertEqual(response.status_code, 302)
self.assertEqual('http://testserver/views/simple/target/', response['Location']) self.assertEqual('http://testserver/simple/target/', response['Location'])
def test_redirect_to_on_empty_url_returns_gone(self): def test_redirect_to_on_empty_url_returns_gone(self):
"simple.redirect_to returns resource gone (410) when given a None url" "simple.redirect_to returns resource gone (410) when given a None url"
response = self.client.get('/views/simple/redirect_to_none/') response = self.client.get('/simple/redirect_to_none/')
self.assertEqual(response.status_code, 410) self.assertEqual(response.status_code, 410)
def test_redirect_to_allows_formatted_url_string(self): def test_redirect_to_allows_formatted_url_string(self):
"simple.redirect_to uses string interpolation on target url for keyword args" "simple.redirect_to uses string interpolation on target url for keyword args"
response = self.client.get('/views/simple/redirect_to_arg/42/') response = self.client.get('/simple/redirect_to_arg/42/')
self.assertEqual(response.status_code, 301) self.assertEqual(response.status_code, 301)
self.assertEqual('http://testserver/views/simple/target_arg/42/', response['Location']) self.assertEqual('http://testserver/simple/target_arg/42/', response['Location'])
def test_redirect_to_allows_query_string_to_be_passed(self): def test_redirect_to_allows_query_string_to_be_passed(self):
"simple.redirect_to configured with query_string=True passes on any query string" "simple.redirect_to configured with query_string=True passes on any query string"
# the default is to not forward the query string # the default is to not forward the query string
response = self.client.get('/views/simple/redirect_to/?param1=foo&param2=bar') response = self.client.get('/simple/redirect_to/?param1=foo&param2=bar')
self.assertEqual(response.status_code, 301) self.assertEqual(response.status_code, 301)
self.assertEqual('http://testserver/views/simple/target/', response['Location']) self.assertEqual('http://testserver/simple/target/', response['Location'])
# views configured with query_string=True however passes the query string along # views configured with query_string=True however passes the query string along
response = self.client.get('/views/simple/redirect_to_query/?param1=foo&param2=bar') response = self.client.get('/simple/redirect_to_query/?param1=foo&param2=bar')
self.assertEqual(response.status_code, 301) self.assertEqual(response.status_code, 301)
self.assertEqual('http://testserver/views/simple/target/?param1=foo&param2=bar', response['Location']) self.assertEqual('http://testserver/simple/target/?param1=foo&param2=bar', response['Location'])

View File

@ -4,6 +4,8 @@ from django.conf import settings
from django.test import TestCase from django.test import TestCase
class ShortcutTests(TestCase): class ShortcutTests(TestCase):
urls = 'regressiontests.views.generic_urls'
def setUp(self): def setUp(self):
self.save_warnings_state() self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning, warnings.filterwarnings('ignore', category=DeprecationWarning,
@ -25,51 +27,51 @@ class ShortcutTests(TestCase):
settings.TEMPLATE_CONTEXT_PROCESSORS = self.old_TEMPLATE_CONTEXT_PROCESSORS settings.TEMPLATE_CONTEXT_PROCESSORS = self.old_TEMPLATE_CONTEXT_PROCESSORS
def test_render_to_response(self): def test_render_to_response(self):
response = self.client.get('/views/shortcuts/render_to_response/') response = self.client.get('/shortcuts/render_to_response/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'FOO.BAR..\n') self.assertEqual(response.content, 'FOO.BAR..\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
def test_render_to_response_with_request_context(self): def test_render_to_response_with_request_context(self):
response = self.client.get('/views/shortcuts/render_to_response/request_context/') response = self.client.get('/shortcuts/render_to_response/request_context/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'FOO.BAR../path/to/static/media/\n') self.assertEqual(response.content, 'FOO.BAR../path/to/static/media/\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
def test_render_to_response_with_mimetype(self): def test_render_to_response_with_mimetype(self):
response = self.client.get('/views/shortcuts/render_to_response/mimetype/') response = self.client.get('/shortcuts/render_to_response/mimetype/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'FOO.BAR..\n') self.assertEqual(response.content, 'FOO.BAR..\n')
self.assertEqual(response['Content-Type'], 'application/x-rendertest') self.assertEqual(response['Content-Type'], 'application/x-rendertest')
def test_render(self): def test_render(self):
response = self.client.get('/views/shortcuts/render/') response = self.client.get('/shortcuts/render/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'FOO.BAR../path/to/static/media/\n') self.assertEqual(response.content, 'FOO.BAR../path/to/static/media/\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
self.assertEqual(response.context.current_app, None) self.assertEqual(response.context.current_app, None)
def test_render_with_base_context(self): def test_render_with_base_context(self):
response = self.client.get('/views/shortcuts/render/base_context/') response = self.client.get('/shortcuts/render/base_context/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'FOO.BAR..\n') self.assertEqual(response.content, 'FOO.BAR..\n')
self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8') self.assertEqual(response['Content-Type'], 'text/html; charset=utf-8')
def test_render_with_content_type(self): def test_render_with_content_type(self):
response = self.client.get('/views/shortcuts/render/content_type/') response = self.client.get('/shortcuts/render/content_type/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'FOO.BAR../path/to/static/media/\n') self.assertEqual(response.content, 'FOO.BAR../path/to/static/media/\n')
self.assertEqual(response['Content-Type'], 'application/x-rendertest') self.assertEqual(response['Content-Type'], 'application/x-rendertest')
def test_render_with_status(self): def test_render_with_status(self):
response = self.client.get('/views/shortcuts/render/status/') response = self.client.get('/shortcuts/render/status/')
self.assertEqual(response.status_code, 403) self.assertEqual(response.status_code, 403)
self.assertEqual(response.content, 'FOO.BAR../path/to/static/media/\n') self.assertEqual(response.content, 'FOO.BAR../path/to/static/media/\n')
def test_render_with_current_app(self): def test_render_with_current_app(self):
response = self.client.get('/views/shortcuts/render/current_app/') response = self.client.get('/shortcuts/render/current_app/')
self.assertEqual(response.context.current_app, "foobar_app") self.assertEqual(response.context.current_app, "foobar_app")
def test_render_with_current_app_conflict(self): def test_render_with_current_app_conflict(self):
self.assertRaises(ValueError, self.client.get, '/views/shortcuts/render/current_app_conflict/') self.assertRaises(ValueError, self.client.get, '/shortcuts/render/current_app_conflict/')

View File

@ -1,11 +1,23 @@
# coding: utf-8 # coding: utf-8
import warnings
from django.test import TestCase from django.test import TestCase
class URLHandling(TestCase): class URLHandling(TestCase):
""" """
Tests for URL handling in views and responses. Tests for URL handling in views and responses.
""" """
redirect_target = "/views/%E4%B8%AD%E6%96%87/target/" urls = 'regressiontests.views.generic_urls'
redirect_target = "/%E4%B8%AD%E6%96%87/target/"
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.simple')
def tearDown(self):
self.restore_warnings_state()
def test_combining_redirect(self): def test_combining_redirect(self):
""" """
@ -15,14 +27,14 @@ class URLHandling(TestCase):
characters so this test ensures the creation of the full path with a characters so this test ensures the creation of the full path with a
base non-ASCII part is handled correctly. base non-ASCII part is handled correctly.
""" """
response = self.client.get(u'/views/中文/') response = self.client.get(u'/中文/')
self.assertRedirects(response, self.redirect_target) self.assertRedirects(response, self.redirect_target)
def test_nonascii_redirect(self): def test_nonascii_redirect(self):
""" """
Tests that a non-ASCII argument to HttpRedirect is handled properly. Tests that a non-ASCII argument to HttpRedirect is handled properly.
""" """
response = self.client.get('/views/nonascii_redirect/') response = self.client.get('/nonascii_redirect/')
self.assertRedirects(response, self.redirect_target) self.assertRedirects(response, self.redirect_target)
def test_permanent_nonascii_redirect(self): def test_permanent_nonascii_redirect(self):
@ -30,6 +42,6 @@ class URLHandling(TestCase):
Tests that a non-ASCII argument to HttpPermanentRedirect is handled Tests that a non-ASCII argument to HttpPermanentRedirect is handled
properly. properly.
""" """
response = self.client.get('/views/permanent_nonascii_redirect/') response = self.client.get('/permanent_nonascii_redirect/')
self.assertRedirects(response, self.redirect_target, status_code=301) self.assertRedirects(response, self.redirect_target, status_code=301)

View File

@ -3,7 +3,6 @@ from os import path
from django.conf.urls.defaults import * from django.conf.urls.defaults import *
from models import *
import views import views
@ -31,25 +30,6 @@ js_info_dict_multi_packages2 = {
'packages': ('regressiontests.views.app3', 'regressiontests.views.app4'), 'packages': ('regressiontests.views.app3', 'regressiontests.views.app4'),
} }
date_based_info_dict = {
'queryset': Article.objects.all(),
'date_field': 'date_created',
'month_format': '%m',
}
object_list_dict = {
'queryset': Article.objects.all(),
'paginate_by': 2,
}
object_list_no_paginate_by = {
'queryset': Article.objects.all(),
}
numeric_days_info_dict = dict(date_based_info_dict, day_format='%d')
date_based_datefield_info_dict = dict(date_based_info_dict, queryset=DateArticle.objects.all())
urlpatterns = patterns('', urlpatterns = patterns('',
(r'^$', views.index_page), (r'^$', views.index_page),
@ -58,6 +38,10 @@ urlpatterns = patterns('',
(r'^non_existing_url/', 'django.views.defaults.page_not_found'), (r'^non_existing_url/', 'django.views.defaults.page_not_found'),
(r'^server_error/', 'django.views.defaults.server_error'), (r'^server_error/', 'django.views.defaults.server_error'),
# a view that raises an exception for the debug view
(r'^raises/$', views.raises),
(r'^raises404/$', views.raises404),
# i18n views # i18n views
(r'^i18n/', include('django.conf.urls.i18n')), (r'^i18n/', include('django.conf.urls.i18n')),
(r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict), (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
@ -67,100 +51,10 @@ urlpatterns = patterns('',
# Static views # Static views
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': media_dir}), (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': media_dir}),
# Special URLs for particular regression cases.
url(u'^中文/$', 'regressiontests.views.views.redirect'),
url(u'^中文/target/$', 'regressiontests.views.views.index_page'),
)
# Date-based generic views.
urlpatterns += patterns('django.views.generic.date_based',
(r'^date_based/object_detail/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/$',
'object_detail',
dict(slug_field='slug', **date_based_info_dict)),
(r'^date_based/object_detail/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>[-\w]+)/allow_future/$',
'object_detail',
dict(allow_future=True, slug_field='slug', **date_based_info_dict)),
(r'^date_based/archive_day/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/$',
'archive_day',
numeric_days_info_dict),
(r'^date_based/archive_month/(?P<year>\d{4})/(?P<month>\d{1,2})/$',
'archive_month',
date_based_info_dict),
(r'^date_based/datefield/archive_month/(?P<year>\d{4})/(?P<month>\d{1,2})/$',
'archive_month',
date_based_datefield_info_dict),
)
# crud generic views.
urlpatterns += patterns('django.views.generic.create_update',
(r'^create_update/member/create/article/$', 'create_object',
dict(login_required=True, model=Article)),
(r'^create_update/create/article/$', 'create_object',
dict(post_save_redirect='/views/create_update/view/article/%(slug)s/',
model=Article)),
(r'^create_update/update/article/(?P<slug>[-\w]+)/$', 'update_object',
dict(post_save_redirect='/views/create_update/view/article/%(slug)s/',
slug_field='slug', model=Article)),
(r'^create_update/create_custom/article/$', views.custom_create),
(r'^create_update/delete/article/(?P<slug>[-\w]+)/$', 'delete_object',
dict(post_delete_redirect='/views/create_update/', slug_field='slug',
model=Article)),
# No post_save_redirect and no get_absolute_url on model.
(r'^create_update/no_redirect/create/article/$', 'create_object',
dict(model=Article)),
(r'^create_update/no_redirect/update/article/(?P<slug>[-\w]+)/$',
'update_object', dict(slug_field='slug', model=Article)),
# get_absolute_url on model, but no passed post_save_redirect.
(r'^create_update/no_url/create/article/$', 'create_object',
dict(model=UrlArticle)),
(r'^create_update/no_url/update/article/(?P<slug>[-\w]+)/$',
'update_object', dict(slug_field='slug', model=UrlArticle)),
)
urlpatterns += patterns('django.views.generic.list_detail',
(r'^object_list/page(?P<page>[\w]*)/$', 'object_list', object_list_dict),
(r'^object_list_no_paginate_by/page(?P<page>[0-9]+)/$', 'object_list',
object_list_no_paginate_by),
)
# a view that raises an exception for the debug view
urlpatterns += patterns('',
(r'^raises/$', views.raises),
(r'^raises404/$', views.raises404),
)
# rediriects, both temporary and permanent, with non-ASCII targets
urlpatterns += patterns('django.views.generic.simple',
('^nonascii_redirect/$', 'redirect_to',
{'url': u'/views/中文/target/', 'permanent': False}),
('^permanent_nonascii_redirect/$', 'redirect_to',
{'url': u'/views/中文/target/', 'permanent': True}),
) )
urlpatterns += patterns('regressiontests.views.views', urlpatterns += patterns('regressiontests.views.views',
url(r'view_exception/(?P<n>\d+)/$', 'view_exception', name='view_exception'), url(r'view_exception/(?P<n>\d+)/$', 'view_exception', name='view_exception'),
url(r'template_exception/(?P<n>\d+)/$', 'template_exception', name='template_exception'), url(r'template_exception/(?P<n>\d+)/$', 'template_exception', name='template_exception'),
url(r'^raises_template_does_not_exist/$', 'raises_template_does_not_exist', name='raises_template_does_not_exist'), url(r'^raises_template_does_not_exist/$', 'raises_template_does_not_exist', name='raises_template_does_not_exist'),
(r'^shortcuts/render_to_response/$', 'render_to_response_view'),
(r'^shortcuts/render_to_response/request_context/$', 'render_to_response_view_with_request_context'),
(r'^shortcuts/render_to_response/mimetype/$', 'render_to_response_view_with_mimetype'),
(r'^shortcuts/render/$', 'render_view'),
(r'^shortcuts/render/base_context/$', 'render_view_with_base_context'),
(r'^shortcuts/render/content_type/$', 'render_view_with_content_type'),
(r'^shortcuts/render/status/$', 'render_view_with_status'),
(r'^shortcuts/render/current_app/$', 'render_view_with_current_app'),
(r'^shortcuts/render/current_app_conflict/$', 'render_view_with_current_app_conflict'),
)
# simple generic views.
urlpatterns += patterns('django.views.generic.simple',
(r'^simple/redirect_to/$', 'redirect_to', dict(url='/views/simple/target/')),
(r'^simple/redirect_to_temp/$', 'redirect_to', dict(url='/views/simple/target/', permanent=False)),
(r'^simple/redirect_to_none/$', 'redirect_to', dict(url=None)),
(r'^simple/redirect_to_arg/(?P<id>\d+)/$', 'redirect_to', dict(url='/views/simple/target_arg/%(id)s/')),
(r'^simple/redirect_to_query/$', 'redirect_to', dict(url='/views/simple/target/', query_string=True)),
) )

View File

@ -32,7 +32,7 @@ def custom_create(request):
from django.views.generic.create_update import create_object from django.views.generic.create_update import create_object
return create_object(request, return create_object(request,
post_save_redirect='/views/create_update/view/article/%(slug)s/', post_save_redirect='/create_update/view/article/%(slug)s/',
form_class=SlugChangingArticleForm) form_class=SlugChangingArticleForm)
def raises(request): def raises(request):