Updates to the test suite to allow for newly deprecated and removed features

git-svn-id: http://code.djangoproject.com/svn/django/trunk@15990 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Russell Keith-Magee 2011-04-02 08:44:47 +00:00
parent 603884505f
commit 4c468800ee
28 changed files with 255 additions and 298 deletions

View File

@ -0,0 +1,77 @@
# from django.conf import settings
from django.contrib.auth import authenticate
from django.db.models import Q
from django.test import TestCase
# from django.template import Template
class AuthContextProcessorTests(TestCase):
"""
Tests for the ``django.contrib.auth.context_processors.auth`` processor
"""
urls = 'regressiontests.context_processors.urls'
fixtures = ['context-processors-users.xml']
def test_session_not_accessed(self):
"""
Tests that the session is not accessed simply by including
the auth context processor
"""
response = self.client.get('/auth_processor_no_attr_access/')
self.assertContains(response, "Session not accessed")
def test_session_is_accessed(self):
"""
Tests that the session is accessed if the auth context processor
is used and relevant attributes accessed.
"""
response = self.client.get('/auth_processor_attr_access/')
self.assertContains(response, "Session accessed")
def test_perms_attrs(self):
self.client.login(username='super', password='secret')
response = self.client.get('/auth_processor_perms/')
self.assertContains(response, "Has auth permissions")
def test_message_attrs(self):
self.client.login(username='super', password='secret')
response = self.client.get('/auth_processor_messages/')
self.assertContains(response, "Message 1")
def test_user_attrs(self):
"""
Test that the lazy objects returned behave just like the wrapped objects.
"""
# These are 'functional' level tests for common use cases. Direct
# testing of the implementation (SimpleLazyObject) is in the 'utils'
# tests.
self.client.login(username='super', password='secret')
user = authenticate(username='super', password='secret')
response = self.client.get('/auth_processor_user/')
self.assertContains(response, "unicode: super")
self.assertContains(response, "id: 100")
self.assertContains(response, "username: super")
# bug #12037 is tested by the {% url %} in the template:
self.assertContains(response, "url: /userpage/super/")
# See if this object can be used for queries where a Q() comparing
# a user can be used with another Q() (in an AND or OR fashion).
# This simulates what a template tag might do with the user from the
# context. Note that we don't need to execute a query, just build it.
#
# The failure case (bug #12049) on Python 2.4 with a LazyObject-wrapped
# User is a fatal TypeError: "function() takes at least 2 arguments
# (0 given)" deep inside deepcopy().
#
# Python 2.5 and 2.6 succeeded, but logged internally caught exception
# spew:
#
# Exception RuntimeError: 'maximum recursion depth exceeded while
# calling a Python object' in <type 'exceptions.AttributeError'>
# ignored"
query = Q(user=response.context['user']) & Q(someflag=True)
# Tests for user equality. This is hard because User defines
# equality in a non-duck-typing way
# See bug #12060
self.assertEqual(response.context['user'], user)
self.assertEqual(user, response.context['user'])

View File

