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_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 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...
'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....
'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(...
'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.assertJSON...
'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.assertJSONEqual(out.getvalue().strip(), '[{"pk": 1, "model": "m2m_through_regress.usermembership", "fields": {"price": 100, "group": 1, "user": 1}}, {"pk": 1, "m...
'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_labe...
'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.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[u'security_hash'] = u'Nobody expects the Spanish Inquisition!' response = self.client.post(u'/post/', data) self.assertEqual(response.status_code, 400) self.assertTe...
'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'jane@example.com', 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....
'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...
'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.assertEqua...
'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'/some...
'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/\\?...
'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.assertE...
'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...
'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=%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:...
'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=%d' ...
'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.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_...
'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...
'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(hos...
'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) ...
'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.assertE...
'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...
'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...
'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=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.crea...
'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.c...
'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(Cl...
'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'st...
'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...
'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'choi...
'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-TO...
'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.Query...
'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 ...
'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,...
'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 ...
'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...
'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[...
'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.ass...
'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...
'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...
'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) ...
'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_...
'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(r...
'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...
'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) ...
'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_...