desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Ensure that the fieldsets validation is skipped when the ModelAdmin.get_form() method is overridden. Refs #19445.'
def test_custom_get_form_with_fieldsets(self):
validate(ValidFormFieldsets, Song)
'Tests for basic validation of \'exclude\' option values (#12689)'
def test_exclude_values(self):
class ExcludedFields1(admin.ModelAdmin, ): exclude = 'foo' self.assertRaisesMessage(ImproperlyConfigured, "'ExcludedFields1.exclude' must be a list or tuple.", validate, ExcludedFields1, Book)
'# Regression test for #9932 - exclude in InlineModelAdmin # should not contain the ForeignKey field used in ModelAdmin.model'
def test_exclude_inline_model_admin(self):
class SongInline(admin.StackedInline, ): model = Song exclude = ['album'] class AlbumAdmin(admin.ModelAdmin, ): model = Album inlines = [SongInline] self.assertRaisesMessage(ImproperlyConfigured, "SongInline cannot exclude the field 'album' - this is the foreign key to the parent model admin_validation.Album.", validate, AlbumAdmin, Album)
'Regression test for #15669 - Include app label in admin validation messages'
def test_app_label_in_admin_validation(self):
class RawIdNonexistingAdmin(admin.ModelAdmin, ): raw_id_fields = ('nonexisting',) self.assertRaisesMessage(ImproperlyConfigured, "'RawIdNonexistingAdmin.raw_id_fields' refers to field 'nonexisting' that is missing from model 'admin_validation.Album'.", validate, RawIdNonexistingAdmin, Album)
'Regression test for #11709 - when testing for fk excluding (when exclude is given) make sure fk_name is honored or things blow up when there is more than one fk to the parent model.'
def test_fk_exclusion(self):
class TwoAlbumFKAndAnEInline(admin.TabularInline, ): model = TwoAlbumFKAndAnE exclude = ('e',) fk_name = 'album1' validate_inline(TwoAlbumFKAndAnEInline, None, Album)
'Regression test for #12203/#12237 - Fail more gracefully when a M2M field that specifies the \'through\' option is included in the \'fields\' or the \'fieldsets\' ModelAdmin options.'
def test_graceful_m2m_fail(self):
class BookAdmin(admin.ModelAdmin, ): fields = ['authors'] self.assertRaisesMessage(ImproperlyConfigured, "'BookAdmin.fields' can't include the ManyToManyField field 'authors' because 'authors' manually specifies a 'through' model.", validate, BookAdmin, Book)
'Regression test for #12209 -- If the explicitly provided through model is specified as a string, the admin should still be able use Model.m2m_field.through'
def test_explicit_through_override(self):
class AuthorsInline(admin.TabularInline, ): model = Book.authors.through class BookAdmin(admin.ModelAdmin, ): inlines = [AuthorsInline] validate(BookAdmin, Book)
'Regression for ensuring ModelAdmin.fields can contain non-model fields that broke with r11737'
def test_non_model_fields(self):
class SongForm(forms.ModelForm, ): extra_data = forms.CharField() class Meta: model = Song class FieldsOnFormOnlyAdmin(admin.ModelAdmin, ): form = SongForm fields = ['title', 'extra_data'] validate(FieldsOnFormOnlyAdmin, Song)
'Regression for ensuring ModelAdmin.field can handle first elem being a non-model field (test fix for UnboundLocalError introduced with r16225).'
def test_non_model_first_field(self):
class SongForm(forms.ModelForm, ): extra_data = forms.CharField() class Meta: model = Song class FieldsOnFormOnlyAdmin(admin.ModelAdmin, ): form = SongForm fields = ['extra_data', 'title'] validate(FieldsOnFormOnlyAdmin, Song)
'Tests for bug #11193 (errors inside middleware shouldn\'t leave the initLock locked).'
@override_settings(MIDDLEWARE_CLASSES=42) def test_lock_safety(self):
handler = WSGIHandler() self.assertEqual(handler.initLock.locked(), False) with self.assertRaises(Exception): handler(None, None) self.assertEqual(handler.initLock.locked(), False)
'Tests for bug #15672 (\'request\' referenced before assignment)'
def test_bad_path_info(self):
environ = RequestFactory().get('/').environ environ['PATH_INFO'] = '\xed' handler = WSGIHandler() response = handler(environ, (lambda *a, **k: None)) self.assertEqual(response.status_code, 400)
'Test the structure and content of feeds generated by Rss201rev2Feed.'
def test_rss2_feed(self):
response = self.client.get(u'/syndication/rss2/') doc = minidom.parseString(response.content) feed_elem = doc.getElementsByTagName(u'rss') self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute(u'version'), u'2.0') chan_elem = feed.getElementsByTagName(u'channel') self.assertEqual(len(chan_elem), 1) chan = chan_elem[0] d = Entry.objects.latest(u'date').date ltz = tzinfo.LocalTimezone(d) last_build_date = rfc2822_date(d.replace(tzinfo=ltz)) self.assertChildNodes(chan, [u'title', u'link', u'description', u'language', u'lastBuildDate', u'item', u'atom:link', u'ttl', u'copyright', u'category']) self.assertChildNodeContent(chan, {u'title': u'My blog', u'description': u'A more thorough description of my blog.', u'link': u'http://example.com/blog/', u'language': u'en', u'lastBuildDate': last_build_date, u'ttl': u'600', u'copyright': u'Copyright (c) 2007, Sally Smith'}) self.assertCategories(chan, [u'python', u'django']) self.assertChildNodeContent(chan, {u'title': u'My blog', u'link': u'http://example.com/blog/'}) self.assertEqual(chan.getElementsByTagName(u'atom:link')[0].getAttribute(u'href'), u'http://example.com/syndication/rss2/') d = Entry.objects.get(pk=1).date ltz = tzinfo.LocalTimezone(d) pub_date = rfc2822_date(d.replace(tzinfo=ltz)) items = chan.getElementsByTagName(u'item') self.assertEqual(len(items), Entry.objects.count()) self.assertChildNodeContent(items[0], {u'title': u'My first entry', u'description': u'Overridden description: My first entry', u'link': u'http://example.com/blog/1/', u'guid': u'http://example.com/blog/1/', u'pubDate': pub_date, u'author': u'[email protected] (Sally Smith)'}) self.assertCategories(items[0], [u'python', u'testing']) for item in items: self.assertChildNodes(item, [u'title', u'link', u'description', u'guid', u'category', u'pubDate', u'author'])
'Test the structure and content of feeds generated by RssUserland091Feed.'
def test_rss091_feed(self):
response = self.client.get(u'/syndication/rss091/') doc = minidom.parseString(response.content) feed_elem = doc.getElementsByTagName(u'rss') self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute(u'version'), u'0.91') chan_elem = feed.getElementsByTagName(u'channel') self.assertEqual(len(chan_elem), 1) chan = chan_elem[0] self.assertChildNodes(chan, [u'title', u'link', u'description', u'language', u'lastBuildDate', u'item', u'atom:link', u'ttl', u'copyright', u'category']) self.assertChildNodeContent(chan, {u'title': u'My blog', u'link': u'http://example.com/blog/'}) self.assertCategories(chan, [u'python', u'django']) self.assertEqual(chan.getElementsByTagName(u'atom:link')[0].getAttribute(u'href'), u'http://example.com/syndication/rss091/') items = chan.getElementsByTagName(u'item') self.assertEqual(len(items), Entry.objects.count()) self.assertChildNodeContent(items[0], {u'title': u'My first entry', u'description': u'Overridden description: My first entry', u'link': u'http://example.com/blog/1/'}) for item in items: self.assertChildNodes(item, [u'title', u'link', u'description']) self.assertCategories(item, [])
'Test the structure and content of feeds generated by Atom1Feed.'
def test_atom_feed(self):
response = self.client.get(u'/syndication/atom/') feed = minidom.parseString(response.content).firstChild self.assertEqual(feed.nodeName, u'feed') self.assertEqual(feed.getAttribute(u'xmlns'), u'http://www.w3.org/2005/Atom') self.assertChildNodes(feed, [u'title', u'subtitle', u'link', u'id', u'updated', u'entry', u'rights', u'category', u'author']) for link in feed.getElementsByTagName(u'link'): if (link.getAttribute(u'rel') == u'self'): self.assertEqual(link.getAttribute(u'href'), u'http://example.com/syndication/atom/') entries = feed.getElementsByTagName(u'entry') self.assertEqual(len(entries), Entry.objects.count()) for entry in entries: self.assertChildNodes(entry, [u'title', u'link', u'id', u'summary', u'category', u'updated', u'rights', u'author']) summary = entry.getElementsByTagName(u'summary')[0] self.assertEqual(summary.getAttribute(u'type'), u'html')
'Tests that titles are escaped correctly in RSS feeds.'
def test_title_escaping(self):
response = self.client.get(u'/syndication/rss2/') doc = minidom.parseString(response.content) for item in doc.getElementsByTagName(u'item'): link = item.getElementsByTagName(u'link')[0] if (link.firstChild.wholeText == u'http://example.com/blog/4/'): title = item.getElementsByTagName(u'title')[0] self.assertEqual(title.firstChild.wholeText, u'A & B < C > D')
'Test that datetimes are correctly converted to the local time zone.'
def test_naive_datetime_conversion(self):
response = self.client.get(u'/syndication/naive-dates/') doc = minidom.parseString(response.content) updated = doc.getElementsByTagName(u'updated')[0].firstChild.wholeText d = Entry.objects.latest(u'date').date ltz = tzinfo.LocalTimezone(d) latest = rfc3339_date(d.replace(tzinfo=ltz)) self.assertEqual(updated, latest)
'Test that datetimes with timezones don\'t get trodden on.'
def test_aware_datetime_conversion(self):
response = self.client.get(u'/syndication/aware-dates/') doc = minidom.parseString(response.content) updated = doc.getElementsByTagName(u'updated')[0].firstChild.wholeText self.assertEqual(updated[(-6):], u'+00:42')
'Test that the feed_url can be overridden.'
def test_feed_url(self):
response = self.client.get(u'/syndication/feedurl/') doc = minidom.parseString(response.content) for link in doc.getElementsByTagName(u'link'): if (link.getAttribute(u'rel') == u'self'): self.assertEqual(link.getAttribute(u'href'), u'http://example.com/customfeedurl/')
'Test URLs are prefixed with https:// when feed is requested over HTTPS.'
def test_secure_urls(self):
response = self.client.get(u'/syndication/rss2/', **{u'wsgi.url_scheme': u'https'}) doc = minidom.parseString(response.content) chan = doc.getElementsByTagName(u'channel')[0] self.assertEqual(chan.getElementsByTagName(u'link')[0].firstChild.wholeText[0:5], u'https') atom_link = chan.getElementsByTagName(u'atom:link')[0] self.assertEqual(atom_link.getAttribute(u'href')[0:5], u'https') for link in doc.getElementsByTagName(u'link'): if (link.getAttribute(u'rel') == u'self'): self.assertEqual(link.getAttribute(u'href')[0:5], u'https')
'Test that a ImproperlyConfigured is raised if no link could be found for the item(s).'
def test_item_link_error(self):
self.assertRaises(ImproperlyConfigured, self.client.get, u'/syndication/articles/')
'Test that the item title and description can be overridden with templates.'
def test_template_feed(self):
response = self.client.get(u'/syndication/template/') doc = minidom.parseString(response.content) feed = doc.getElementsByTagName(u'rss')[0] chan = feed.getElementsByTagName(u'channel')[0] items = chan.getElementsByTagName(u'item') self.assertChildNodeContent(items[0], {u'title': u'Title in your templates: My first entry', u'description': u'Description in your templates: My first entry', u'link': u'http://example.com/blog/1/'})
'Test add_domain() prefixes domains onto the correct URLs.'
def test_add_domain(self):
self.assertEqual(views.add_domain(u'example.com', u'/foo/?arg=value'), u'http://example.com/foo/?arg=value') self.assertEqual(views.add_domain(u'example.com', u'/foo/?arg=value', True), u'https://example.com/foo/?arg=value') self.assertEqual(views.add_domain(u'example.com', u'http://djangoproject.com/doc/'), u'http://djangoproject.com/doc/') self.assertEqual(views.add_domain(u'example.com', u'https://djangoproject.com/doc/'), u'https://djangoproject.com/doc/') self.assertEqual(views.add_domain(u'example.com', u'mailto:[email protected]'), u'mailto:[email protected]') self.assertEqual(views.add_domain(u'example.com', u'//example.com/foo/?arg=value'), u'http://example.com/foo/?arg=value')
'Test that debug-false filter is added to mail_admins handler if it has no filters.'
def test_filter_added(self):
config = copy.deepcopy(OLD_LOGGING) with warnings.catch_warnings(record=True) as w: warnings.simplefilter(u'always') compat_patch_logging_config(config) self.assertEqual(len(w), 1) self.assertEqual(config[u'handlers'][u'mail_admins'][u'filters'], [u'require_debug_false'])
'Test that the auto-added require_debug_false filter is an instance of `RequireDebugFalse` filter class.'
def test_filter_configuration(self):
config = copy.deepcopy(OLD_LOGGING) with warnings.catch_warnings(record=True): compat_patch_logging_config(config) flt = config[u'filters'][u'require_debug_false'] self.assertEqual(flt[u'()'], u'django.utils.log.RequireDebugFalse')
'Test the RequireDebugFalse filter class.'
def test_require_debug_false_filter(self):
filter_ = RequireDebugFalse() with self.settings(DEBUG=True): self.assertEqual(filter_.filter(u'record is not used'), False) with self.settings(DEBUG=False): self.assertEqual(filter_.filter(u'record is not used'), True)
'Test that the logging configuration is not modified if the mail_admins handler already has a "filters" key.'
def test_no_patch_if_filters_key_exists(self):
config = copy.deepcopy(OLD_LOGGING) config[u'handlers'][u'mail_admins'][u'filters'] = [] new_config = copy.deepcopy(config) compat_patch_logging_config(new_config) self.assertEqual(config, new_config)
'Test that the logging configuration is not modified if the mail_admins handler is not present.'
def test_no_patch_if_no_mail_admins_handler(self):
config = copy.deepcopy(OLD_LOGGING) config[u'handlers'].pop(u'mail_admins') new_config = copy.deepcopy(config) compat_patch_logging_config(new_config) self.assertEqual(config, new_config)
'The \'django\' base logger only output anything when DEBUG=True.'
def test_django_logger(self):
output = StringIO() self.logger.handlers[0].stream = output self.logger.error(u'Hey, this is an error.') self.assertEqual(output.getvalue(), u'') with self.settings(DEBUG=True): self.logger.error(u'Hey, this is an error.') self.assertEqual(output.getvalue(), u'Hey, this is an error.\n')
'Ensure that user-supplied arguments and the EMAIL_SUBJECT_PREFIX setting are used to compose the email subject. Refs #16736.'
@override_settings(ADMINS=((u'whatever admin', u'[email protected]'),), EMAIL_SUBJECT_PREFIX=u'-SuperAwesomeSubject-') def test_accepts_args(self):
message = u"Custom message that says '%s' and '%s'" token1 = u'ping' token2 = u'pong' admin_email_handler = self.get_admin_email_handler(self.logger) orig_filters = admin_email_handler.filters try: admin_email_handler.filters = [] self.logger.error(message, token1, token2) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, [u'[email protected]']) self.assertEqual(mail.outbox[0].subject, u"-SuperAwesomeSubject-ERROR: Custom message that says 'ping' and 'pong'") finally: admin_email_handler.filters = orig_filters
'Ensure that the subject is also handled if being passed a request object.'
@override_settings(ADMINS=((u'whatever admin', u'[email protected]'),), EMAIL_SUBJECT_PREFIX=u'-SuperAwesomeSubject-', INTERNAL_IPS=(u'127.0.0.1',)) def test_accepts_args_and_request(self):
message = u"Custom message that says '%s' and '%s'" token1 = u'ping' token2 = u'pong' admin_email_handler = self.get_admin_email_handler(self.logger) orig_filters = admin_email_handler.filters try: admin_email_handler.filters = [] rf = RequestFactory() request = rf.get(u'/') self.logger.error(message, token1, token2, extra={u'status_code': 403, u'request': request}) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, [u'[email protected]']) self.assertEqual(mail.outbox[0].subject, u"-SuperAwesomeSubject-ERROR (internal IP): Custom message that says 'ping' and 'pong'") finally: admin_email_handler.filters = orig_filters
'Ensure that newlines in email reports\' subjects are escaped to avoid AdminErrorHandler to fail. Refs #17281.'
@override_settings(ADMINS=((u'admin', u'[email protected]'),), EMAIL_SUBJECT_PREFIX=u'', DEBUG=False) def test_subject_accepts_newlines(self):
message = u'Message \r\n with newlines' expected_subject = u'ERROR: Message \\r\\n with newlines' self.assertEqual(len(mail.outbox), 0) self.logger.error(message) self.assertEqual(len(mail.outbox), 1) self.assertFalse((u'\n' in mail.outbox[0].subject)) self.assertFalse((u'\r' in mail.outbox[0].subject)) self.assertEqual(mail.outbox[0].subject, expected_subject)
'RFC 2822\'s hard limit is 998 characters per line. So, minus "Subject: ", the actual subject must be no longer than 989 characters. Refs #17281.'
@override_settings(ADMINS=((u'admin', u'[email protected]'),), EMAIL_SUBJECT_PREFIX=u'', DEBUG=False) def test_truncate_subject(self):
message = (u'a' * 1000) expected_subject = (u'ERROR: aa' + (u'a' * 980)) self.assertEqual(len(mail.outbox), 0) self.logger.error(message) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, expected_subject)
'Regression test for #7722'
def test_cc(self):
email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]'], cc=[u'[email protected]']) message = email.message() self.assertEqual(message[u'Cc'], u'[email protected]') self.assertEqual(email.recipients(), [u'[email protected]', u'[email protected]']) email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]', u'[email protected]'], cc=[u'[email protected]', u'[email protected]']) message = email.message() self.assertEqual(message[u'Cc'], u'[email protected], [email protected]') self.assertEqual(email.recipients(), [u'[email protected]', u'[email protected]', u'[email protected]', u'[email protected]']) email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]', u'[email protected]'], cc=[u'[email protected]', u'[email protected]'], bcc=[u'[email protected]']) message = email.message() self.assertEqual(message[u'Cc'], u'[email protected], [email protected]') self.assertEqual(email.recipients(), [u'[email protected]', u'[email protected]', u'[email protected]', u'[email protected]', u'[email protected]'])
'Test for space continuation character in long (ascii) subject headers (#7747)'
def test_space_continuation(self):
email = EmailMessage(u'Long subject lines that get wrapped should contain a space continuation character to get expected behavior in Outlook and Thunderbird', u'Content', u'[email protected]', [u'[email protected]']) message = email.message() self.assertEqual(message[u'Subject'].encode(), 'Long subject lines that get wrapped should contain a space continuation\n character to get expected behavior in Outlook and Thunderbird')
'Specifying dates or message-ids in the extra headers overrides the default values (#9233)'
def test_message_header_overrides(self):
headers = {u'date': u'Fri, 09 Nov 2001 01:08:47 -0000', u'Message-ID': u'foo'} email = EmailMessage(u'subject', u'content', u'[email protected]', [u'[email protected]'], headers=headers) self.assertEqual(sorted(email.message().items()), [(u'Content-Transfer-Encoding', u'7bit'), (u'Content-Type', u'text/plain; charset="utf-8"'), (u'From', u'[email protected]'), (u'MIME-Version', u'1.0'), (u'Message-ID', u'foo'), (u'Subject', u'subject'), (u'To', u'[email protected]'), (u'date', u'Fri, 09 Nov 2001 01:08:47 -0000')])
'Make sure we can manually set the From header (#9214)'
def test_from_header(self):
email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]'], headers={u'From': u'[email protected]'}) message = email.message() self.assertEqual(message[u'From'], u'[email protected]')
'Make sure we can manually set the To header (#17444)'
def test_to_header(self):
email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]', u'[email protected]'], headers={u'To': u'[email protected]'}) message = email.message() self.assertEqual(message[u'To'], u'[email protected]') self.assertEqual(email.to, [u'[email protected]', u'[email protected]']) email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]', u'[email protected]']) message = email.message() self.assertEqual(message[u'To'], u'[email protected], [email protected]') self.assertEqual(email.to, [u'[email protected]', u'[email protected]'])
'Regression for #13259 - Make sure that headers are not changed when calling EmailMessage.message()'
def test_multiple_message_call(self):
email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]'], headers={u'From': u'[email protected]'}) message = email.message() self.assertEqual(message[u'From'], u'[email protected]') message = email.message() self.assertEqual(message[u'From'], u'[email protected]')
'Regression for #11144 - When a to/from/cc header contains unicode, make sure the email addresses are parsed correctly (especially with regards to commas)'
def test_unicode_address_header(self):
email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'"Firstname S\xfcrname" <[email protected]>', u'[email protected]']) self.assertEqual(email.message()[u'To'], u'=?utf-8?q?Firstname_S=C3=BCrname?= <[email protected]>, [email protected]') email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'"S\xfcrname, Firstname" <[email protected]>', u'[email protected]']) self.assertEqual(email.message()[u'To'], u'=?utf-8?q?S=C3=BCrname=2C_Firstname?= <[email protected]>, [email protected]')
'Make sure headers can be set with a different encoding than utf-8 in SafeMIMEMultipart as well'
def test_safe_mime_multipart(self):
headers = {u'Date': u'Fri, 09 Nov 2001 01:08:47 -0000', u'Message-ID': u'foo'} (subject, from_email, to) = (u'hello', u'[email protected]', u'"S\xfcrname, Firstname" <[email protected]>') text_content = u'This is an important message.' html_content = u'<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(u'Message from Firstname S\xfcrname', text_content, from_email, [to], headers=headers) msg.attach_alternative(html_content, u'text/html') msg.encoding = u'iso-8859-1' self.assertEqual(msg.message()[u'To'], u'=?iso-8859-1?q?S=FCrname=2C_Firstname?= <[email protected]>') self.assertEqual(msg.message()[u'Subject'], u'=?iso-8859-1?q?Message_from_Firstname_S=FCrname?=')
'Regression for #12791 - Encode body correctly with other encodings than utf-8'
def test_encoding(self):
email = EmailMessage(u'Subject', u'Firstname S\xfcrname is a great guy.', u'[email protected]', [u'[email protected]']) email.encoding = u'iso-8859-1' message = email.message() self.assertTrue(message.as_string().startswith(u'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]')) self.assertEqual(message.get_payload(), u'Firstname S=FCrname is a great guy.') text_content = u'Firstname S\xfcrname is a great guy.' html_content = u'<p>Firstname S\xfcrname is a <strong>great</strong> guy.</p>' msg = EmailMultiAlternatives(u'Subject', text_content, u'[email protected]', [u'[email protected]']) msg.encoding = u'iso-8859-1' msg.attach_alternative(html_content, u'text/html') self.assertEqual(msg.message().get_payload(0).as_string(), u'Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\nFirstname S=FCrname is a great guy.') self.assertEqual(msg.message().get_payload(1).as_string(), u'Content-Type: text/html; charset="iso-8859-1"\nMIME-Version: 1.0\nContent-Transfer-Encoding: quoted-printable\n\n<p>Firstname S=FCrname is a <strong>great</strong> guy.</p>')
'Regression test for #9367'
def test_attachments(self):
headers = {u'Date': u'Fri, 09 Nov 2001 01:08:47 -0000', u'Message-ID': u'foo'} (subject, from_email, to) = (u'hello', u'[email protected]', u'[email protected]') text_content = u'This is an important message.' html_content = u'<p>This is an <strong>important</strong> message.</p>' msg = EmailMultiAlternatives(subject, text_content, from_email, [to], headers=headers) msg.attach_alternative(html_content, u'text/html') msg.attach(u'an attachment.pdf', '%PDF-1.4.%...', mimetype=u'application/pdf') msg_str = msg.message().as_string() message = email.message_from_string(msg_str) self.assertTrue(message.is_multipart()) self.assertEqual(message.get_content_type(), u'multipart/mixed') self.assertEqual(message.get_default_type(), u'text/plain') payload = message.get_payload() self.assertEqual(payload[0].get_content_type(), u'multipart/alternative') self.assertEqual(payload[1].get_content_type(), u'application/pdf')
'Regression test for #14964'
def test_non_ascii_attachment_filename(self):
headers = {u'Date': u'Fri, 09 Nov 2001 01:08:47 -0000', u'Message-ID': u'foo'} (subject, from_email, to) = (u'hello', u'[email protected]', u'[email protected]') content = u'This is the message.' msg = EmailMessage(subject, content, from_email, [to], headers=headers) msg.attach(u'une pi\xe8ce jointe.pdf', '%PDF-1.4.%...', mimetype=u'application/pdf') msg_str = msg.message().as_string() message = email.message_from_string(msg_str) payload = message.get_payload() self.assertEqual(payload[1].get_filename(), u'une pi\xe8ce jointe.pdf')
'Make sure that dummy backends returns correct number of sent messages'
def test_dummy_backend(self):
connection = dummy.EmailBackend() email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]'], headers={u'From': u'[email protected]'}) self.assertEqual(connection.send_messages([email, email, email]), 3)
'Make sure that get_connection() accepts arbitrary keyword that might be used with custom backends.'
def test_arbitrary_keyword(self):
c = mail.get_connection(fail_silently=True, foo=u'bar') self.assertTrue(c.fail_silently)
'Test custom backend defined in this suite.'
def test_custom_backend(self):
conn = mail.get_connection(u'regressiontests.mail.custombackend.EmailBackend') self.assertTrue(hasattr(conn, u'test_outbox')) email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]'], headers={u'From': u'[email protected]'}) conn.send_messages([email]) self.assertEqual(len(conn.test_outbox), 1)
'Test backend argument of mail.get_connection()'
def test_backend_arg(self):
self.assertTrue(isinstance(mail.get_connection(u'django.core.mail.backends.smtp.EmailBackend'), smtp.EmailBackend)) self.assertTrue(isinstance(mail.get_connection(u'django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend)) self.assertTrue(isinstance(mail.get_connection(u'django.core.mail.backends.dummy.EmailBackend'), dummy.EmailBackend)) self.assertTrue(isinstance(mail.get_connection(u'django.core.mail.backends.console.EmailBackend'), console.EmailBackend)) tmp_dir = tempfile.mkdtemp() try: self.assertTrue(isinstance(mail.get_connection(u'django.core.mail.backends.filebased.EmailBackend', file_path=tmp_dir), filebased.EmailBackend)) finally: shutil.rmtree(tmp_dir) self.assertTrue(isinstance(mail.get_connection(), locmem.EmailBackend))
'Test connection argument to send_mail(), et. al.'
@override_settings(EMAIL_BACKEND=u'django.core.mail.backends.locmem.EmailBackend', ADMINS=[(u'nobody', u'[email protected]')], MANAGERS=[(u'nobody', u'[email protected]')]) def test_connection_arg(self):
mail.outbox = [] connection = mail.get_connection(u'regressiontests.mail.custombackend.EmailBackend') send_mail(u'Subject', u'Content', u'[email protected]', [u'[email protected]'], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, u'Subject') connection = mail.get_connection(u'regressiontests.mail.custombackend.EmailBackend') send_mass_mail([(u'Subject1', u'Content1', u'[email protected]', [u'[email protected]']), (u'Subject2', u'Content2', u'[email protected]', [u'[email protected]'])], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 2) self.assertEqual(connection.test_outbox[0].subject, u'Subject1') self.assertEqual(connection.test_outbox[1].subject, u'Subject2') connection = mail.get_connection(u'regressiontests.mail.custombackend.EmailBackend') mail_admins(u'Admin message', u'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, u'[Django] Admin message') connection = mail.get_connection(u'regressiontests.mail.custombackend.EmailBackend') mail_managers(u'Manager message', u'Content', connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(connection.test_outbox[0].subject, u'[Django] Manager message')
'Test html_message argument to mail_managers'
@override_settings(MANAGERS=[(u'nobody', u'[email protected]')]) def test_html_mail_managers(self):
mail_managers(u'Subject', u'Content', html_message=u'HTML Content') message = self.get_the_message() self.assertEqual(message.get(u'subject'), u'[Django] Subject') self.assertEqual(message.get_all(u'to'), [u'[email protected]']) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), u'Content') self.assertEqual(message.get_payload(0).get_content_type(), u'text/plain') self.assertEqual(message.get_payload(1).get_payload(), u'HTML Content') self.assertEqual(message.get_payload(1).get_content_type(), u'text/html')
'Test html_message argument to mail_admins'
@override_settings(ADMINS=[(u'nobody', u'[email protected]')]) def test_html_mail_admins(self):
mail_admins(u'Subject', u'Content', html_message=u'HTML Content') message = self.get_the_message() self.assertEqual(message.get(u'subject'), u'[Django] Subject') self.assertEqual(message.get_all(u'to'), [u'[email protected]']) self.assertTrue(message.is_multipart()) self.assertEqual(len(message.get_payload()), 2) self.assertEqual(message.get_payload(0).get_payload(), u'Content') self.assertEqual(message.get_payload(0).get_content_type(), u'text/plain') self.assertEqual(message.get_payload(1).get_payload(), u'HTML Content') self.assertEqual(message.get_payload(1).get_content_type(), u'text/html')
'String prefix + lazy translated subject = bad output Regression for #13494'
@override_settings(ADMINS=[(u'nobody', u'[email protected]')], MANAGERS=[(u'nobody', u'[email protected]')]) def test_manager_and_admin_mail_prefix(self):
mail_managers(ugettext_lazy(u'Subject'), u'Content') message = self.get_the_message() self.assertEqual(message.get(u'subject'), u'[Django] Subject') self.flush_mailbox() mail_admins(ugettext_lazy(u'Subject'), u'Content') message = self.get_the_message() self.assertEqual(message.get(u'subject'), u'[Django] Subject')
'Test that mail_admins/mail_managers doesn\'t connect to the mail server if there are no recipients (#9383)'
@override_settings(ADMINS=(), MANAGERS=()) def test_empty_admins(self):
mail_admins(u'hi', u'there') self.assertEqual(self.get_mailbox_content(), []) mail_managers(u'hi', u'there') self.assertEqual(self.get_mailbox_content(), [])
'Regression test for #7722'
def test_message_cc_header(self):
email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]'], cc=[u'[email protected]']) mail.get_connection().send_messages([email]) message = self.get_the_message() self.assertStartsWith(message.as_string(), u'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]\nCc: [email protected]\nDate: ')
'Regression test for #14301'
def test_idn_send(self):
self.assertTrue(send_mail(u'Subject', u'Content', u'from@\xf6\xe4\xfc.com', [u'to@\xf6\xe4\xfc.com'])) message = self.get_the_message() self.assertEqual(message.get(u'subject'), u'Subject') self.assertEqual(message.get(u'from'), u'[email protected]') self.assertEqual(message.get(u'to'), u'[email protected]') self.flush_mailbox() m = EmailMessage(u'Subject', u'Content', u'from@\xf6\xe4\xfc.com', [u'to@\xf6\xe4\xfc.com'], cc=[u'cc@\xf6\xe4\xfc.com']) m.send() message = self.get_the_message() self.assertEqual(message.get(u'subject'), u'Subject') self.assertEqual(message.get(u'from'), u'[email protected]') self.assertEqual(message.get(u'to'), u'[email protected]') self.assertEqual(message.get(u'cc'), u'[email protected]')
'Regression test for #15042'
def test_recipient_without_domain(self):
self.assertTrue(send_mail(u'Subject', u'Content', u'tester', [u'django'])) message = self.get_the_message() self.assertEqual(message.get(u'subject'), u'Subject') self.assertEqual(message.get(u'from'), u'tester') self.assertEqual(message.get(u'to'), u'django')
'Test that connection can be closed (even when not explicitely opened)'
def test_close_connection(self):
conn = mail.get_connection(username=u'', password=u'') try: conn.close() except Exception as e: self.fail((u'close() unexpectedly raised an exception: %s' % e))
'Make sure that the locmen backend populates the outbox.'
def test_locmem_shared_messages(self):
connection = locmem.EmailBackend() connection2 = locmem.EmailBackend() email = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]'], headers={u'From': u'[email protected]'}) connection.send_messages([email]) connection2.send_messages([email]) self.assertEqual(len(mail.outbox), 2)
'Make sure opening a connection creates a new file'
def test_file_sessions(self):
msg = EmailMessage(u'Subject', u'Content', u'[email protected]', [u'[email protected]'], headers={u'From': u'[email protected]'}) connection = mail.get_connection() connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 1) with open(os.path.join(self.tmp_dir, os.listdir(self.tmp_dir)[0])) as fp: message = email.message_from_file(fp) self.assertEqual(message.get_content_type(), u'text/plain') self.assertEqual(message.get(u'subject'), u'Subject') self.assertEqual(message.get(u'from'), u'[email protected]') self.assertEqual(message.get(u'to'), u'[email protected]') connection2 = mail.get_connection() connection2.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 2) msg.connection = mail.get_connection() self.assertTrue(connection.open()) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) msg.send() self.assertEqual(len(os.listdir(self.tmp_dir)), 3) connection.close()
'Test that the console backend can be pointed at an arbitrary stream.'
def test_console_stream_kwarg(self):
s = StringIO() connection = mail.get_connection(u'django.core.mail.backends.console.EmailBackend', stream=s) send_mail(u'Subject', u'Content', u'[email protected]', [u'[email protected]'], connection=connection) self.assertTrue(s.getvalue().startswith(u'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nContent-Transfer-Encoding: 7bit\nSubject: Subject\nFrom: [email protected]\nTo: [email protected]\nDate: '))
'Test that closing the backend while the SMTP server is stopped doesn\'t raise an exception.'
def test_server_stopped(self):
backend = smtp.EmailBackend(username=u'', password=u'') backend.open() self.server.stop() try: backend.close() except Exception as e: self.fail((u'close() unexpectedly raised an exception: %s' % e))
'Test that a view can\'t be accidentally instantiated before deployment'
def test_no_init_kwargs(self):
try: view = SimpleView(key='value').as_view() self.fail('Should not be able to instantiate a view') except AttributeError: pass
'Test that a view can\'t be accidentally instantiated before deployment'
def test_no_init_args(self):
try: view = SimpleView.as_view('value') self.fail('Should not be able to use non-keyword arguments instantiating a view') except TypeError: pass
'The edge case of a http request that spoofs an existing method name is caught.'
def test_pathological_http_method(self):
self.assertEqual(SimpleView.as_view()(self.rf.get('/', REQUEST_METHOD='DISPATCH')).status_code, 405)
'Test a view which only allows GET doesn\'t allow other methods.'
def test_get_only(self):
self._assert_simple(SimpleView.as_view()(self.rf.get('/'))) self.assertEqual(SimpleView.as_view()(self.rf.post('/')).status_code, 405) self.assertEqual(SimpleView.as_view()(self.rf.get('/', REQUEST_METHOD='FAKE')).status_code, 405)
'Test a view which supplies a GET method also responds correctly to HEAD.'
def test_get_and_head(self):
self._assert_simple(SimpleView.as_view()(self.rf.get('/'))) response = SimpleView.as_view()(self.rf.head('/')) self.assertEqual(response.status_code, 200)
'Test a view which supplies no GET method responds to HEAD with HTTP 405.'
def test_head_no_get(self):
response = PostOnlyView.as_view()(self.rf.head('/')) self.assertEqual(response.status_code, 405)
'Test a view which only allows both GET and POST.'
def test_get_and_post(self):
self._assert_simple(SimplePostView.as_view()(self.rf.get('/'))) self._assert_simple(SimplePostView.as_view()(self.rf.post('/'))) self.assertEqual(SimplePostView.as_view()(self.rf.get('/', REQUEST_METHOD='FAKE')).status_code, 405)
'Test that view arguments must be predefined on the class and can\'t be named like a HTTP method.'
def test_invalid_keyword_argument(self):
for method in SimpleView.http_method_names: kwargs = dict(((method, 'value'),)) self.assertRaises(TypeError, SimpleView.as_view, **kwargs) CustomizableView.as_view(parameter='value') self.assertRaises(TypeError, CustomizableView.as_view, foobar='value')
'Test a view can only be called once.'
def test_calling_more_than_once(self):
request = self.rf.get('/') view = InstanceView.as_view() self.assertNotEqual(view(request), view(request))
'Test that the callable returned from as_view() has proper docstring, name and module.'
def test_class_attributes(self):
self.assertEqual(SimpleView.__doc__, SimpleView.as_view().__doc__) self.assertEqual(SimpleView.__name__, SimpleView.as_view().__name__) self.assertEqual(SimpleView.__module__, SimpleView.as_view().__module__)
'Test that attributes set by decorators on the dispatch method are also present on the closure.'
def test_dispatch_decoration(self):
self.assertTrue(DecoratedDispatchView.as_view().is_decorated)
'Test that views respond to HTTP OPTIONS requests with an Allow header appropriate for the methods implemented by the view class.'
def test_options(self):
request = self.rf.options('/') view = SimpleView.as_view() response = view(request) self.assertEqual(200, response.status_code) self.assertTrue(response['Allow'])
'Test that a view implementing GET allows GET and HEAD.'
def test_options_for_get_view(self):
request = self.rf.options('/') view = SimpleView.as_view() response = view(request) self._assert_allows(response, 'GET', 'HEAD')
'Test that a view implementing GET and POST allows GET, HEAD, and POST.'
def test_options_for_get_and_post_view(self):
request = self.rf.options('/') view = SimplePostView.as_view() response = view(request) self._assert_allows(response, 'GET', 'HEAD', 'POST')
'Test that a view implementing POST allows POST.'
def test_options_for_post_view(self):
request = self.rf.options('/') view = PostOnlyView.as_view() response = view(request) self._assert_allows(response, 'POST')
'Assert allowed HTTP methods reported in the Allow response header'
def _assert_allows(self, response, *expected_methods):
response_allows = set(response['Allow'].split(', ')) self.assertEqual(set((expected_methods + ('OPTIONS',))), response_allows)
'Test a view only has args, kwargs & request once `as_view` has been called.'
def test_args_kwargs_request_on_self(self):
bare_view = InstanceView() view = InstanceView.as_view()(self.rf.get('/')) for attribute in ('args', 'kwargs', 'request'): self.assertNotIn(attribute, dir(bare_view)) self.assertIn(attribute, dir(view))
'Test a view that simply renders a template on GET'
def test_get(self):
self._assert_about(AboutTemplateView.as_view()(self.rf.get('/about/')))
'Test a TemplateView responds correctly to HEAD'
def test_head(self):
response = AboutTemplateView.as_view()(self.rf.head('/about/')) self.assertEqual(response.status_code, 200)
'Test a view that renders a template on GET with the template name as an attribute on the class.'
def test_get_template_attribute(self):
self._assert_about(AboutTemplateAttributeView.as_view()(self.rf.get('/about/')))
'Test a completely generic view that renders a template on GET with the template name as an argument at instantiation.'
def test_get_generic_template(self):
self._assert_about(TemplateView.as_view(template_name='generic_views/about.html')(self.rf.get('/about/')))
'A template view must provide a template name'
def test_template_name_required(self):
self.assertRaises(ImproperlyConfigured, self.client.get, '/template/no_template/')
'A generic template view passes kwargs as context.'
def test_template_params(self):
response = self.client.get('/template/simple/bar/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['foo'], 'bar') self.assertTrue(isinstance(response.context['view'], View))
'A template view can be customized to return extra context.'
def test_extra_template_params(self):
response = self.client.get('/template/custom/bar/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['foo'], 'bar') self.assertEqual(response.context['key'], 'value') self.assertTrue(isinstance(response.context['view'], View))
'A template view can be cached'
def test_cached_views(self):
response = self.client.get('/template/cached/bar/') self.assertEqual(response.status_code, 200) time.sleep(1.0) response2 = self.client.get('/template/cached/bar/') self.assertEqual(response2.status_code, 200) self.assertEqual(response.content, response2.content) time.sleep(2.0) response2 = self.client.get('/template/cached/bar/') self.assertEqual(response2.status_code, 200) self.assertNotEqual(response.content, response2.content)
'Without any configuration, returns HTTP 410 GONE'
def test_no_url(self):
response = RedirectView.as_view()(self.rf.get('/foo/')) self.assertEqual(response.status_code, 410)
'Default is a permanent redirect'
def test_permanent_redirect(self):
response = RedirectView.as_view(url='/bar/')(self.rf.get('/foo/')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/')
'Permanent redirects are an option'
def test_temporary_redirect(self):
response = RedirectView.as_view(url='/bar/', permanent=False)(self.rf.get('/foo/')) self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '/bar/')
'GET arguments can be included in the redirected URL'
def test_include_args(self):
response = RedirectView.as_view(url='/bar/')(self.rf.get('/foo/')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/') response = RedirectView.as_view(url='/bar/', query_string=True)(self.rf.get('/foo/?pork=spam')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/?pork=spam')
'GET arguments can be URL-encoded when included in the redirected URL'
def test_include_urlencoded_args(self):
response = RedirectView.as_view(url='/bar/', query_string=True)(self.rf.get('/foo/?unicode=%E2%9C%93')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/?unicode=%E2%9C%93')
'Redirection URLs can be parameterized'
def test_parameter_substitution(self):
response = RedirectView.as_view(url='/bar/%(object_id)d/')(self.rf.get('/foo/42/'), object_id=42) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/42/')
'Default is a permanent redirect'
def test_redirect_POST(self):
response = RedirectView.as_view(url='/bar/')(self.rf.post('/foo/')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/')
'Default is a permanent redirect'
def test_redirect_HEAD(self):
response = RedirectView.as_view(url='/bar/')(self.rf.head('/foo/')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/')
'Default is a permanent redirect'
def test_redirect_OPTIONS(self):
response = RedirectView.as_view(url='/bar/')(self.rf.options('/foo/')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/')
'Default is a permanent redirect'
def test_redirect_PUT(self):
response = RedirectView.as_view(url='/bar/')(self.rf.put('/foo/')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/')
'Default is a permanent redirect'
def test_redirect_DELETE(self):
response = RedirectView.as_view(url='/bar/')(self.rf.delete('/foo/')) self.assertEqual(response.status_code, 301) self.assertEqual(response['Location'], '/bar/')
'regression for #16705'
def test_redirect_when_meta_contains_no_query_string(self):
response = RedirectView.as_view(url='/bar/')(self.rf.request(PATH_INFO='/foo/')) self.assertEqual(response.status_code, 301)
'date_list should be sorted descending in index'
def test_date_list_order(self):
_make_books(5, base_date=datetime.date(2011, 12, 25)) res = self.client.get('/dates/books/') self.assertEqual(res.status_code, 200) self.assertEqual(list(res.context['date_list']), list(reversed(sorted(res.context['date_list']))))
'date_list should be sorted ascending in year view'
def test_date_list_order(self):
_make_books(10, base_date=datetime.date(2011, 12, 25)) res = self.client.get('/dates/books/2011/') self.assertEqual(list(res.context['date_list']), list(sorted(res.context['date_list'])))
'Content can exist on any day of the previous month. Refs #14711'
def test_previous_month_without_content(self):
self.pubdate_list = [datetime.date(2010, month, day) for (month, day) in ((9, 1), (10, 2), (11, 3))] for pubdate in self.pubdate_list: name = str(pubdate) Book.objects.create(name=name, slug=name, pages=100, pubdate=pubdate) res = self.client.get('/dates/books/2010/nov/allow_empty/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['previous_month'], datetime.date(2010, 10, 1)) res = self.client.get('/dates/books/2010/nov/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['previous_month'], datetime.date(2010, 10, 1)) res = self.client.get('/dates/books/2010/oct/') self.assertEqual(res.status_code, 200) self.assertEqual(res.context['previous_month'], datetime.date(2010, 9, 1))