@ -1,4 +1,4 @@
from django.conf.urls.defaults import patterns
from django.conf.urls.defaults import patterns, url
from django.contrib.auth.urls import urlpatterns
from django.contrib.auth.views import password_reset
from django.contrib.auth.decorators import login_required
@ -13,6 +13,35 @@ def remote_user_auth_view(request):
c = RequestContext(request, {})
return HttpResponse(t.render(c))
def auth_processor_no_attr_access(request):
r1 = render_to_response('context_processors/auth_attrs_no_access.html',
RequestContext(request, {}, processors=[context_processors.auth]))
# *After* rendering, we check whether the session was accessed
return render_to_response('context_processors/auth_attrs_test_access.html',
{'session_accessed':request.session.accessed})
def auth_processor_attr_access(request):
r1 = render_to_response('context_processors/auth_attrs_access.html',
RequestContext(request, {}, processors=[context_processors.auth]))
return render_to_response('context_processors/auth_attrs_test_access.html',
{'session_accessed':request.session.accessed})
def auth_processor_user(request):
return render_to_response('context_processors/auth_attrs_user.html',
RequestContext(request, {}, processors=[context_processors.auth]))
def auth_processor_perms(request):
return render_to_response('context_processors/auth_attrs_perms.html',
RequestContext(request, {}, processors=[context_processors.auth]))
def auth_processor_messages(request):
request.user.message_set.create(message="Message 1")
return render_to_response('context_processors/auth_attrs_messages.html',
RequestContext(request, {}, processors=[context_processors.auth]))
def userpage(request):
pass
# special urls for auth test cases
urlpatterns = urlpatterns + patterns('',
(r'^logout/custom_query/$', 'django.contrib.auth.views.logout', dict(redirect_field_name='follow')),
@ -21,5 +50,12 @@ urlpatterns = urlpatterns + patterns('',
(r'^password_reset_from_email/$', 'django.contrib.auth.views.password_reset', dict(from_email='staffmember@example.com')),
(r'^login_required/$', login_required(password_reset)),
(r'^login_required_login_url/$', login_required(password_reset, login_url='/somewhere/')),
(r'^auth_processor_no_attr_access/$', auth_processor_no_attr_access),
(r'^auth_processor_attr_access/$', auth_processor_attr_access),
(r'^auth_processor_user/$', auth_processor_user),
(r'^auth_processor_perms/$', auth_processor_perms),
(r'^auth_processor_messages/$', auth_processor_messages),
url(r'^userpage/(.+)/$', userpage, name="userpage"),
)

View File

@ -3,9 +3,6 @@ from django.db import models
from django.utils import simplejson as json
from django.utils.encoding import force_unicode
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning, module='django.db.models.fields.subclassing')
class Small(object):
"""
A simple class to show that non-trivial Python objects can be used as

View File

@ -108,10 +108,12 @@ class AdminScriptTestCase(unittest.TestCase):
# Build the command line
executable = sys.executable
arg_string = ' '.join(['%s' % arg for arg in args])
# Silence the DeprecationWarning caused by having a locale directory
# in the project directory.
if ' ' in executable:
cmd = '""%s" "%s" %s"' % (executable, script, arg_string)
cmd = '""%s" -Wignore:::django.utils.translation "%s" %s"' % (executable, script, arg_string)
else:
cmd = '%s "%s" %s' % (executable, script, arg_string)
cmd = '%s -Wignore:::django.utils.translation "%s" %s' % (executable, script, arg_string)
# Move to the test directory and run
os.chdir(test_dir)

View File

@ -5,7 +5,7 @@ import datetime
from django.core.management.color import no_style
from django.db import backend, connection, connections, DEFAULT_DB_ALIAS, IntegrityError
from django.db.backends.signals import connection_created
from django.db.backends.postgresql import version as pg_version
from django.db.backends.postgresql_psycopg2 import version as pg_version
from django.test import TestCase, skipUnlessDBFeature, TransactionTestCase
from django.utils import unittest

View File

@ -17,17 +17,3 @@ class CommentFeedTests(CommentTestCase):
self.assertContains(response, '<title>example.com comments</title>')
self.assertContains(response, '<link>http://example.com/</link>')
self.assertContains(response, '</rss>')
class LegacyCommentFeedTests(CommentFeedTests):
feed_url = '/rss/legacy/comments/'
def setUp(self):
self._warnings_state = get_warnings_state()
warnings.filterwarnings("ignore", category=DeprecationWarning,
module='django.contrib.syndication.views')
warnings.filterwarnings("ignore", category=DeprecationWarning,
module='django.contrib.syndication.feeds')
def tearDown(self):
restore_warnings_state(self._warnings_state)

View File

@ -13,6 +13,5 @@ urlpatterns = patterns('regressiontests.comment_tests.custom_comments.views',
)
urlpatterns += patterns('',
(r'^rss/legacy/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': feeds}),
(r'^rss/comments/$', LatestCommentFeed()),
)

View File

@ -1,13 +1,8 @@
"""
Tests for Django's bundled context processors.
"""
import warnings
from django.conf import settings
from django.contrib.auth import authenticate
from django.db.models import Q
from django.test import TestCase
from django.template import Template
class RequestContextProcessorTests(TestCase):
"""
@ -40,84 +35,3 @@ class RequestContextProcessorTests(TestCase):
response = self.client.post(url, {'path': '/blah/'})
self.assertContains(response, url)
class AuthContextProcessorTests(TestCase):
"""
Tests for the ``django.contrib.auth.context_processors.auth`` processor
"""
urls = 'regressiontests.context_processors.urls'
fixtures = ['context-processors-users.xml']
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.contrib.auth.models')
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.core.context_processors')
def tearDown(self):
self.restore_warnings_state()
def test_session_not_accessed(self):
"""
Tests that the session is not accessed simply by including
the auth context processor
"""
response = self.client.get('/auth_processor_no_attr_access/')
self.assertContains(response, "Session not accessed")
def test_session_is_accessed(self):
"""
Tests that the session is accessed if the auth context processor
is used and relevant attributes accessed.
"""
response = self.client.get('/auth_processor_attr_access/')
self.assertContains(response, "Session accessed")
def test_perms_attrs(self):
self.client.login(username='super', password='secret')
response = self.client.get('/auth_processor_perms/')
self.assertContains(response, "Has auth permissions")
def test_message_attrs(self):
self.client.login(username='super', password='secret')
response = self.client.get('/auth_processor_messages/')
self.assertContains(response, "Message 1")
def test_user_attrs(self):
"""
Test that the lazy objects returned behave just like the wrapped objects.
"""
# These are 'functional' level tests for common use cases. Direct
# testing of the implementation (SimpleLazyObject) is in the 'utils'
# tests.
self.client.login(username='super', password='secret')
user = authenticate(username='super', password='secret')
response = self.client.get('/auth_processor_user/')
self.assertContains(response, "unicode: super")
self.assertContains(response, "id: 100")
self.assertContains(response, "username: super")
# bug #12037 is tested by the {% url %} in the template:
self.assertContains(response, "url: /userpage/super/")
# See if this object can be used for queries where a Q() comparing
# a user can be used with another Q() (in an AND or OR fashion).
# This simulates what a template tag might do with the user from the
# context. Note that we don't need to execute a query, just build it.
#
# The failure case (bug #12049) on Python 2.4 with a LazyObject-wrapped
# User is a fatal TypeError: "function() takes at least 2 arguments
# (0 given)" deep inside deepcopy().
#
# Python 2.5 and 2.6 succeeded, but logged internally caught exception
# spew:
#
# Exception RuntimeError: 'maximum recursion depth exceeded while
# calling a Python object' in <type 'exceptions.AttributeError'>
# ignored"
query = Q(user=response.context['user']) & Q(someflag=True)
# Tests for user equality. This is hard because User defines
# equality in a non-duck-typing way
# See bug #12060
self.assertEqual(response.context['user'], user)
self.assertEqual(user, response.context['user'])

