desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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_unsafe_email(custom_exception_reporter_filter_view)
'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_params=False) self.verify_safe_email(sensitive_method_view, check_for_POST_params=False)
'Ensure that sensitive variables don\'t leak in the sensitive_variables decorator\'s frame, when those variables are passed as arguments to the decorated function. Refs #19453.'
def test_sensitive_function_arguments(self):
with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_args_function_caller) self.verify_unsafe_email(sensitive_args_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_args_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_args_function_caller, check_for_POST_params=False)
'Ensure that sensitive variables don\'t leak in the sensitive_variables decorator\'s frame, when those variables are passed as keyword arguments to the decorated function. Refs #19453.'
def test_sensitive_function_keyword_arguments(self):
with self.settings(DEBUG=True): self.verify_unsafe_response(sensitive_kwargs_function_caller) self.verify_unsafe_email(sensitive_kwargs_function_caller) with self.settings(DEBUG=False): self.verify_safe_response(sensitive_kwargs_function_caller, check_for_POST_params=False) self.verify_safe_email(sensitive_kwargs_function_caller, check_for_POST_params=False)
'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(u'__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(u'error', MyWarning) self.assertRaises(Warning, (lambda : warnings.warn(u'warn', MyWarning))) self.restore_warnings_state() warnings.simplefilter(u'ignore', MyWarning) warnings.warn(u'warn', MyWarning) self.restore_warnings_state()
'assertRaisesMessage shouldn\'t interpret RE special chars.'
def test_special_re_chars(self):
def func1(): raise ValueError(u'[.*x+]y?') self.assertRaisesMessage(ValueError, u'[.*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.assertJSONEqual(out.getvalue().strip(), ('[{"pk": %(m_pk)s, "model": "m2m_through_regress.membership", "fields": {"person": %(p_pk)s, "price": 100, "group": %(g_pk)s}}, {"pk": %(p_pk)s, "model": "m2m_through_regress.person", "fields": {"name": "Bob"}}, {"pk": %(g_pk)s, "model": "m2m_through_regress.group", "fields": {"name": "Roll"}}]' % pks)) out = StringIO() management.call_command('dumpdata', 'm2m_through_regress', format='xml', indent=2, stdout=out) self.assertXMLEqual(out.getvalue().strip(), ('\n<?xml version="1.0" encoding="utf-8"?>\n<django-objects version="1.0">\n <object pk="%(m_pk)s" model="m2m_through_regress.membership">\n <field to="m2m_through_regress.person" name="person" rel="ManyToOneRel">%(p_pk)s</field>\n <field to="m2m_through_regress.group" name="group" rel="ManyToOneRel">%(g_pk)s</field>\n <field type="IntegerField" name="price">100</field>\n </object>\n <object pk="%(p_pk)s" model="m2m_through_regress.person">\n <field type="CharField" name="name">Bob</field>\n </object>\n <object pk="%(g_pk)s" model="m2m_through_regress.group">\n <field type="CharField" name="name">Roll</field>\n </object>\n</django-objects>\n '.strip() % pks))
'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.create(person=bob, group=roll, price=50) self.assertQuerysetEqual(rock.members.filter(membership__price=50), ['<Person: Jim>']) self.assertQuerysetEqual(bob.group_set.filter(membership__price=50), ['<Group: Roll>'])
'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.assertJSONEqual(out.getvalue().strip(), '[{"pk": 1, "model": "m2m_through_regress.usermembership", "fields": {"price": 100, "group": 1, "user": 1}}, {"pk": 1, "model": "m2m_through_regress.person", "fields": {"name": "Guido"}}, {"pk": 1, "model": "m2m_through_regress.group", "fields": {"name": "Python Core Group"}}]')
'Permissions and content types are not created for a swapped model'
@override_settings(TEST_ARTICLE_MODEL=u'swappable_models.AlternateArticle') def test_generated_data(self):
Permission.objects.filter(content_type__app_label=u'swappable_models').delete() ContentType.objects.filter(app_label=u'swappable_models').delete() new_io = StringIO() management.call_command(u'syncdb', load_initial_data=False, interactive=False, stdout=new_io) apps_models = [(p.content_type.app_label, p.content_type.model) for p in Permission.objects.all()] self.assertIn((u'swappable_models', u'alternatearticle'), apps_models) self.assertNotIn((u'swappable_models', u'article'), apps_models) apps_models = [(ct.app_label, ct.model) for ct in ContentType.objects.all()] self.assertIn((u'swappable_models', u'alternatearticle'), apps_models) self.assertNotIn((u'swappable_models', u'article'), apps_models)
'Model names are case insensitive. Check that model swapping honors this.'
@override_settings(TEST_ARTICLE_MODEL=u'swappable_models.article') def test_case_insensitive(self):
try: Article.objects.all() except AttributeError: self.fail(u'Swappable model names should be case insensitive.') self.assertIsNone(Article._meta.swapped)
'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.verifyGetCommentList() with self.assertNumQueries(3): self.verifyGetCommentList() ContentType.objects.clear_cache() with self.assertNumQueries(3): self.testRenderCommentForm() with self.assertNumQueries(2): self.testRenderCommentForm() ContentType.objects.clear_cache() with self.assertNumQueries(3): self.testGetCommentForm() with self.assertNumQueries(2): self.testGetCommentForm() ContentType.objects.clear_cache() with self.assertNumQueries(3): self.verifyGetCommentCount() with self.assertNumQueries(2): self.verifyGetCommentCount()
'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.assertFalse(f.is_valid()) settings.COMMENTS_ALLOW_PROFANITIES = True f = CommentForm(a, data=dict(d, comment='What a rooster!')) self.assertTrue(f.is_valid()) (settings.PROFANITIES_LIST, settings.COMMENTS_ALLOW_PROFANITIES) = saved
'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[u'security_hash'] = u'Nobody expects the Spanish Inquisition!' response = self.client.post(u'/post/', data) self.assertEqual(response.status_code, 400) self.assertTemplateUsed(response, u'comments/400-debug.html') settings.DEBUG = False response = self.client.post(u'/post/', data) self.assertEqual(response.status_code, 400) self.assertTemplateNotUsed(response, u'comments/400-debug.html') settings.DEBUG = olddebug
'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=u'jane_other', email=u'[email protected]', password=u'jane_other') a = Article.objects.get(pk=1) data = self.getValidData(a) data[u'name'] = data[u'email'] = u'' self.client.login(username=u'jane_other', password=u'jane_other') self.response = self.client.post(u'/post/', data, REMOTE_ADDR=u'1.2.3.4') c = Comment.objects.get(user=user) self.assertEqual(c.ip_address, u'1.2.3.4') self.assertEqual(c.user_name, u'jane_other') user.delete()
'Prevent posting the exact same comment twice'
def testPreventDuplicateComments(self):
a = Article.objects.get(pk=1) data = self.getValidData(a) self.client.post(u'/post/', data) self.client.post(u'/post/', data) self.assertEqual(Comment.objects.count(), 1) self.client.post(u'/post/', dict(data, comment=u'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[u'comment'].comment, u'This is my comment') self.assertTrue((u'request' in kwargs)) received_signals.append(kwargs.get(u'signal')) received_signals = [] expected_signals = [signals.comment_will_be_posted, signals.comment_was_posted] for signal in expected_signals: signal.connect(receive) self.testCreateValidComment() self.assertEqual(received_signals, expected_signals) for signal in expected_signals: signal.disconnect(receive)
'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=u'comment-test') a = Article.objects.get(pk=1) data = self.getValidData(a) response = self.client.post(u'/post/', data) self.assertEqual(response.status_code, 400) self.assertEqual(Comment.objects.count(), 0) signals.comment_will_be_posted.disconnect(dispatch_uid=u'comment-test')
'Test that the comment_will_be_posted signal can modify a comment before it gets posted'
def testWillBePostedSignalModifyComment(self):
def receive(sender, **kwargs): kwargs[u'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(u'/post/', data) location = response[u'Location'] match = post_redirect_re.match(location) self.assertTrue((match != None), (u'Unexpected redirect location: %s' % location)) data[u'next'] = u'/somewhere/else/' data[u'comment'] = u'This is another comment' response = self.client.post(u'/post/', data) location = response[u'Location'] match = re.search(u'^http://testserver/somewhere/else/\\?c=\\d+$', location) self.assertTrue((match != None), (u'Unexpected redirect location: %s' % location)) data[u'next'] = u'http://badserver/somewhere/else/' data[u'comment'] = u'This is another comment with an unsafe next url' response = self.client.post(u'/post/', data) location = response[u'Location'] match = post_redirect_re.match(location) self.assertTrue((match != None), (u'Unsafe redirection to: %s' % location))
'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[u'next'] = u'/somewhere/else/?foo=bar' data[u'comment'] = u'This is another comment' response = self.client.post(u'/post/', data) location = response[u'Location'] match = re.search(u'^http://testserver/somewhere/else/\\?foo=bar&c=\\d+$', location) self.assertTrue((match != None), (u'Unexpected redirect location: %s' % location))
'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[u'comment'] = u'This is another comment' response = self.client.post(u'/post/', data) location = response[u'Location'] broken_location = (location + u'\ufffd') response = self.client.get(broken_location) self.assertEqual(response.status_code, 200)
'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[u'next'] = u'/somewhere/else/?foo=bar#baz' data[u'comment'] = u'This is another comment' response = self.client.post(u'/post/', data) location = response[u'Location'] match = re.search(u'^http://testserver/somewhere/else/\\?foo=bar&c=\\d+#baz$', location) self.assertTrue((match != None), (u'Unexpected redirect location: %s' % location)) a = Article.objects.get(pk=1) data = self.getValidData(a) data[u'next'] = u'/somewhere/else/#baz' data[u'comment'] = u'This is another comment' response = self.client.post(u'/post/', data) location = response[u'Location'] match = re.search(u'^http://testserver/somewhere/else/\\?c=\\d+#baz$', location) self.assertTrue((match != None), (u'Unexpected redirect location: %s' % location))
'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.assertEqual(c.flags.filter(flag=CommentFlag.SUGGEST_REMOVAL).count(), 1) return c
'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=%d' % pk))
'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://testserver/accounts/login/?next=/flag/%d/' % pk))
'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.testFlagPost() self.assertEqual(received_signals, [signals.comment_was_flagged]) signals.comment_was_flagged.disconnect(receive)
'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') response = self.client.get(('/delete/%d/' % pk)) self.assertEqual(response.status_code, 200)
'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.objects.get(pk=pk) self.assertTrue(c.is_removed) self.assertEqual(c.flags.filter(flag=CommentFlag.MODERATOR_DELETION, user__username='normaluser').count(), 1)
'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=%d' % pk))
'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/deleted/?c=%d' % pk))
'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('normaluser') response = self.client.get(('/approve/%d/' % pk)) self.assertEqual(response.status_code, 200)
'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=%d' % c1.pk)) c = Comment.objects.get(pk=c1.pk) self.assertTrue(c.is_public) self.assertEqual(c.flags.filter(flag=CommentFlag.MODERATOR_APPROVAL, user__username='normaluser').count(), 1)
'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://testserver/go/here/?c=%d' % c1.pk))
'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'], ('http://testserver/approved/?c=%d' % c1.pk))
'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.assertNotContains(response, '<option value="delete_selected">')
'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 = {u'serial': u'1', u'username': u'apollo13', u'usersite_set-TOTAL_FORMS': u'1', u'usersite_set-INITIAL_FORMS': u'0', u'usersite_set-MAX_NUM_FORMS': u'0', u'usersite_set-0-data': u'10', u'usersite_set-0-user': u'apollo13'} user = User() form = Form(data) if form.is_valid(): user = form.save() else: self.fail((u'Errors found on form:%s' % form_set)) form_set = FormSet(data, instance=user) if form_set.is_valid(): form_set.save() usersite = UserSite.objects.all().values() self.assertEqual(usersite[0][u'data'], 10) self.assertEqual(usersite[0][u'user_id'], u'apollo13') else: self.fail((u'Errors found on formset:%s' % form_set.errors)) data = {u'usersite_set-TOTAL_FORMS': u'1', u'usersite_set-INITIAL_FORMS': u'1', u'usersite_set-MAX_NUM_FORMS': u'0', u'usersite_set-0-id': six.text_type(usersite[0][u'id']), u'usersite_set-0-data': u'11', u'usersite_set-0-user': u'apollo13'} form_set = FormSet(data, instance=user) if form_set.is_valid(): form_set.save() usersite = UserSite.objects.all().values() self.assertEqual(usersite[0][u'data'], 11) self.assertEqual(usersite[0][u'user_id'], u'apollo13') else: self.fail((u'Errors found on formset:%s' % form_set.errors)) data = {u'usersite_set-TOTAL_FORMS': u'2', u'usersite_set-INITIAL_FORMS': u'1', u'usersite_set-MAX_NUM_FORMS': u'0', u'usersite_set-0-id': six.text_type(usersite[0][u'id']), u'usersite_set-0-data': u'11', u'usersite_set-0-user': u'apollo13', u'usersite_set-1-data': u'42', u'usersite_set-1-user': u'apollo13'} form_set = FormSet(data, instance=user) if form_set.is_valid(): form_set.save() usersite = UserSite.objects.all().values().order_by(u'data') self.assertEqual(usersite[0][u'data'], 11) self.assertEqual(usersite[0][u'user_id'], u'apollo13') self.assertEqual(usersite[1][u'data'], 42) self.assertEqual(usersite[1][u'user_id'], u'apollo13') else: self.fail((u'Errors found on formset:%s' % form_set.errors))
'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 = {u'name': u"Guido's House of Pasta", u'manager_set-TOTAL_FORMS': u'1', u'manager_set-INITIAL_FORMS': u'0', u'manager_set-MAX_NUM_FORMS': u'0', u'manager_set-0-name': u'Guido Van Rossum'} restaurant = User() form = Form(data) if form.is_valid(): restaurant = form.save() else: self.fail((u'Errors found on form:%s' % form_set)) form_set = FormSet(data, instance=restaurant) if form_set.is_valid(): form_set.save() manager = Manager.objects.all().values() self.assertEqual(manager[0][u'name'], u'Guido Van Rossum') else: self.fail((u'Errors found on formset:%s' % form_set.errors)) data = {u'manager_set-TOTAL_FORMS': u'1', u'manager_set-INITIAL_FORMS': u'1', u'manager_set-MAX_NUM_FORMS': u'0', u'manager_set-0-id': six.text_type(manager[0][u'id']), u'manager_set-0-name': u'Terry Gilliam'} form_set = FormSet(data, instance=restaurant) if form_set.is_valid(): form_set.save() manager = Manager.objects.all().values() self.assertEqual(manager[0][u'name'], u'Terry Gilliam') else: self.fail((u'Errors found on formset:%s' % form_set.errors)) data = {u'manager_set-TOTAL_FORMS': u'2', u'manager_set-INITIAL_FORMS': u'1', u'manager_set-MAX_NUM_FORMS': u'0', u'manager_set-0-id': six.text_type(manager[0][u'id']), u'manager_set-0-name': u'Terry Gilliam', u'manager_set-1-name': u'John Cleese'} form_set = FormSet(data, instance=restaurant) if form_set.is_valid(): form_set.save() manager = Manager.objects.all().values().order_by(u'name') self.assertEqual(manager[0][u'name'], u'John Cleese') self.assertEqual(manager[1][u'name'], u'Terry Gilliam') else: self.fail((u'Errors found on formset:%s' % form_set.errors))
'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((u'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=u'EFNet') host1 = Host.objects.create(hostname=u'irc.he.net', network=efnet) HostFormSet = inlineformset_factory(Network, Host) data = {u'host_set-TOTAL_FORMS': u'2', u'host_set-INITIAL_FORMS': u'1', u'host_set-MAX_NUM_FORMS': u'0', u'host_set-0-id': six.text_type(host1.id), u'host_set-0-hostname': u'tranquility.hub.dal.net', u'host_set-1-hostname': u'matrix.de.eu.dal.net'} dalnet = Network.objects.create(name=u'DALnet') formset = HostFormSet(data, instance=dalnet, save_as_new=True) self.assertTrue(formset.is_valid()) formset.save() self.assertQuerysetEqual(dalnet.host_set.order_by(u'hostname'), [u'<Host: matrix.de.eu.dal.net>', u'<Host: tranquility.hub.dal.net>'])
'Test the type of Formset and Form error attributes'
def test_error_class(self):
Formset = modelformset_factory(User) data = {u'form-TOTAL_FORMS': u'2', u'form-INITIAL_FORMS': u'0', u'form-MAX_NUM_FORMS': u'0', u'form-0-id': u'', u'form-0-username': u'apollo13', u'form-0-serial': u'1', u'form-1-id': u'', u'form-1-username': u'apollo13', u'form-1-serial': u'2'} formset = Formset(data) self.assertTrue(isinstance(formset.errors, list)) self.assertTrue(isinstance(formset.non_form_errors(), ErrorList)) for form in formset.forms: self.assertTrue(isinstance(form.errors, ErrorDict)) self.assertTrue(isinstance(form.non_field_errors(), ErrorList))
'delete form if odd PK'
def should_delete(self):
return ((self.instance.pk % 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[u'form-INITIAL_FORMS'] = 4 data.update(dict((((u'form-%d-id' % i), user.pk) for (i, user) in enumerate(User.objects.all())))) formset = self.NormalFormset(data, queryset=User.objects.all()) self.assertTrue(formset.is_valid()) self.assertEqual(len(formset.save()), 0) self.assertEqual(len(User.objects.all()), 4)
'Verify base formset honors DELETE field'
def test_all_delete(self):
self.test_init_database() data = dict(self.data) data[u'form-INITIAL_FORMS'] = 4 data.update(dict((((u'form-%d-id' % i), user.pk) for (i, user) in enumerate(User.objects.all())))) data.update(self.delete_all_ids) formset = self.NormalFormset(data, queryset=User.objects.all()) self.assertTrue(formset.is_valid()) self.assertEqual(len(formset.save()), 0) self.assertEqual(len(User.objects.all()), 0)
'Verify DeleteFormset ignores DELETE field and uses form method'
def test_custom_delete(self):
self.test_init_database() data = dict(self.data) data[u'form-INITIAL_FORMS'] = 4 data.update(dict((((u'form-%d-id' % i), user.pk) for (i, user) in enumerate(User.objects.all())))) data.update(self.delete_all_ids) formset = self.DeleteFormset(data, queryset=User.objects.all()) self.assertTrue(formset.is_valid()) self.assertEqual(len(formset.save()), 0) self.assertEqual(len(User.objects.all()), 2) odd_ids = [user.pk for user in User.objects.all() if (user.pk % 2)] self.assertEqual(len(odd_ids), 0)
'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 more than the absolute minimum number of tables (history has shown that it\'s easy to make a mistake in the implementation and include some unnecessary bonus joins).'
def test_regression_7110(self):
b = Building.objects.create(name=u'101') dev1 = Device.objects.create(name=u'router', building=b) dev2 = Device.objects.create(name=u'switch', building=b) dev3 = Device.objects.create(name=u'server', building=b) port1 = Port.objects.create(port_number=u'4', device=dev1) port2 = Port.objects.create(port_number=u'7', device=dev2) port3 = Port.objects.create(port_number=u'1', device=dev3) c1 = Connection.objects.create(start=port1, end=port2) c2 = Connection.objects.create(start=port2, end=port3) connections = Connection.objects.filter(start__device__building=b, end__device__building=b).order_by(u'id') self.assertEqual([(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections], [(c1.id, u'router/4', u'switch/7'), (c2.id, u'switch/7', u'server/1')]) connections = Connection.objects.filter(start__device__building=b, end__device__building=b).select_related().order_by(u'id') self.assertEqual([(c.id, six.text_type(c.start), six.text_type(c.end)) for c in connections], [(c1.id, u'router/4', u'switch/7'), (c2.id, u'switch/7', u'server/1')]) self.assertEqual(str(connections.query).count(u' JOIN '), 6)
'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=u'std') usp = Person.objects.create(user=us) uo = TUser.objects.create(name=u'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.create(std=s, cls=c) e_related = Enrollment.objects.all().select_related()[0] self.assertEqual(e_related.std.person.user.name, u'std') self.assertEqual(e_related.cls.org.person.user.name, u'org')
'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=u'Australia') active = ClientStatus.objects.create(name=u'active') client = Client.objects.create(name=u'client', status=active) self.assertEqual(client.status, active) self.assertEqual(Client.objects.select_related()[0].status, active) self.assertEqual(Client.objects.select_related(u'state')[0].status, active) self.assertEqual(Client.objects.select_related(u'state', u'status')[0].status, active) self.assertEqual(Client.objects.select_related(u'state__country')[0].status, active) self.assertEqual(Client.objects.select_related(u'state__country', u'status')[0].status, active) self.assertEqual(Client.objects.select_related(u'status')[0].status, active)
'Exercising select_related() with multi-table model inheritance.'
def test_multi_table_inheritance(self):
c1 = Child.objects.create(name=u'child1', value=42) i1 = Item.objects.create(name=u'item1', child=c1) i2 = Item.objects.create(name=u'item2') self.assertQuerysetEqual(Item.objects.select_related(u'child').order_by(u'name'), [u'<Item: item1>', u'<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=u'Australia') active = ClientStatus.objects.create(name=u'active') wa = State.objects.create(name=u'Western Australia', country=australia) c1 = Client.objects.create(name=u'Brian Burke', state=wa, status=active) burke = Client.objects.select_related(u'state').defer(u'state__name').get(name=u'Brian Burke') self.assertEqual(burke.name, u'Brian Burke') self.assertEqual(burke.state.name, u'Western Australia') sc1 = SpecialClient.objects.create(name=u'Troy Buswell', state=wa, status=active, value=42) troy = SpecialClient.objects.select_related(u'state').defer(u'state__name').get(name=u'Troy Buswell') self.assertEqual(troy.name, u'Troy Buswell') self.assertEqual(troy.value, 42) self.assertEqual(troy.state.name, u'Western Australia') troy = SpecialClient.objects.select_related(u'state').defer(u'value', u'state__name').get(name=u'Troy Buswell') self.assertEqual(troy.name, u'Troy Buswell') self.assertEqual(troy.value, 42) self.assertEqual(troy.state.name, u'Western Australia') troy = SpecialClient.objects.select_related(u'state').only(u'name', u'state').get(name=u'Troy Buswell') self.assertEqual(troy.name, u'Troy Buswell') self.assertEqual(troy.value, 42) self.assertEqual(troy.state.name, u'Western Australia')
'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()), {u'maxlength': u'10'}) self.assertEqual(f.widget_attrs(PasswordInput()), {u'maxlength': u'10'})
'Ensure that it works with unicode characters. Refs #.'
def test_regexfield_6(self):
f = RegexField(u'^\\w+$') self.assertEqual(u'\xe9\xe8\xf8\xe7\xce\xce\u4f60\u597d', f.clean(u'\xe9\xe8\xf8\xe7\xce\xce\u4f60\u597d'))
'Test URLField correctly validates IPv6 (#18779).'
def test_urlfield_10(self):
f = URLField() urls = (u'http://::/', u'http://6:21b4:92/', u'http://[12:34:3a53]/', u'http://[a34:9238::]:8080/') for url in urls: self.assertEqual(url, f.clean(url))
'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)
'A formset has a hard limit on the number of forms instantiated.'
def test_hard_limit_on_instantiated_forms(self):
_old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 3 ChoiceFormSet = formset_factory(Choice) formset = ChoiceFormSet({u'choices-TOTAL_FORMS': u'4', u'choices-INITIAL_FORMS': u'0', u'choices-MAX_NUM_FORMS': u'4', u'choices-0-choice': u'Zero', u'choices-0-votes': u'0', u'choices-1-choice': u'One', u'choices-1-votes': u'1', u'choices-2-choice': u'Two', u'choices-2-votes': u'2', u'choices-3-choice': u'Three', u'choices-3-votes': u'3'}, prefix=u'choices') self.assertEqual(len(formset.forms), 3) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM
'Can increase the built-in forms limit via a higher max_num.'
def test_increase_hard_limit(self):
_old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 3 ChoiceFormSet = formset_factory(Choice, max_num=4) formset = ChoiceFormSet({u'choices-TOTAL_FORMS': u'4', u'choices-INITIAL_FORMS': u'0', u'choices-MAX_NUM_FORMS': u'4', u'choices-0-choice': u'Zero', u'choices-0-votes': u'0', u'choices-1-choice': u'One', u'choices-1-votes': u'1', u'choices-2-choice': u'Two', u'choices-2-votes': u'2', u'choices-3-choice': u'Three', u'choices-3-votes': u'3'}, prefix=u'choices') self.assertEqual(len(formset.forms), 4) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM
'Test that an empty formset still calls clean()'
def test_empty_formset_is_valid(self):
EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate) formset = EmptyFsetWontValidateFormset(data={u'form-INITIAL_FORMS': u'0', u'form-TOTAL_FORMS': u'0'}, prefix=u'form') formset2 = EmptyFsetWontValidateFormset(data={u'form-INITIAL_FORMS': u'0', u'form-TOTAL_FORMS': u'1', u'form-0-name': u'bah'}, prefix=u'form') self.assertFalse(formset.is_valid()) self.assertFalse(formset2.is_valid())
'Make sure media is available on empty formset, refs #19545'
def test_empty_formset_media(self):
class MediaForm(Form, ): class Media: js = (u'some-file.js',) self.assertIn(u'some-file.js', str(formset_factory(MediaForm, extra=0)().media))
'Make sure `is_multipart()` works with empty formset, refs #19545'
def test_empty_formset_is_multipart(self):
class FileForm(Form, ): file = FileField() self.assertTrue(formset_factory(FileForm, extra=0)().is_multipart())
'If a model\'s ManyToManyField has blank=True and is saved with no data, a queryset is returned.'
def test_empty_queryset_return(self):
form = OptionalMultiChoiceModelForm({u'multi_choice_optional': u'', u'multi_choice': [u'1']}) self.assertTrue(form.is_valid()) self.assertTrue(isinstance(form.cleaned_data[u'multi_choice_optional'], models.query.QuerySet)) self.assertTrue(isinstance(form.cleaned_data[u'multi_choice'], models.query.QuerySet))
'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=u'default') choices = list(ChoiceFieldForm().fields[u'choice'].choices) self.assertEqual(len(choices), 1) self.assertEqual(choices[0], (option.pk, six.text_type(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=u'default') obj2 = ChoiceOptionModel.objects.create(id=2, name=u'option 2') obj3 = ChoiceOptionModel.objects.create(id=3, name=u'option 3') self.assertHTMLEqual(ChoiceFieldForm().as_p(), u'<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">\n<option value="1" selected="selected">ChoiceOption 1</option>\n<option value="2">ChoiceOption 2</option>\n<option value="3">ChoiceOption 3</option>\n</select><input type="hidden" name="initial-choice" value="1" id="initial-id_choice" /></p>\n<p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int">\n<option value="1" selected="selected">ChoiceOption 1</option>\n<option value="2">ChoiceOption 2</option>\n<option value="3">ChoiceOption 3</option>\n</select><input type="hidden" name="initial-choice_int" value="1" id="initial-id_choice_int" /></p>\n<p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice">\n<option value="1" selected="selected">ChoiceOption 1</option>\n<option value="2">ChoiceOption 2</option>\n<option value="3">ChoiceOption 3</option>\n</select><input type="hidden" name="initial-multi_choice" value="1" id="initial-id_multi_choice_0" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p>\n<p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int">\n<option value="1" selected="selected">ChoiceOption 1</option>\n<option value="2">ChoiceOption 2</option>\n<option value="3">ChoiceOption 3</option>\n</select><input type="hidden" name="initial-multi_choice_int" value="1" id="initial-id_multi_choice_int_0" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p>')
'Initial instances for model fields may also be instances (refs #7287)'
def test_initial_instance_value(self):
obj1 = ChoiceOptionModel.objects.create(id=1, name=u'default') obj2 = ChoiceOptionModel.objects.create(id=2, name=u'option 2') obj3 = ChoiceOptionModel.objects.create(id=3, name=u'option 3') self.assertHTMLEqual(ChoiceFieldForm(initial={u'choice': obj2, u'choice_int': obj2, u'multi_choice': [obj2, obj3], u'multi_choice_int': ChoiceOptionModel.objects.exclude(name=u'default')}).as_p(), u'<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">\n<option value="1">ChoiceOption 1</option>\n<option value="2" selected="selected">ChoiceOption 2</option>\n<option value="3">ChoiceOption 3</option>\n</select><input type="hidden" name="initial-choice" value="2" id="initial-id_choice" /></p>\n<p><label for="id_choice_int">Choice int:</label> <select name="choice_int" id="id_choice_int">\n<option value="1">ChoiceOption 1</option>\n<option value="2" selected="selected">ChoiceOption 2</option>\n<option value="3">ChoiceOption 3</option>\n</select><input type="hidden" name="initial-choice_int" value="2" id="initial-id_choice_int" /></p>\n<p><label for="id_multi_choice">Multi choice:</label> <select multiple="multiple" name="multi_choice" id="id_multi_choice">\n<option value="1">ChoiceOption 1</option>\n<option value="2" selected="selected">ChoiceOption 2</option>\n<option value="3" selected="selected">ChoiceOption 3</option>\n</select><input type="hidden" name="initial-multi_choice" value="2" id="initial-id_multi_choice_0" />\n<input type="hidden" name="initial-multi_choice" value="3" id="initial-id_multi_choice_1" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p>\n<p><label for="id_multi_choice_int">Multi choice int:</label> <select multiple="multiple" name="multi_choice_int" id="id_multi_choice_int">\n<option value="1">ChoiceOption 1</option>\n<option value="2" selected="selected">ChoiceOption 2</option>\n<option value="3" selected="selected">ChoiceOption 3</option>\n</select><input type="hidden" name="initial-multi_choice_int" value="2" id="initial-id_multi_choice_int_0" />\n<input type="hidden" name="initial-multi_choice_int" value="3" id="initial-id_multi_choice_int_1" /> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></p>')
'Test for issue 10405'
def test_invalid_loading_order(self):
class A(models.Model, ): ref = models.ForeignKey(u'B') class Meta: model = A self.assertRaises(ValueError, ModelFormMetaclass, str(u'Form'), (ModelForm,), {u'Meta': Meta}) class B(models.Model, ): pass
'Test for issue 10405'
def test_valid_loading_order(self):
class A(models.Model, ): ref = models.ForeignKey(u'B') class B(models.Model, ): pass class Meta: model = A self.assertTrue(issubclass(ModelFormMetaclass(str(u'Form'), (ModelForm,), {u'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[u'bool'].widget.render(u'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
'Test that a roundtrip on a ModelForm doesn\'t alter the TextField value'
def test_textarea_trailing_newlines(self):
article = Article.objects.create(content=u'\nTst\n') self.selenium.get((u'%s%s' % (self.live_server_url, reverse(u'article_form', args=[article.pk])))) self.selenium.find_element_by_id(u'submit').submit() article = Article.objects.get(pk=article.pk) self.assertEqual(article.content, u'\r\nTst\r\n')
'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(u'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 />Change: <input type="file" name="myfile" />')
'A ClearableFileInput should escape name, filename and URL when rendering HTML. Refs #15182.'
def test_html_escaped(self):
@python_2_unicode_compatible class StrangeFieldFile(object, ): url = u'something?chapter=1&sect=2&copy=3&lang=en' def __str__(self): return u'something<div onclick="alert(\'oops\')">.jpg' widget = ClearableFileInput() field = StrangeFieldFile() output = widget.render(u'my<div>file', field) self.assertFalse((field.url in output)) self.assertTrue((u'href="something?chapter=1&amp;sect=2&amp;copy=3&amp;lang=en"' in output)) self.assertFalse((six.text_type(field) in output)) self.assertTrue((u'something&lt;div onclick=&quot;alert(&#39;oops&#39;)&quot;&gt;.jpg' in output)) self.assertTrue((u'my&lt;div&gt;file' in output)) self.assertFalse((u'my<div>file' in output))
'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(u'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(u'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={u'myfile-clear': True}, files={}, name=u'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(u'something.txt', 'content') self.assertEqual(widget.value_from_datadict(data={u'myfile-clear': True}, files={u'myfile': f}, name=u'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[u'myfield'].validators[0] = MaxValueValidator(12) self.assertFalse((f1.fields[u'myfield'].validators[0] == f2.fields[u'myfield'].validators[0]))
'Re-cleaning an instance that was added via a ModelForm should not raise a pk uniqueness error.'
def test_regression_14234(self):
class CheeseForm(ModelForm, ): class Meta: model = Cheese form = CheeseForm({u'name': u'Brie'}) self.assertTrue(form.is_valid()) obj = form.save() obj.name = u'Camembert' obj.full_clean()
'Ensure that SelectDateWidget._has_changed() works correctly with a localized date format. Refs #17165.'
def test_l10n_date_changed(self):
b = GetDate({u'mydate_year': u'2008', u'mydate_month': u'4', u'mydate_day': u'1'}, initial={u'mydate': datetime.date(2008, 4, 1)}) self.assertFalse(b.has_changed()) b = GetDate({u'mydate_year': u'2008', u'mydate_month': u'4', u'mydate_day': u'2'}, initial={u'mydate': datetime.date(2008, 4, 1)}) self.assertTrue(b.has_changed()) b = GetDateShowHiddenInitial({u'mydate_year': u'2008', u'mydate_month': u'4', u'mydate_day': u'1', u'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 1))}, initial={u'mydate': datetime.date(2008, 4, 1)}) self.assertFalse(b.has_changed()) b = GetDateShowHiddenInitial({u'mydate_year': u'2008', u'mydate_month': u'4', u'mydate_day': u'22', u'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 1))}, initial={u'mydate': datetime.date(2008, 4, 1)}) self.assertTrue(b.has_changed()) b = GetDateShowHiddenInitial({u'mydate_year': u'2008', u'mydate_month': u'4', u'mydate_day': u'22', u'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 1))}, initial={u'mydate': datetime.date(2008, 4, 22)}) self.assertTrue(b.has_changed()) b = GetDateShowHiddenInitial({u'mydate_year': u'2008', u'mydate_month': u'4', u'mydate_day': u'22', u'initial-mydate': HiddenInput()._format_value(datetime.date(2008, 4, 22))}, initial={u'mydate': datetime.date(2008, 4, 1)}) self.assertFalse(b.has_changed())
'TimeFields can parse dates in the default format'
def test_timeField(self):
f = forms.TimeField() self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') result = f.clean('13:30:05') self.assertEqual(result, time(13, 30, 5)) text = f.widget._format_value(result) self.assertEqual(text, '13:30:05') result = f.clean('13:30') self.assertEqual(result, time(13, 30, 0)) text = f.widget._format_value(result) self.assertEqual(text, '13:30:00')
'Localized TimeFields act as unlocalized widgets'
def test_localized_timeField(self):
f = forms.TimeField(localize=True) self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') result = f.clean('13:30:05') self.assertEqual(result, time(13, 30, 5)) text = f.widget._format_value(result) self.assertEqual(text, '13:30:05') result = f.clean('13:30') self.assertEqual(result, time(13, 30, 0)) text = f.widget._format_value(result) self.assertEqual(text, '13:30:00')
'TimeFields with manually specified input formats can accept those formats'
def test_timeField_with_inputformat(self):
f = forms.TimeField(input_formats=['%H.%M.%S', '%H.%M']) self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') self.assertRaises(forms.ValidationError, f.clean, '13:30:05') result = f.clean('13.30.05') self.assertEqual(result, time(13, 30, 5)) text = f.widget._format_value(result) self.assertEqual(text, '13:30:05') result = f.clean('13.30') self.assertEqual(result, time(13, 30, 0)) text = f.widget._format_value(result) self.assertEqual(text, '13:30:00')
'Localized TimeFields with manually specified input formats can accept those formats'
def test_localized_timeField_with_inputformat(self):
f = forms.TimeField(input_formats=['%H.%M.%S', '%H.%M'], localize=True) self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') self.assertRaises(forms.ValidationError, f.clean, '13:30:05') result = f.clean('13.30.05') self.assertEqual(result, time(13, 30, 5)) text = f.widget._format_value(result) self.assertEqual(text, '13:30:05') result = f.clean('13.30') self.assertEqual(result, time(13, 30, 0)) text = f.widget._format_value(result) self.assertEqual(text, '13:30:00')
'TimeFields can parse dates in the default format'
def test_timeField(self):
f = forms.TimeField() self.assertRaises(forms.ValidationError, f.clean, '13:30:05') result = f.clean('1:30:05 PM') self.assertEqual(result, time(13, 30, 5)) text = f.widget._format_value(result) self.assertEqual(text, '01:30:05 PM') result = f.clean('1:30 PM') self.assertEqual(result, time(13, 30, 0)) text = f.widget._format_value(result) self.assertEqual(text, '01:30:00 PM')
'Localized TimeFields act as unlocalized widgets'
def test_localized_timeField(self):
f = forms.TimeField(localize=True) self.assertRaises(forms.ValidationError, f.clean, '13:30:05') result = f.clean('1:30:05 PM') self.assertEqual(result, time(13, 30, 5)) text = f.widget._format_value(result) self.assertEqual(text, '01:30:05 PM') result = f.clean('01:30 PM') self.assertEqual(result, time(13, 30, 0)) text = f.widget._format_value(result) self.assertEqual(text, '01:30:00 PM')
'TimeFields with manually specified input formats can accept those formats'
def test_timeField_with_inputformat(self):
f = forms.TimeField(input_formats=['%H.%M.%S', '%H.%M']) self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') self.assertRaises(forms.ValidationError, f.clean, '13:30:05') result = f.clean('13.30.05') self.assertEqual(result, time(13, 30, 5)) text = f.widget._format_value(result) self.assertEqual(text, '01:30:05 PM') result = f.clean('13.30') self.assertEqual(result, time(13, 30, 0)) text = f.widget._format_value(result) self.assertEqual(text, '01:30:00 PM')
'Localized TimeFields with manually specified input formats can accept those formats'
def test_localized_timeField_with_inputformat(self):
f = forms.TimeField(input_formats=['%H.%M.%S', '%H.%M'], localize=True) self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM') self.assertRaises(forms.ValidationError, f.clean, '13:30:05') result = f.clean('13.30.05') self.assertEqual(result, time(13, 30, 5)) text = f.widget._format_value(result) self.assertEqual(text, '01:30:05 PM') result = f.clean('13.30') self.assertEqual(result, time(13, 30, 0)) text = f.widget._format_value(result) self.assertEqual(text, '01:30:00 PM')