desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'date_based.object_detail can view a page from today'
| def test_object_detail_finds_today(self):
| today_url = datetime.now().strftime('%Y/%m/%d')
response = self.client.get(('/date_based/object_detail/%s/current_article/' % today_url))
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['object'].title, 'Current Article')
|
'date_based.object_detail can view a page from the future, but only if allowed.'
| def test_object_detail_ignores_future(self):
| response = self.client.get('/date_based/object_detail/3000/01/01/future_article/')
self.assertEqual(response.status_code, 404)
|
'date_based.object_detail can view a page from the future if explicitly allowed.'
| def test_object_detail_allowed_future_if_enabled(self):
| response = self.client.get('/date_based/object_detail/3000/01/01/future_article/allow_future/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['object'].title, 'Future Article')
|
'Regression for #3031: Archives around Feburary include only one month'
| def test_archive_month_includes_only_month(self):
| author = Author(name='John Smith')
author.save()
first_second_of_feb = datetime(2004, 2, 1, 0, 0, 1)
first_second_of_mar = datetime(2004, 3, 1, 0, 0, 1)
two_seconds = timedelta(0, 2, 0)
article = Article(title='example', author=author)
article.date_created = first_second_of_feb
articl... |
'Make sure day views don\'t get confused with numeric month formats (#7944)'
| def test_year_month_day_format(self):
| author = Author.objects.create(name='John Smith')
article = Article.objects.create(title='example', author=author, date_created=datetime(2004, 1, 21, 0, 0, 1))
response = self.client.get('/date_based/archive_day/2004/1/21/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.co... |
'Tests that redirecting to an IRI, requiring encoding before we use it
in an HTTP response, is handled correctly. In this case the arg to
HttpRedirect is ASCII but the current request path contains non-ASCII
characters so this test ensures the creation of the full path with a
base non-ASCII part is handled correctly.'
| def test_combining_redirect(self):
| response = self.client.get(u'/\u4e2d\u6587/')
self.assertRedirects(response, self.redirect_target)
|
'Tests that a non-ASCII argument to HttpRedirect is handled properly.'
| def test_nonascii_redirect(self):
| response = self.client.get('/nonascii_redirect/')
self.assertRedirects(response, self.redirect_target)
|
'Tests that a non-ASCII argument to HttpPermanentRedirect is handled
properly.'
| def test_permanent_nonascii_redirect(self):
| response = self.client.get('/permanent_nonascii_redirect/')
self.assertRedirects(response, self.redirect_target, status_code=301)
|
'A simple exception report can be generated'
| def test_request_and_exception(self):
| try:
request = self.rf.get('/test_view/')
raise ValueError("Can't find my keys")
except ValueError:
(exc_type, exc_value, tb) = sys.exc_info()
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
self.assertIn('<h1>Value... |
'An exception report can be generated without request'
| def test_no_request(self):
| try:
raise ValueError("Can't find my keys")
except ValueError:
(exc_type, exc_value, tb) = sys.exc_info()
reporter = ExceptionReporter(None, exc_type, exc_value, tb)
html = reporter.get_traceback_html()
self.assertIn('<h1>ValueError</h1>', html)
self.assertIn('<pre cl... |
'An exception report can be generated for just a request'
| def test_no_exception(self):
| request = self.rf.get('/test_view/')
reporter = ExceptionReporter(request, None, None, None)
html = reporter.get_traceback_html()
self.assertIn('<h1>Report at /test_view/</h1>', html)
self.assertIn('<pre class="exception_value">No exception supplied</pre>', html)
self.assertIn('<t... |
'A message can be provided in addition to a request'
| def test_request_and_message(self):
| request = self.rf.get('/test_view/')
reporter = ExceptionReporter(request, None, "I'm a little teapot", None)
html = reporter.get_traceback_html()
self.assertIn('<h1>Report at /test_view/</h1>', html)
self.assertIn('<pre class="exception_value">I'm a little teapot</pre... |
'A simple exception report can be generated'
| def test_request_and_exception(self):
| try:
request = self.rf.get('/test_view/')
raise ValueError("Can't find my keys")
except ValueError:
(exc_type, exc_value, tb) = sys.exc_info()
reporter = ExceptionReporter(request, exc_type, exc_value, tb)
text = reporter.get_traceback_text()
self.assertIn('ValueErro... |
'An exception report can be generated without request'
| def test_no_request(self):
| try:
raise ValueError("Can't find my keys")
except ValueError:
(exc_type, exc_value, tb) = sys.exc_info()
reporter = ExceptionReporter(None, exc_type, exc_value, tb)
text = reporter.get_traceback_text()
self.assertIn('ValueError', text)
self.assertIn("Can't find my... |
'An exception report can be generated for just a request'
| def test_no_exception(self):
| request = self.rf.get('/test_view/')
reporter = ExceptionReporter(request, None, None, None)
text = reporter.get_traceback_text()
|
'A message can be provided in addition to a request'
| def test_request_and_message(self):
| request = self.rf.get('/test_view/')
reporter = ExceptionReporter(request, None, "I'm a little teapot", None)
text = reporter.get_traceback_text()
|
'Asserts that potentially sensitive info are displayed in the response.'
| def verify_unsafe_response(self, view, check_for_vars=True, check_for_POST_params=True):
| request = self.rf.post('/some_url/', self.breakfast_data)
response = view(request)
if check_for_vars:
self.assertContains(response, 'cooked_eggs', status_code=500)
self.assertContains(response, 'scrambled', status_code=500)
self.assertContains(response, 'sauce', status_code=500)
... |
'Asserts that certain sensitive info are not displayed in the response.'
| def verify_safe_response(self, view, check_for_vars=True, check_for_POST_params=True):
| request = self.rf.post('/some_url/', self.breakfast_data)
response = view(request)
if check_for_vars:
self.assertContains(response, 'cooked_eggs', status_code=500)
self.assertContains(response, 'scrambled', status_code=500)
self.assertContains(response, 'sauce', status_code=500)
... |
'Asserts that no variables or POST parameters are displayed in the response.'
| def verify_paranoid_response(self, view, check_for_vars=True, check_for_POST_params=True):
| request = self.rf.post('/some_url/', self.breakfast_data)
response = view(request)
if check_for_vars:
self.assertContains(response, 'cooked_eggs', status_code=500)
self.assertNotContains(response, 'scrambled', status_code=500)
self.assertContains(response, 'sauce', status_code=500)
... |
'Asserts that potentially sensitive info are displayed in the email report.'
| def verify_unsafe_email(self, view, check_for_POST_params=True):
| with self.settings(ADMINS=(('Admin', 'admin@fattie-breakie.com'),)):
mail.outbox = []
request = self.rf.post('/some_url/', self.breakfast_data)
response = view(request)
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
self.assertNotIn('cooked_eggs', email.... |
'Asserts that certain sensitive info are not displayed in the email report.'
| def verify_safe_email(self, view, check_for_POST_params=True):
| with self.settings(ADMINS=(('Admin', 'admin@fattie-breakie.com'),)):
mail.outbox = []
request = self.rf.post('/some_url/', self.breakfast_data)
response = view(request)
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
self.assertNotIn('cooked_eggs', email.... |
'Asserts that no variables or POST parameters are displayed in the email report.'
| def verify_paranoid_email(self, view):
| with self.settings(ADMINS=(('Admin', 'admin@fattie-breakie.com'),)):
mail.outbox = []
request = self.rf.post('/some_url/', self.breakfast_data)
response = view(request)
self.assertEqual(len(mail.outbox), 1)
email = mail.outbox[0]
self.assertNotIn('cooked_eggs', email.... |
'Ensure that everything (request info and frame variables) can bee seen
in the default error reports for non-sensitive requests.'
| def test_non_sensitive_request(self):
| with self.settings(DEBUG=True):
self.verify_unsafe_response(non_sensitive_view)
self.verify_unsafe_email(non_sensitive_view)
with self.settings(DEBUG=False):
self.verify_unsafe_response(non_sensitive_view)
self.verify_unsafe_email(non_sensitive_view)
|
'Ensure that sensitive POST parameters and frame variables cannot be
seen in the default error reports for sensitive requests.'
| def test_sensitive_request(self):
| with self.settings(DEBUG=True):
self.verify_unsafe_response(sensitive_view)
self.verify_unsafe_email(sensitive_view)
with self.settings(DEBUG=False):
self.verify_safe_response(sensitive_view)
self.verify_safe_email(sensitive_view)
|
'Ensure that no POST parameters and frame variables can be seen in the
default error reports for "paranoid" requests.'
| def test_paranoid_request(self):
| with self.settings(DEBUG=True):
self.verify_unsafe_response(paranoid_view)
self.verify_unsafe_email(paranoid_view)
with self.settings(DEBUG=False):
self.verify_paranoid_response(paranoid_view)
self.verify_paranoid_email(paranoid_view)
|
'Ensure that it\'s possible to assign an exception reporter filter to
the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER.'
| def test_custom_exception_reporter_filter(self):
| with self.settings(DEBUG=True):
self.verify_unsafe_response(custom_exception_reporter_filter_view)
self.verify_unsafe_email(custom_exception_reporter_filter_view)
with self.settings(DEBUG=False):
self.verify_unsafe_response(custom_exception_reporter_filter_view)
self.verify_unsaf... |
'Ensure that the sensitive_variables decorator works with object
methods.
Refs #18379.'
| def test_sensitive_method(self):
| with self.settings(DEBUG=True):
self.verify_unsafe_response(sensitive_method_view, check_for_POST_params=False)
self.verify_unsafe_email(sensitive_method_view, check_for_POST_params=False)
with self.settings(DEBUG=False):
self.verify_safe_response(sensitive_method_view, check_for_POST_pa... |
'Ensure that request info can bee seen in the default error reports for
non-sensitive requests.'
| def test_non_sensitive_request(self):
| with self.settings(DEBUG=True):
self.verify_unsafe_response(non_sensitive_view, check_for_vars=False)
with self.settings(DEBUG=False):
self.verify_unsafe_response(non_sensitive_view, check_for_vars=False)
|
'Ensure that sensitive POST parameters cannot be seen in the default
error reports for sensitive requests.'
| def test_sensitive_request(self):
| with self.settings(DEBUG=True):
self.verify_unsafe_response(sensitive_view, check_for_vars=False)
with self.settings(DEBUG=False):
self.verify_safe_response(sensitive_view, check_for_vars=False)
|
'Ensure that no POST parameters can be seen in the default error reports
for "paranoid" requests.'
| def test_paranoid_request(self):
| with self.settings(DEBUG=True):
self.verify_unsafe_response(paranoid_view, check_for_vars=False)
with self.settings(DEBUG=False):
self.verify_paranoid_response(paranoid_view, check_for_vars=False)
|
'Ensure that it\'s possible to assign an exception reporter filter to
the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER.'
| def test_custom_exception_reporter_filter(self):
| with self.settings(DEBUG=True):
self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False)
with self.settings(DEBUG=False):
self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False)
|
'A test that might be skipped is actually called.'
| def test_skip_unless_db_feature(self):
| @skipUnlessDBFeature('__class__')
def test_func():
raise ValueError
self.assertRaises(ValueError, test_func)
|
'Ensure save_warnings_state/restore_warnings_state work correctly.'
| def test_save_restore_warnings_state(self):
| import warnings
self.save_warnings_state()
class MyWarning(Warning, ):
pass
warnings.simplefilter('error', MyWarning)
self.assertRaises(Warning, (lambda : warnings.warn('warn', MyWarning)))
self.restore_warnings_state()
warnings.simplefilter('ignore', MyWarning)
warnings.warn('wa... |
'assertRaisesMessage shouldn\'t interpret RE special chars.'
| def test_special_re_chars(self):
| def func1():
raise ValueError('[.*x+]y?')
self.assertRaisesMessage(ValueError, '[.*x+]y?', func1)
|
'm2m-through models aren\'t serialized as m2m fields. Refs #8134'
| def test_serialization(self):
| p = Person.objects.create(name='Bob')
g = Group.objects.create(name='Roll')
m = Membership.objects.create(person=p, group=g)
pks = {'p_pk': p.pk, 'g_pk': g.pk, 'm_pk': m.pk}
out = StringIO()
management.call_command('dumpdata', 'm2m_through_regress', format='json', stdout=out)
self.assertEqua... |
'Check that we don\'t involve too many copies of the intermediate table when doing a join. Refs #8046, #8254'
| def test_join_trimming(self):
| bob = Person.objects.create(name='Bob')
jim = Person.objects.create(name='Jim')
rock = Group.objects.create(name='Rock')
roll = Group.objects.create(name='Roll')
Membership.objects.create(person=bob, group=rock)
Membership.objects.create(person=jim, group=rock, price=50)
Membership.objects.c... |
'Check that sequences on an m2m_through are created for the through model, not a phantom auto-generated m2m table. Refs #11107'
| def test_sequence_creation(self):
| out = StringIO()
management.call_command('dumpdata', 'm2m_through_regress', format='json', stdout=out)
self.assertEqual(out.getvalue().strip(), '[{"pk": 1, "model": "m2m_through_regress.usermembership", "fields": {"price": 100, "group": 1, "user": 1}}, {"pk": 1, "model... |
'Comments that aren\'t public are considered in moderation'
| def testInModeration(self):
| (c1, c2, c3, c4) = self.createSomeComments()
c1.is_public = False
c2.is_public = False
c1.save()
c2.save()
moderated_comments = list(Comment.objects.in_moderation().order_by('id'))
self.assertEqual(moderated_comments, [c1, c2])
|
'Removed comments are not considered in moderation'
| def testRemovedCommentsNotInModeration(self):
| (c1, c2, c3, c4) = self.createSomeComments()
c1.is_public = False
c2.is_public = False
c2.is_removed = True
c1.save()
c2.save()
moderated_comments = list(Comment.objects.in_moderation())
self.assertEqual(moderated_comments, [c1])
|
'Ensure that the template tags use cached content types to reduce the
number of DB queries.
Refs #16042.'
| def testNumberQueries(self):
| self.createSomeComments()
ContentType.objects.clear_cache()
with self.assertNumQueries(4):
self.testRenderCommentListFromObject()
with self.assertNumQueries(3):
self.testRenderCommentListFromObject()
ContentType.objects.clear_cache()
with self.assertNumQueries(4):
self.ve... |
'Test COMMENTS_ALLOW_PROFANITIES and PROFANITIES_LIST settings'
| def testProfanities(self):
| a = Article.objects.get(pk=1)
d = self.getValidData(a)
saved = (settings.PROFANITIES_LIST, settings.COMMENTS_ALLOW_PROFANITIES)
settings.PROFANITIES_LIST = ['rooster']
settings.COMMENTS_ALLOW_PROFANITIES = False
f = CommentForm(a, data=dict(d, comment='What a rooster!'))
self.assertFal... |
'The debug error template should be shown only if DEBUG is True'
| def testDebugCommentErrors(self):
| olddebug = settings.DEBUG
settings.DEBUG = True
a = Article.objects.get(pk=1)
data = self.getValidData(a)
data['security_hash'] = 'Nobody expects the Spanish Inquisition!'
response = self.client.post('/post/', data)
self.assertEqual(response.status_code, 400)
self.assertTempl... |
'Check that the user\'s name in the comment is populated for
authenticated users without first_name and last_name.'
| def testPostAsAuthenticatedUserWithoutFullname(self):
| user = User.objects.create_user(username='jane_other', email='jane@example.com', password='jane_other')
a = Article.objects.get(pk=1)
data = self.getValidData(a)
data['name'] = data['email'] = ''
self.client.login(username='jane_other', password='jane_other')
self.response = self.client.post('/p... |
'Prevent posting the exact same comment twice'
| def testPreventDuplicateComments(self):
| a = Article.objects.get(pk=1)
data = self.getValidData(a)
self.client.post('/post/', data)
self.client.post('/post/', data)
self.assertEqual(Comment.objects.count(), 1)
self.client.post('/post/', dict(data, comment='My second comment.'))
self.assertEqual(Comment.objects.count(), 2)
|
'Test signals emitted by the comment posting view'
| def testCommentSignals(self):
| def receive(sender, **kwargs):
self.assertEqual(kwargs['comment'].comment, 'This is my comment')
self.assertTrue(('request' in kwargs))
received_signals.append(kwargs.get('signal'))
received_signals = []
expected_signals = [signals.comment_will_be_posted, signals.comment_was... |
'Test that the comment_will_be_posted signal can prevent the comment from
actually getting saved'
| def testWillBePostedSignal(self):
| def receive(sender, **kwargs):
return False
signals.comment_will_be_posted.connect(receive, dispatch_uid='comment-test')
a = Article.objects.get(pk=1)
data = self.getValidData(a)
response = self.client.post('/post/', data)
self.assertEqual(response.status_code, 400)
self.assertEqual(... |
'Test that the comment_will_be_posted signal can modify a comment before
it gets posted'
| def testWillBePostedSignalModifyComment(self):
| def receive(sender, **kwargs):
kwargs['comment'].is_public = False
signals.comment_will_be_posted.connect(receive)
self.testCreateValidComment()
c = Comment.objects.all()[0]
self.assertFalse(c.is_public)
|
'Test the different "next" actions the comment view can take'
| def testCommentNext(self):
| a = Article.objects.get(pk=1)
data = self.getValidData(a)
response = self.client.post('/post/', data)
location = response['Location']
match = post_redirect_re.match(location)
self.assertTrue((match != None), ('Unexpected redirect location: %s' % location))
data['next'] = '/somewhere... |
'The `next` key needs to handle already having a query string (#10585)'
| def testCommentNextWithQueryString(self):
| a = Article.objects.get(pk=1)
data = self.getValidData(a)
data['next'] = '/somewhere/else/?foo=bar'
data['comment'] = 'This is another comment'
response = self.client.post('/post/', data)
location = response['Location']
match = re.search('^http://testserver/somewhere/else/\\?foo=bar... |
'Tests that attempting to retrieve the location specified in the
post redirect, after adding some invalid data to the expected
querystring it ends with, doesn\'t cause a server error.'
| def testCommentPostRedirectWithInvalidIntegerPK(self):
| a = Article.objects.get(pk=1)
data = self.getValidData(a)
data['comment'] = 'This is another comment'
response = self.client.post('/post/', data)
location = response['Location']
broken_location = (location + u'\ufffd')
response = self.client.get(broken_location)
self.assertEqual... |
'The `next` key needs to handle already having an anchor. Refs #13411.'
| def testCommentNextWithQueryStringAndAnchor(self):
| a = Article.objects.get(pk=1)
data = self.getValidData(a)
data['next'] = '/somewhere/else/?foo=bar#baz'
data['comment'] = 'This is another comment'
response = self.client.post('/post/', data)
location = response['Location']
match = re.search('^http://testserver/somewhere/else/\\?foo... |
'GET the flag view: render a confirmation page.'
| def testFlagGet(self):
| comments = self.createSomeComments()
pk = comments[0].pk
self.client.login(username='normaluser', password='normaluser')
response = self.client.get(('/flag/%d/' % pk))
self.assertTemplateUsed(response, 'comments/flag.html')
|
'POST the flag view: actually flag the view (nice for XHR)'
| def testFlagPost(self):
| comments = self.createSomeComments()
pk = comments[0].pk
self.client.login(username='normaluser', password='normaluser')
response = self.client.post(('/flag/%d/' % pk))
self.assertEqual(response['Location'], ('http://testserver/flagged/?c=%d' % pk))
c = Comment.objects.get(pk=pk)
self.assert... |
'POST the flag view, explicitly providing a next url.'
| def testFlagPostNext(self):
| comments = self.createSomeComments()
pk = comments[0].pk
self.client.login(username='normaluser', password='normaluser')
response = self.client.post(('/flag/%d/' % pk), {'next': '/go/here/'})
self.assertEqual(response['Location'], 'http://testserver/go/here/?c=1')
|
'POSTing to the flag view with an unsafe next url will ignore the
provided url when redirecting.'
| def testFlagPostUnsafeNext(self):
| comments = self.createSomeComments()
pk = comments[0].pk
self.client.login(username='normaluser', password='normaluser')
response = self.client.post(('/flag/%d/' % pk), {'next': 'http://elsewhere/bad'})
self.assertEqual(response['Location'], ('http://testserver/flagged/?c=%d' % pk))
|
'Users don\'t get to flag comments more than once.'
| def testFlagPostTwice(self):
| c = self.testFlagPost()
self.client.post(('/flag/%d/' % c.pk))
self.client.post(('/flag/%d/' % c.pk))
self.assertEqual(c.flags.filter(flag=CommentFlag.SUGGEST_REMOVAL).count(), 1)
|
'GET/POST the flag view while not logged in: redirect to log in.'
| def testFlagAnon(self):
| comments = self.createSomeComments()
pk = comments[0].pk
response = self.client.get(('/flag/%d/' % pk))
self.assertEqual(response['Location'], ('http://testserver/accounts/login/?next=/flag/%d/' % pk))
response = self.client.post(('/flag/%d/' % pk))
self.assertEqual(response['Location'], ('http:... |
'Test signals emitted by the comment flag view'
| def testFlagSignals(self):
| def receive(sender, **kwargs):
self.assertEqual(kwargs['flag'].flag, CommentFlag.SUGGEST_REMOVAL)
self.assertEqual(kwargs['request'].user.username, 'normaluser')
received_signals.append(kwargs.get('signal'))
received_signals = []
signals.comment_was_flagged.connect(receive)
self.... |
'The delete view should only be accessible to \'moderators\''
| def testDeletePermissions(self):
| comments = self.createSomeComments()
pk = comments[0].pk
self.client.login(username='normaluser', password='normaluser')
response = self.client.get(('/delete/%d/' % pk))
self.assertEqual(response['Location'], ('http://testserver/accounts/login/?next=/delete/%d/' % pk))
makeModerator('normaluser'... |
'POSTing the delete view should mark the comment as removed'
| def testDeletePost(self):
| comments = self.createSomeComments()
pk = comments[0].pk
makeModerator('normaluser')
self.client.login(username='normaluser', password='normaluser')
response = self.client.post(('/delete/%d/' % pk))
self.assertEqual(response['Location'], ('http://testserver/deleted/?c=%d' % pk))
c = Comment.... |
'POSTing the delete view will redirect to an explicitly provided a next
url.'
| def testDeletePostNext(self):
| comments = self.createSomeComments()
pk = comments[0].pk
makeModerator('normaluser')
self.client.login(username='normaluser', password='normaluser')
response = self.client.post(('/delete/%d/' % pk), {'next': '/go/here/'})
self.assertEqual(response['Location'], 'http://testserver/go/here/?c=1')
|
'POSTing to the delete view with an unsafe next url will ignore the
provided url when redirecting.'
| def testDeletePostUnsafeNext(self):
| comments = self.createSomeComments()
pk = comments[0].pk
makeModerator('normaluser')
self.client.login(username='normaluser', password='normaluser')
response = self.client.post(('/delete/%d/' % pk), {'next': 'http://elsewhere/bad'})
self.assertEqual(response['Location'], ('http://testserver/dele... |
'The approve view should only be accessible to \'moderators\''
| def testApprovePermissions(self):
| comments = self.createSomeComments()
pk = comments[0].pk
self.client.login(username='normaluser', password='normaluser')
response = self.client.get(('/approve/%d/' % pk))
self.assertEqual(response['Location'], ('http://testserver/accounts/login/?next=/approve/%d/' % pk))
makeModerator('normaluse... |
'POSTing the approve view should mark the comment as removed'
| def testApprovePost(self):
| (c1, c2, c3, c4) = self.createSomeComments()
c1.is_public = False
c1.save()
makeModerator('normaluser')
self.client.login(username='normaluser', password='normaluser')
response = self.client.post(('/approve/%d/' % c1.pk))
self.assertEqual(response['Location'], ('http://testserver/approved/?c... |
'POSTing the approve view will redirect to an explicitly provided a next
url.'
| def testApprovePostNext(self):
| (c1, c2, c3, c4) = self.createSomeComments()
c1.is_public = False
c1.save()
makeModerator('normaluser')
self.client.login(username='normaluser', password='normaluser')
response = self.client.post(('/approve/%d/' % c1.pk), {'next': '/go/here/'})
self.assertEqual(response['Location'], 'http://... |
'POSTing to the approve view with an unsafe next url will ignore the
provided url when redirecting.'
| def testApprovePostUnsafeNext(self):
| (c1, c2, c3, c4) = self.createSomeComments()
c1.is_public = False
c1.save()
makeModerator('normaluser')
self.client.login(username='normaluser', password='normaluser')
response = self.client.post(('/approve/%d/' % c1.pk), {'next': 'http://elsewhere/bad'})
self.assertEqual(response['Location'... |
'Tests a CommentAdmin where \'delete_selected\' has been disabled.'
| def testActionsDisabledDelete(self):
| comments = self.createSomeComments()
self.client.login(username='normaluser', password='normaluser')
response = self.client.get('/admin2/comments/comment/')
self.assertEqual(response.status_code, 200)
self.assertTrue(('<option value="delete_selected">' not in response.content), 'Found an un... |
'A formset over a ForeignKey with a to_field can be saved. Regression for #10243'
| def test_formset_over_to_field(self):
| Form = modelform_factory(User)
FormSet = inlineformset_factory(User, UserSite)
form = Form()
form_set = FormSet(instance=User())
data = {'serial': u'1', 'username': u'apollo13', 'usersite_set-TOTAL_FORMS': u'1', 'usersite_set-INITIAL_FORMS': u'0', 'usersite_set-MAX_NUM_FORMS': u'0', 'usersite_set-0-... |
'A formset over a ForeignKey with a to_field can be saved. Regression for #11120'
| def test_formset_over_inherited_model(self):
| Form = modelform_factory(Restaurant)
FormSet = inlineformset_factory(Restaurant, Manager)
form = Form()
form_set = FormSet(instance=Restaurant())
data = {'name': u"Guido's House of Pasta", 'manager_set-TOTAL_FORMS': u'1', 'manager_set-INITIAL_FORMS': u'0', 'manager_set-MAX_NUM_FORMS': u'0',... |
'A formset with instance=None can be created. Regression for #11872'
| def test_formset_with_none_instance(self):
| Form = modelform_factory(User)
FormSet = inlineformset_factory(User, UserSite)
form = Form(instance=None)
formset = FormSet(instance=None)
|
'No fields passed to modelformset_factory should result in no fields on returned forms except for the id. See #14119.'
| def test_empty_fields_on_modelformset(self):
| UserFormSet = modelformset_factory(User, fields=())
formset = UserFormSet()
for form in formset.forms:
self.assertTrue(('id' in form.fields))
self.assertEqual(len(form.fields), 1)
|
'Existing and new inlines are saved with save_as_new.
Regression for #14938.'
| def test_save_as_new_with_new_inlines(self):
| efnet = Network.objects.create(name='EFNet')
host1 = Host.objects.create(hostname='irc.he.net', network=efnet)
HostFormSet = inlineformset_factory(Network, Host)
data = {'host_set-TOTAL_FORMS': u'2', 'host_set-INITIAL_FORMS': u'1', 'host_set-MAX_NUM_FORMS': u'0', 'host_set-0-id': unicode(host1.id), 'hos... |
'Test the type of Formset and Form error attributes'
| def test_error_class(self):
| Formset = modelformset_factory(User)
data = {'form-TOTAL_FORMS': u'2', 'form-INITIAL_FORMS': u'0', 'form-MAX_NUM_FORMS': u'0', 'form-0-id': '', 'form-0-username': u'apollo13', 'form-0-serial': u'1', 'form-1-id': '', 'form-1-username': u'apollo13', 'form-1-serial': u'2'}
formset = Formset(data)
self.asse... |
'delete form if odd PK'
| def should_delete(self):
| return ((self.instance.id % 2) != 0)
|
'Add test data to database via formset'
| def test_init_database(self):
| formset = self.NormalFormset(self.data)
self.assertTrue(formset.is_valid())
self.assertEqual(len(formset.save()), 4)
|
'Verify base formset doesn\'t modify database'
| def test_no_delete(self):
| self.test_init_database()
data = dict(self.data)
data['form-INITIAL_FORMS'] = 4
data.update(dict(((('form-%d-id' % i), user.id) for (i, user) in enumerate(User.objects.all()))))
formset = self.NormalFormset(data, queryset=User.objects.all())
self.assertTrue(formset.is_valid())
self.assertEqu... |
'Verify base formset honors DELETE field'
| def test_all_delete(self):
| self.test_init_database()
data = dict(self.data)
data['form-INITIAL_FORMS'] = 4
data.update(dict(((('form-%d-id' % i), user.id) for (i, user) in enumerate(User.objects.all()))))
data.update(self.delete_all_ids)
formset = self.NormalFormset(data, queryset=User.objects.all())
self.assertTrue(f... |
'Verify DeleteFormset ignores DELETE field and uses form method'
| def test_custom_delete(self):
| self.test_init_database()
data = dict(self.data)
data['form-INITIAL_FORMS'] = 4
data.update(dict(((('form-%d-id' % i), user.id) for (i, user) in enumerate(User.objects.all()))))
data.update(self.delete_all_ids)
formset = self.DeleteFormset(data, queryset=User.objects.all())
self.assertTrue(f... |
'Regression test for bug #7110.
When using select_related(), we must query the
Device and Building tables using two different aliases (each) in order to
differentiate the start and end Connection fields. The net result is that
both the "connections = ..." queries here should give the same results
without pulling in mor... | def test_regression_7110(self):
| b = Building.objects.create(name='101')
dev1 = Device.objects.create(name='router', building=b)
dev2 = Device.objects.create(name='switch', building=b)
dev3 = Device.objects.create(name='server', building=b)
port1 = Port.objects.create(port_number='4', device=dev1)
port2 = Port.objects.create(po... |
'Regression test for bug #8106.
Same sort of problem as the previous test, but this time there are
more extra tables to pull in as part of the select_related() and some
of them could potentially clash (so need to be kept separate).'
| def test_regression_8106(self):
| us = TUser.objects.create(name='std')
usp = Person.objects.create(user=us)
uo = TUser.objects.create(name='org')
uop = Person.objects.create(user=uo)
s = Student.objects.create(person=usp)
o = Organizer.objects.create(person=uop)
c = Class.objects.create(org=o)
e = Enrollment.objects.cre... |
'Regression test for bug #8036
the first related model in the tests below
("state") is empty and we try to select the more remotely related
state__country. The regression here was not skipping the empty column results
for country before getting status.'
| def test_regression_8036(self):
| australia = Country.objects.create(name='Australia')
active = ClientStatus.objects.create(name='active')
client = Client.objects.create(name='client', status=active)
self.assertEqual(client.status, active)
self.assertEqual(Client.objects.select_related()[0].status, active)
self.assertEqual(Clien... |
'Exercising select_related() with multi-table model inheritance.'
| def test_multi_table_inheritance(self):
| c1 = Child.objects.create(name='child1', value=42)
i1 = Item.objects.create(name='item1', child=c1)
i2 = Item.objects.create(name='item2')
self.assertQuerysetEqual(Item.objects.select_related('child').order_by('name'), ['<Item: item1>', '<Item: item2>'])
|
'Regression for #12851
Deferred fields are used correctly if you select_related a subset
of fields.'
| def test_regression_12851(self):
| australia = Country.objects.create(name='Australia')
active = ClientStatus.objects.create(name='active')
wa = State.objects.create(name='Western Australia', country=australia)
c1 = Client.objects.create(name='Brian Burke', state=wa, status=active)
burke = Client.objects.select_related('state')... |
'Ensure that CharField.widget_attrs() always returns a dictionary.
Refs #15912'
| def test_charfield_widget_attrs(self):
| f = CharField()
self.assertEqual(f.widget_attrs(TextInput()), {})
f = CharField(max_length=10)
self.assertEqual(f.widget_attrs(HiddenInput()), {})
self.assertEqual(f.widget_attrs(TextInput()), {'maxlength': '10'})
self.assertEqual(f.widget_attrs(PasswordInput()), {'maxlength': '10'})
|
'Formsets with no forms should still evaluate as true.
Regression test for #15722'
| def test_formset_nonzero(self):
| ChoiceFormset = formset_factory(Choice, extra=0)
formset = ChoiceFormset()
self.assertEqual(len(formset.forms), 0)
self.assertTrue(formset)
|
'If a model\'s ForeignKey has blank=False and a default, no empty option is created (Refs #10792).'
| def test_no_empty_option(self):
| option = ChoiceOptionModel.objects.create(name='default')
choices = list(ChoiceFieldForm().fields['choice'].choices)
self.assertEqual(len(choices), 1)
self.assertEqual(choices[0], (option.pk, unicode(option)))
|
'The initial value for a callable default returning a queryset is the pk (refs #13769)'
| def test_callable_initial_value(self):
| obj1 = ChoiceOptionModel.objects.create(id=1, name='default')
obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2')
obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3')
self.assertHTMLEqual(ChoiceFieldForm().as_p(), '<p><label for="id_choice">Choice:</label> <select nam... |
'Initial instances for model fields may also be instances (refs #7287)'
| def test_initial_instance_value(self):
| obj1 = ChoiceOptionModel.objects.create(id=1, name='default')
obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2')
obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3')
self.assertHTMLEqual(ChoiceFieldForm(initial={'choice': obj2, 'choice_int': obj2, 'multi_choice': [obj2, obj3]... |
'Test for issue 10405'
| def test_invalid_loading_order(self):
| class A(models.Model, ):
ref = models.ForeignKey('B')
class Meta:
model = A
self.assertRaises(ValueError, ModelFormMetaclass, 'Form', (ModelForm,), {'Meta': Meta})
class B(models.Model, ):
pass
|
'Test for issue 10405'
| def test_valid_loading_order(self):
| class A(models.Model, ):
ref = models.ForeignKey('B')
class B(models.Model, ):
pass
class Meta:
model = A
self.assertTrue(issubclass(ModelFormMetaclass('Form', (ModelForm,), {'Meta': Meta}), ModelForm))
|
'Ensure that the NullBooleanSelect widget\'s options are lazily
localized.
Refs #17190'
| def test_nullbooleanselect(self):
| f = NullBooleanSelectLazyForm()
self.assertHTMLEqual(f.fields['bool'].widget.render('id_bool', True), u'<select name="id_bool">\n<option value="1">Unbekannt</option>\n<option value="2" selected="selected">Ja</option>\n<option value="3">Nein</option>\n</select>')
|
'When choices are set for this widget, we want to pass those along to the Select widget'
| def _set_choices(self, choices):
| self.widgets[0].choices = choices
|
'The choices for this widget are the Select widget\'s choices'
| def _get_choices(self):
| return self.widgets[0].choices
|
'A ClearableFileInput with is_required False and rendered with
an initial value that is a file renders a clear checkbox.'
| def test_clear_input_renders(self):
| widget = ClearableFileInput()
widget.is_required = False
self.assertHTMLEqual(widget.render('myfile', FakeFieldFile()), u'Currently: <a href="something">something</a> <input type="checkbox" name="myfile-clear" id="myfile-clear_id" /> <label for="myfile-clear_id">Clear</label><br ... |
'A ClearableFileInput should escape name, filename and URL when
rendering HTML. Refs #15182.'
| def test_html_escaped(self):
| class StrangeFieldFile(object, ):
url = 'something?chapter=1§=2©=3&lang=en'
def __unicode__(self):
return u'something<div onclick="alert(\'oops\')">.jpg'
widget = ClearableFileInput()
field = StrangeFieldFile()
output = widget.render('my<div>file', field)
self.... |
'A ClearableFileInput with is_required=False does not render a clear
checkbox.'
| def test_clear_input_renders_only_if_not_required(self):
| widget = ClearableFileInput()
widget.is_required = True
self.assertHTMLEqual(widget.render('myfile', FakeFieldFile()), u'Currently: <a href="something">something</a> <br />Change: <input type="file" name="myfile" />')
|
'A ClearableFileInput instantiated with no initial value does not render
a clear checkbox.'
| def test_clear_input_renders_only_if_initial(self):
| widget = ClearableFileInput()
widget.is_required = False
self.assertHTMLEqual(widget.render('myfile', None), u'<input type="file" name="myfile" />')
|
'ClearableFileInput.value_from_datadict returns False if the clear
checkbox is checked, if not required.'
| def test_clear_input_checked_returns_false(self):
| widget = ClearableFileInput()
widget.is_required = False
self.assertEqual(widget.value_from_datadict(data={'myfile-clear': True}, files={}, name='myfile'), False)
|
'ClearableFileInput.value_from_datadict never returns False if the field
is required.'
| def test_clear_input_checked_returns_false_only_if_not_required(self):
| widget = ClearableFileInput()
widget.is_required = True
f = SimpleUploadedFile('something.txt', 'content')
self.assertEqual(widget.value_from_datadict(data={'myfile-clear': True}, files={'myfile': f}, name='myfile'), f)
|
'Test that we are able to modify a form field validators list without polluting
other forms'
| def test_validators_independence(self):
| from django.core.validators import MaxValueValidator
class MyForm(Form, ):
myfield = CharField(max_length=25)
f1 = MyForm()
f2 = MyForm()
f1.fields['myfield'].validators[0] = MaxValueValidator(12)
self.assertFalse((f1.fields['myfield'].validators[0] == f2.fields['myfield'].validators[0])... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.