View File

@ -5,10 +5,4 @@ import views
urlpatterns = patterns('',
(r'^request_attrs/$', views.request_processor),
(r'^auth_processor_no_attr_access/$', views.auth_processor_no_attr_access),
(r'^auth_processor_attr_access/$', views.auth_processor_attr_access),
(r'^auth_processor_user/$', views.auth_processor_user),
(r'^auth_processor_perms/$', views.auth_processor_perms),
(r'^auth_processor_messages/$', views.auth_processor_messages),
url(r'^userpage/(.+)/$', views.userpage, name="userpage"),
)

View File

@ -6,32 +6,3 @@ from django.template.context import RequestContext
def request_processor(request):
return render_to_response('context_processors/request_attrs.html',
RequestContext(request, {}, processors=[context_processors.request]))
def auth_processor_no_attr_access(request):
r1 = render_to_response('context_processors/auth_attrs_no_access.html',
RequestContext(request, {}, processors=[context_processors.auth]))
# *After* rendering, we check whether the session was accessed
return render_to_response('context_processors/auth_attrs_test_access.html',
{'session_accessed':request.session.accessed})
def auth_processor_attr_access(request):
r1 = render_to_response('context_processors/auth_attrs_access.html',
RequestContext(request, {}, processors=[context_processors.auth]))
return render_to_response('context_processors/auth_attrs_test_access.html',
{'session_accessed':request.session.accessed})
def auth_processor_user(request):
return render_to_response('context_processors/auth_attrs_user.html',
RequestContext(request, {}, processors=[context_processors.auth]))
def auth_processor_perms(request):
return render_to_response('context_processors/auth_attrs_perms.html',
RequestContext(request, {}, processors=[context_processors.auth]))
def auth_processor_messages(request):
request.user.message_set.create(message="Message 1")
return render_to_response('context_processors/auth_attrs_messages.html',
RequestContext(request, {}, processors=[context_processors.auth]))
def userpage(request):
pass

View File

@ -50,14 +50,6 @@ class CsrfViewMiddlewareTest(TestCase):
_csrf_id_cookie = "<1>\xc2\xa1"
_csrf_id = "1"
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.middleware.csrf')
def tearDown(self):
self.restore_warnings_state()
def _get_GET_no_csrf_cookie_request(self):
return TestingHttpRequest()

View File

@ -12,7 +12,7 @@ class CZLocalFlavorTests(LocalFlavorTestCase):
self.save_warnings_state()
warnings.filterwarnings(
"ignore",
category=PendingDeprecationWarning,
category=DeprecationWarning,
module='django.contrib.localflavor.cz.forms'
)

View File

@ -22,23 +22,23 @@ class DeprecationWarningTests(TestCase):
settings.LOCALE_PATHS = self.old_locale_paths
def test_warn_if_project_has_locale_subdir(self):
"""Test that PendingDeprecationWarning is generated when a deprecated project level locale/ subdir is present."""
"""Test that DeprecationWarning is generated when a deprecated project level locale/ subdir is present."""
project_path = join(dirname(abspath(__file__)), '..')
warnings.filterwarnings('error',
"Translations in the project directory aren't supported anymore\. Use the LOCALE_PATHS setting instead\.",
PendingDeprecationWarning)
DeprecationWarning)
_trans.__dict__ = {}
self.assertRaises(PendingDeprecationWarning, django.utils.translation.ugettext, 'Time')
self.assertRaises(DeprecationWarning, django.utils.translation.ugettext, 'Time')
def test_no_warn_if_project_and_locale_paths_overlap(self):
"""Test that PendingDeprecationWarning isn't generated when a deprecated project level locale/ subdir is also included in LOCALE_PATHS."""
"""Test that DeprecationWarning isn't generated when a deprecated project level locale/ subdir is also included in LOCALE_PATHS."""
project_path = join(dirname(abspath(__file__)), '..')
settings.LOCALE_PATHS += (normpath(join(project_path, 'locale')),)
warnings.filterwarnings('error',
"Translations in the project directory aren't supported anymore\. Use the LOCALE_PATHS setting instead\.",
PendingDeprecationWarning)
DeprecationWarning)
_trans.__dict__ = {}
try:
django.utils.translation.ugettext('Time')
except PendingDeprecationWarning:
self.fail("PendingDeprecationWarning shouldn't be raised when settings/project locale and a LOCALE_PATHS member point to the same file system location.")
except DeprecationWarning:
self.fail("DeprecationWarning shouldn't be raised when settings/project locale and a LOCALE_PATHS member point to the same file system location.")

View File

@ -30,7 +30,7 @@ class TrailingSlashURLTests(unittest.TestCase):
def test_blank(self):
"""
If blank, no PendingDeprecationWarning error will be raised, even though it
If blank, no DeprecationWarning error will be raised, even though it
doesn't end in a slash.
"""
self.settings_module.MEDIA_URL = ''
@ -49,19 +49,19 @@ class TrailingSlashURLTests(unittest.TestCase):
def test_no_end_slash(self):
"""
MEDIA_URL raises an PendingDeprecationWarning error if it doesn't end in a
MEDIA_URL raises an DeprecationWarning error if it doesn't end in a
slash.
"""
import warnings
warnings.filterwarnings('error', 'If set, MEDIA_URL must end with a slash', PendingDeprecationWarning)
warnings.filterwarnings('error', 'If set, MEDIA_URL must end with a slash', DeprecationWarning)
def setattr_settings(settings_module, attr, value):
setattr(settings_module, attr, value)
self.assertRaises(PendingDeprecationWarning, setattr_settings,
self.assertRaises(DeprecationWarning, setattr_settings,
self.settings_module, 'MEDIA_URL', '/foo')
self.assertRaises(PendingDeprecationWarning, setattr_settings,
self.assertRaises(DeprecationWarning, setattr_settings,
self.settings_module, 'MEDIA_URL',
'http://media.foo.com')

View File

@ -1,4 +1,4 @@
from django.contrib.syndication import feeds, views
from django.contrib.syndication import views
from django.core.exceptions import ObjectDoesNotExist
from django.utils import feedgenerator, tzinfo
from models import Article, Entry
@ -121,22 +121,3 @@ class MyCustomAtom1Feed(feedgenerator.Atom1Feed):
class TestCustomFeed(TestAtomFeed):
feed_type = MyCustomAtom1Feed
class DeprecatedComplexFeed(feeds.Feed):
def get_object(self, bits):
if len(bits) != 1:
raise ObjectDoesNotExist
return None
class DeprecatedRssFeed(feeds.Feed):
link = "/blog/"
title = 'My blog'
def items(self):
return Entry.objects.all()
def item_link(self, item):
return "/blog/%s/" % item.pk

View File

@ -2,7 +2,7 @@ import datetime
import warnings
from xml.dom import minidom
from django.contrib.syndication import feeds, views
from django.contrib.syndication import views
from django.core.exceptions import ImproperlyConfigured
from django.test import TestCase
from django.utils import tzinfo
@ -304,61 +304,3 @@ class SyndicationFeedTest(FeedTestCase):
views.add_domain('example.com', 'mailto:uhoh@djangoproject.com'),
'mailto:uhoh@djangoproject.com'
)
######################################
# Deprecated feeds
######################################
class DeprecatedSyndicationFeedTest(FeedTestCase):
"""
Tests for the deprecated API (feed() view and the feed_dict etc).
"""
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.contrib.syndication.feeds')
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.contrib.syndication.views')
def tearDown(self):
self.restore_warnings_state()
def test_empty_feed_dict(self):
"""
Test that an empty feed_dict raises a 404.
"""
response = self.client.get('/syndication/depr-feeds-empty/aware-dates/')
self.assertEqual(response.status_code, 404)
def test_nonexistent_slug(self):
"""
Test that a non-existent slug raises a 404.
"""
response = self.client.get('/syndication/depr-feeds/foobar/')
self.assertEqual(response.status_code, 404)
def test_rss_feed(self):
"""
A simple test for Rss201rev2Feed feeds generated by the deprecated
system.
"""
response = self.client.get('/syndication/depr-feeds/rss/')
doc = minidom.parseString(response.content)
feed = doc.getElementsByTagName('rss')[0]
self.assertEqual(feed.getAttribute('version'), '2.0')
chan = feed.getElementsByTagName('channel')[0]
self.assertChildNodes(chan, ['title', 'link', 'description', 'language', 'lastBuildDate', 'item', 'atom:link'])
items = chan.getElementsByTagName('item')
self.assertEqual(len(items), Entry.objects.count())
def test_complex_base_url(self):
"""
Tests that the base url for a complex feed doesn't raise a 500
exception.
"""
response = self.client.get('/syndication/depr-feeds/complex/')
self.assertEqual(response.status_code, 404)

View File

@ -2,11 +2,6 @@ from django.conf.urls.defaults import *
import feeds
feed_dict = {
'complex': feeds.DeprecatedComplexFeed,
'rss': feeds.DeprecatedRssFeed,
}
urlpatterns = patterns('django.contrib.syndication.views',
(r'^complex/(?P<foo>.*)/$', feeds.ComplexFeed()),
(r'^rss2/$', feeds.TestRss2Feed()),
@ -18,7 +13,4 @@ urlpatterns = patterns('django.contrib.syndication.views',
(r'^feedurl/$', feeds.TestFeedUrlFeed()),
(r'^articles/$', feeds.ArticlesFeed()),
(r'^template/$', feeds.TemplateFeed()),
(r'^depr-feeds/(?P<url>.*)/$', 'feed', {'feed_dict': feed_dict}),
(r'^depr-feeds-empty/(?P<url>.*)/$', 'feed', {'feed_dict': None}),
)

View File

@ -57,33 +57,6 @@ def create_egg(name, resources):
egg._resources = resources
sys.modules[name] = egg
class DeprecatedEggLoaderTest(unittest.TestCase):
"Test the deprecated load_template_source interface to the egg loader"
def setUp(self):
pkg_resources._provider_factories[MockLoader] = MockProvider
self.empty_egg = create_egg("egg_empty", {})
self.egg_1 = create_egg("egg_1", {
os.path.normcase('templates/y.html') : StringIO.StringIO("y"),
os.path.normcase('templates/x.txt') : StringIO.StringIO("x"),
})
self._old_installed_apps = settings.INSTALLED_APPS
settings.INSTALLED_APPS = []
self._warnings_state = get_warnings_state()
warnings.filterwarnings("ignore", category=DeprecationWarning,
module='django.template.loaders.eggs')
def tearDown(self):
settings.INSTALLED_APPS = self._old_installed_apps
restore_warnings_state(self._warnings_state)
def test_existing(self):
"A template can be loaded from an egg"
settings.INSTALLED_APPS = ['egg_1']
contents, template_name = lts_egg("y.html")
self.assertEqual(contents, "y")
self.assertEqual(template_name, "egg:egg_1:templates/y.html")
class EggLoaderTest(unittest.TestCase):
def setUp(self):

View File

@ -11,12 +11,14 @@ import time
import os
import sys
import traceback
import warnings
from django import template
from django.template import base as template_base
from django.core import urlresolvers
from django.template import loader
from django.template.loaders import app_directories, filesystem, cached
from django.test.utils import get_warnings_state, restore_warnings_state
from django.utils import unittest
from django.utils.translation import activate, deactivate, ugettext as _
from django.utils.safestring import mark_safe
@ -137,6 +139,10 @@ class UTF8Class:
class Templates(unittest.TestCase):
def setUp(self):
self._warnings_state = get_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.template.defaulttags')
self.old_static_url = settings.STATIC_URL
self.old_media_url = settings.MEDIA_URL
settings.STATIC_URL = u"/static/"
@ -145,6 +151,7 @@ class Templates(unittest.TestCase):
def tearDown(self):
settings.STATIC_URL = self.old_static_url
settings.MEDIA_URL = self.old_media_url
restore_warnings_state(self._warnings_state)
def test_loaders_security(self):
ad_loader = app_directories.Loader()

View File

@ -1,5 +1,6 @@
import inspect
import sys
import warnings
from django.conf import settings
from django.core.files.uploadedfile import SimpleUploadedFile
@ -13,6 +14,16 @@ from regressiontests.views import BrokenException, except_args
class DebugViewTests(TestCase):
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
settings.DEBUG = True
self.old_template_debug = settings.TEMPLATE_DEBUG
@ -21,6 +32,7 @@ class DebugViewTests(TestCase):
def tearDown(self):
settings.DEBUG = self.old_debug
settings.TEMPLATE_DEBUG = self.old_template_debug
self.restore_warnings_state()
def test_files(self):
response = self.client.get('/views/raises/')

View File

@ -1,4 +1,5 @@
import datetime
import warnings
from django.test import TestCase
from django.core.exceptions import ImproperlyConfigured
@ -8,6 +9,14 @@ class CreateObjectTest(TestCase):
fixtures = ['testdata.json']
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.create_update')
def tearDown(self):
self.restore_warnings_state()
def test_login_required_view(self):
"""
Verifies that an unauthenticated user attempting to access a
@ -69,6 +78,14 @@ class UpdateDeleteObjectTest(TestCase):
fixtures = ['testdata.json']
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.create_update')
def tearDown(self):
self.restore_warnings_state()
def test_update_object_form_display(self):
"""
Verifies that the form was created properly and with initial values.
@ -129,6 +146,14 @@ class PostSaveRedirectTests(TestCase):
update_redirect = '/views/create_update/view/article/another-article-slug/'
delete_redirect = '/views/create_update/'
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.create_update')
def tearDown(self):
self.restore_warnings_state()
def test_create_article(self):
num_articles = self.article_model.objects.count()
response = self.client.post(self.create_url, {
@ -173,6 +198,14 @@ class NoPostSaveNoAbsoluteUrl(PostSaveRedirectTests):
create_url = '/views/create_update/no_redirect/create/article/'
update_url = '/views/create_update/no_redirect/update/article/old_article/'
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.create_update')
def tearDown(self):
self.restore_warnings_state()
def test_create_article(self):
self.assertRaises(ImproperlyConfigured,
super(NoPostSaveNoAbsoluteUrl, self).test_create_article)
@ -203,6 +236,14 @@ class AbsoluteUrlNoPostSave(PostSaveRedirectTests):
create_redirect = '/urlarticles/my-first-article/'
update_redirect = '/urlarticles/another-article-slug/'
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.create_update')
def tearDown(self):
self.restore_warnings_state()
def test_delete_article(self):
"""
The delete_object view requires a post_delete_redirect, so skip testing

View File

@ -1,4 +1,6 @@
# coding: utf-8
import warnings
from django.test import TestCase
from datetime import datetime, date
from datetime import timedelta
@ -7,11 +9,17 @@ from regressiontests.views.models import Article, Author, DateArticle
class ObjectDetailTest(TestCase):
fixtures = ['testdata.json']
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.date_based')
# Correct the date for the current article
current_article = Article.objects.get(title="Current Article")
current_article.date_created = datetime.now()
current_article.save()
def tearDown(self):
self.restore_warnings_state()
def test_finds_past(self):
"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/')
@ -37,6 +45,14 @@ class ObjectDetailTest(TestCase):
self.assertEqual(response.context['object'].title, "Future Article")
class MonthArchiveTest(TestCase):
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.date_based')
def tearDown(self):
self.restore_warnings_state()
def test_archive_month_includes_only_month(self):
"Regression for #3031: Archives around Feburary include only one month"
author = Author(name="John Smith")
@ -128,6 +144,15 @@ class MonthArchiveTest(TestCase):
self.assertEqual(len(response.context['date_list']), 2)
class DayArchiveTests(TestCase):
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.date_based')
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.create_update')
def tearDown(self):
self.restore_warnings_state()
def test_year_month_day_format(self):
"""

View File

@ -1,8 +1,17 @@
import warnings
from django.test import TestCase
class ObjectListTest(TestCase):
fixtures = ['testdata.json']
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.object_list')
def tearDown(self):
self.restore_warnings_state()
def check_pagination(self, url, expected_status_code, object_count=None):
response = self.client.get(url)

View File

@ -1,8 +1,17 @@
# coding: utf-8
import warnings
from django.test import TestCase
class RedirectToTest(TestCase):
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_redirect_to_returns_permanent_redirect(self):
"simple.redirect_to returns a permanent redirect (301) by default"
response = self.client.get('/views/simple/redirect_to/')

View File

@ -1,16 +1,25 @@
import warnings
from django.conf import settings
from django.test import TestCase
class ShortcutTests(TestCase):
def setUp(self):
self.save_warnings_state()
warnings.filterwarnings('ignore', category=DeprecationWarning,
module='django.views.generic.simple')
self.old_STATIC_URL = settings.STATIC_URL
self.old_TEMPLATE_CONTEXT_PROCESSORS = settings.TEMPLATE_CONTEXT_PROCESSORS
settings.STATIC_URL = '/path/to/static/media'
settings.STATIC_URL = '/path/to/static/media/'
settings.TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.static'
)
def tearDown(self):
self.restore_warnings_state()
def tearDown(self):
settings.STATIC_URL = self.old_STATIC_URL
settings.TEMPLATE_CONTEXT_PROCESSORS = self.old_TEMPLATE_CONTEXT_PROCESSORS
@ -24,7 +33,7 @@ class ShortcutTests(TestCase):
def test_render_to_response_with_request_context(self):
response = self.client.get('/views/shortcuts/render_to_response/request_context/')
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')
def test_render_to_response_with_mimetype(self):
@ -36,7 +45,7 @@ class ShortcutTests(TestCase):
def test_render(self):
response = self.client.get('/views/shortcuts/render/')
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.context.current_app, None)
@ -49,13 +58,13 @@ class ShortcutTests(TestCase):
def test_render_with_content_type(self):
response = self.client.get('/views/shortcuts/render/content_type/')
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')
def test_render_with_status(self):
response = self.client.get('/views/shortcuts/render/status/')
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):
response = self.client.get('/views/shortcuts/render/current_app/')

View File

@ -6,7 +6,6 @@ from django.core.urlresolvers import get_resolver
from django.shortcuts import render_to_response, render
from django.template import Context, RequestContext, TemplateDoesNotExist
from django.views.debug import technical_500_response
from django.views.generic.create_update import create_object
from regressiontests.views import BrokenException, except_args
@ -31,6 +30,7 @@ def custom_create(request):
self.instance.slug = 'some-other-slug'
return super(SlugChangingArticleForm, self).save(*args, **kwargs)
from django.views.generic.create_update import create_object
return create_object(request,
post_save_redirect='/views/create_update/view/article/%(slug)s/',
form_class=SlugChangingArticleForm)

View File

@ -188,17 +188,6 @@ def django_tests(verbosity, interactive, failfast, test_labels):
settings.TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner'
TestRunner = get_runner(settings)
if hasattr(TestRunner, 'func_name'):
# Pre 1.2 test runners were just functions,
# and did not support the 'failfast' option.
import warnings
warnings.warn(
'Function-based test runners are deprecated. Test runners should be classes with a run_tests() method.',
DeprecationWarning
)
failures = TestRunner(test_labels, verbosity=verbosity, interactive=interactive,
extra_tests=extra_tests)
else:
test_runner = TestRunner(verbosity=verbosity, interactive=interactive, failfast=failfast)
failures = test_runner.run_tests(test_labels, extra_tests=extra_tests)