desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Tests that APPEND_SLASH doesn\'t redirect to unknown resources.'
def test_append_slash_slashless_unknown_custom_urlconf(self):
settings.APPEND_SLASH = True request = self._get_request('customurlconf/unknown') request.urlconf = 'regressiontests.middleware.extra_urls' self.assertEqual(CommonMiddleware().process_request(request), None)
'Tests that APPEND_SLASH redirects slashless URLs to a valid pattern.'
def test_append_slash_redirect_custom_urlconf(self):
settings.APPEND_SLASH = True request = self._get_request('customurlconf/slash') request.urlconf = 'regressiontests.middleware.extra_urls' r = CommonMiddleware().process_request(request) self.assertFalse((r is None), 'CommonMiddlware failed to return APPEND_SLASH redirect using r...
'Tests that while in debug mode, an exception is raised with a warning when a failed attempt is made to POST to an URL which would normally be redirected to a slashed version.'
def test_append_slash_no_redirect_on_POST_in_DEBUG_custom_urlconf(self):
settings.APPEND_SLASH = True settings.DEBUG = True request = self._get_request('customurlconf/slash') request.urlconf = 'regressiontests.middleware.extra_urls' request.method = 'POST' self.assertRaises(RuntimeError, CommonMiddleware().process_request, request) try: CommonMiddleware()...
'Tests disabling append slash functionality.'
def test_append_slash_disabled_custom_urlconf(self):
settings.APPEND_SLASH = False request = self._get_request('customurlconf/slash') request.urlconf = 'regressiontests.middleware.extra_urls' self.assertEqual(CommonMiddleware().process_request(request), None)
'Tests that URLs which require quoting are redirected to their slash version ok.'
def test_append_slash_quoted_custom_urlconf(self):
settings.APPEND_SLASH = True request = self._get_request('customurlconf/needsquoting#') request.urlconf = 'regressiontests.middleware.extra_urls' r = CommonMiddleware().process_request(request) self.assertFalse((r is None), 'CommonMiddlware failed to return APPEND_SLASH redirect us...
'Tests that the X_FRAME_OPTIONS setting can be set to SAMEORIGIN to have the middleware use that value for the HTTP header.'
def test_same_origin(self):
settings.X_FRAME_OPTIONS = 'SAMEORIGIN' r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN') settings.X_FRAME_OPTIONS = 'sameorigin' r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.as...
'Tests that the X_FRAME_OPTIONS setting can be set to DENY to have the middleware use that value for the HTTP header.'
def test_deny(self):
settings.X_FRAME_OPTIONS = 'DENY' r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r['X-Frame-Options'], 'DENY') settings.X_FRAME_OPTIONS = 'deny' r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r['X-Fra...
'Tests that if the X_FRAME_OPTIONS setting is not set then it defaults to SAMEORIGIN.'
def test_defaults_sameorigin(self):
del settings.X_FRAME_OPTIONS r = XFrameOptionsMiddleware().process_response(HttpRequest(), HttpResponse()) self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN')
'Tests that if the X-Frame-Options header is already set then the middleware does not attempt to override it.'
def test_dont_set_if_set(self):
settings.X_FRAME_OPTIONS = 'DENY' response = HttpResponse() response['X-Frame-Options'] = 'SAMEORIGIN' r = XFrameOptionsMiddleware().process_response(HttpRequest(), response) self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN') settings.X_FRAME_OPTIONS = 'SAMEORIGIN' response = HttpResponse(...
'Tests that if the response has a xframe_options_exempt attribute set to False then it still sets the header, but if it\'s set to True then it does not.'
def test_response_exempt(self):
settings.X_FRAME_OPTIONS = 'SAMEORIGIN' response = HttpResponse() response.xframe_options_exempt = False r = XFrameOptionsMiddleware().process_response(HttpRequest(), response) self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN') response = HttpResponse() response.xframe_options_exempt = Tru...
'Tests that the XFrameOptionsMiddleware method that determines the X-Frame-Options header value can be overridden based on something in the request or response.'
def test_is_extendable(self):
class OtherXFrameOptionsMiddleware(XFrameOptionsMiddleware, ): def get_xframe_options_value(self, request, response): if getattr(request, 'sameorigin', False): return 'SAMEORIGIN' if getattr(response, 'sameorigin', False): return 'SAMEORIGIN' ...
'Tests that compression is performed on responses with compressible content.'
def test_compress_response(self):
r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(self.decompress(r.content), self.compressible_string) self.assertEqual(r.get('Content-Encoding'), 'gzip') self.assertEqual(r.get('Content-Length'), str(len(r.content)))
'Tests that compression is performed on responses with a status other than 200. See #10762.'
def test_compress_non_200_response(self):
self.resp.status_code = 404 r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(self.decompress(r.content), self.compressible_string) self.assertEqual(r.get('Content-Encoding'), 'gzip')
'Tests that compression isn\'t performed on responses with short content.'
def test_no_compress_short_response(self):
self.resp.content = self.short_string r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(r.content, self.short_string) self.assertEqual(r.get('Content-Encoding'), None)
'Tests that compression isn\'t performed on responses that are already compressed.'
def test_no_compress_compressed_response(self):
self.resp['Content-Encoding'] = 'deflate' r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(r.content, self.compressible_string) self.assertEqual(r.get('Content-Encoding'), 'deflate')
'Tests that compression isn\'t performed on JavaScript requests from Internet Explorer.'
def test_no_compress_ie_js_requests(self):
self.req.META['HTTP_USER_AGENT'] = 'Mozilla/4.0 (compatible; MSIE 5.00; Windows 98)' self.resp['Content-Type'] = 'application/javascript; charset=UTF-8' r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(r.content, self.compressible_string) self.assertEqual...
'Tests that compression isn\'t performed on responses with uncompressible content.'
def test_no_compress_uncompressible_response(self):
self.resp.content = self.uncompressible_string r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(r.content, self.uncompressible_string) self.assertEqual(r.get('Content-Encoding'), None)
'Tests that ETag is changed after gzip compression is performed.'
def test_compress_response(self):
request = self.rf.get('/', HTTP_ACCEPT_ENCODING='gzip, deflate') response = GZipMiddleware().process_response(request, CommonMiddleware().process_response(request, HttpResponse(self.compressible_string))) gzip_etag = response.get('ETag') request = self.rf.get('/', HTTP_ACCEPT_ENCODING='') respons...
'# Regression test for #8027: custom ModelForms with fields/fieldsets'
def test_custom_modelforms_with_fields_fieldsets(self):
validate(ValidFields, Song) self.assertRaisesMessage(ImproperlyConfigured, "'InvalidFields.fields' refers to field 'spam' that is missing from the form.", validate, InvalidFields, 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 ...
'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, RawIdNonexi...
'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).'
def test_lock_safety(self):
old_middleware_classes = settings.MIDDLEWARE_CLASSES settings.MIDDLEWARE_CLASSES = 42 handler = WSGIHandler() self.assertEqual(handler.initLock.locked(), False) try: handler(None, None) except: pass self.assertEqual(handler.initLock.locked(), False) settings.MIDDLEWARE_CL...
'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('/syndication/rss2/') doc = minidom.parseString(response.content) feed_elem = doc.getElementsByTagName('rss') self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute('version'), '2.0') chan_elem = feed.getElementsByTagName('channe...
'Test the structure and content of feeds generated by RssUserland091Feed.'
def test_rss091_feed(self):
response = self.client.get('/syndication/rss091/') doc = minidom.parseString(response.content) feed_elem = doc.getElementsByTagName('rss') self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute('version'), '0.91') chan_elem = feed.getElementsByTagName('cha...
'Test the structure and content of feeds generated by Atom1Feed.'
def test_atom_feed(self):
response = self.client.get('/syndication/atom/') feed = minidom.parseString(response.content).firstChild self.assertEqual(feed.nodeName, 'feed') self.assertEqual(feed.getAttribute('xmlns'), 'http://www.w3.org/2005/Atom') self.assertChildNodes(feed, ['title', 'subtitle', 'link', 'id', 'updated', 'ent...
'Tests that titles are escaped correctly in RSS feeds.'
def test_title_escaping(self):
response = self.client.get('/syndication/rss2/') doc = minidom.parseString(response.content) for item in doc.getElementsByTagName('item'): link = item.getElementsByTagName('link')[0] if (link.firstChild.wholeText == 'http://example.com/blog/4/'): title = item.getElementsByTagName...
'Test that datetimes are correctly converted to the local time zone.'
def test_naive_datetime_conversion(self):
response = self.client.get('/syndication/naive-dates/') doc = minidom.parseString(response.content) updated = doc.getElementsByTagName('updated')[0].firstChild.wholeText d = Entry.objects.latest('date').date ltz = tzinfo.LocalTimezone(d) latest = rfc3339_date(d.replace(tzinfo=ltz)) self.asse...
'Test that datetimes with timezones don\'t get trodden on.'
def test_aware_datetime_conversion(self):
response = self.client.get('/syndication/aware-dates/') doc = minidom.parseString(response.content) updated = doc.getElementsByTagName('updated')[0].firstChild.wholeText self.assertEqual(updated[(-6):], '+00:42')
'Test that the feed_url can be overridden.'
def test_feed_url(self):
response = self.client.get('/syndication/feedurl/') doc = minidom.parseString(response.content) for link in doc.getElementsByTagName('link'): if (link.getAttribute('rel') == 'self'): self.assertEqual(link.getAttribute('href'), '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('/syndication/rss2/', **{'wsgi.url_scheme': 'https'}) doc = minidom.parseString(response.content) chan = doc.getElementsByTagName('channel')[0] self.assertEqual(chan.getElementsByTagName('link')[0].firstChild.wholeText[0:5], 'https') atom_link = chan.getElementsByTagName('...
'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, '/syndication/articles/')
'Test that the item title and description can be overridden with templates.'
def test_template_feed(self):
response = self.client.get('/syndication/template/') doc = minidom.parseString(response.content) feed = doc.getElementsByTagName('rss')[0] chan = feed.getElementsByTagName('channel')[0] items = chan.getElementsByTagName('item') self.assertChildNodeContent(items[0], {'title': 'Title in your...
'Test add_domain() prefixes domains onto the correct URLs.'
def test_add_domain(self):
self.assertEqual(views.add_domain('example.com', '/foo/?arg=value'), 'http://example.com/foo/?arg=value') self.assertEqual(views.add_domain('example.com', '/foo/?arg=value', True), 'https://example.com/foo/?arg=value') self.assertEqual(views.add_domain('example.com', 'http://djangoproject.com/doc/'), 'http:...
'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) compat_patch_logging_config(config) self.assertEqual(config['handlers']['mail_admins']['filters'], ['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) compat_patch_logging_config(config) flt = config['filters']['require_debug_false'] self.assertEqual(flt['()'], '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('record is not used'), False) with self.settings(DEBUG=False): self.assertEqual(filter_.filter('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['handlers']['mail_admins']['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['handlers'].pop('mail_admins') new_config = copy.deepcopy(config) compat_patch_logging_config(new_config) self.assertEqual(config, new_config)
'Ensure that user-supplied arguments and the EMAIL_SUBJECT_PREFIX setting are used to compose the email subject. Refs #16736.'
@override_settings(ADMINS=(('whatever admin', 'admin@example.com'),), EMAIL_SUBJECT_PREFIX='-SuperAwesomeSubject-') def test_accepts_args(self):
message = "Custom message that says '%s' and '%s'" token1 = 'ping' token2 = 'pong' logger = getLogger('django.request') admin_email_handler = self.get_admin_email_handler(logger) orig_filters = admin_email_handler.filters try: admin_email_handler.filters = [] ...
'Ensure that the subject is also handled if being passed a request object.'
@override_settings(ADMINS=(('whatever admin', 'admin@example.com'),), EMAIL_SUBJECT_PREFIX='-SuperAwesomeSubject-', INTERNAL_IPS=('127.0.0.1',)) def test_accepts_args_and_request(self):
message = "Custom message that says '%s' and '%s'" token1 = 'ping' token2 = 'pong' logger = getLogger('django.request') admin_email_handler = self.get_admin_email_handler(logger) orig_filters = admin_email_handler.filters try: admin_email_handler.filters = [] ...
'Ensure that newlines in email reports\' subjects are escaped to avoid AdminErrorHandler to fail. Refs #17281.'
@override_settings(ADMINS=(('admin', 'admin@example.com'),), EMAIL_SUBJECT_PREFIX='', 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) logger = getLogger('django.request') logger.error(message) self.assertEqual(len(mail.outbox), 1) self.assertFalse(('\n' in mail.outbox[...
'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=(('admin', 'admin@example.com'),), EMAIL_SUBJECT_PREFIX='', DEBUG=False) def test_truncate_subject(self):
message = ('a' * 1000) expected_subject = ('ERROR: aa' + ('a' * 980)) self.assertEqual(len(mail.outbox), 0) logger = getLogger('django.request') 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('Subject', 'Content', 'from@example.com', ['to@example.com'], cc=['cc@example.com']) message = email.message() self.assertEqual(message['Cc'], 'cc@example.com') self.assertEqual(email.recipients(), ['to@example.com', 'cc@example.com']) email = EmailMessage('Subject', 'Content', ...
'Test for space continuation character in long (ascii) subject headers (#7747)'
def test_space_continuation(self):
email = EmailMessage('Long subject lines that get wrapped should use a space continuation character to get expected behavior in Outlook and Thunderbird', 'Content', 'from@example.com', ['to@example.com']) message = email.message() self.assertEqual(mes...
'Specifying dates or message-ids in the extra headers overrides the default values (#9233)'
def test_message_header_overrides(self):
headers = {'date': 'Fri, 09 Nov 2001 01:08:47 -0000', 'Message-ID': 'foo'} email = EmailMessage('subject', 'content', 'from@example.com', ['to@example.com'], headers=headers) self.assertEqual(email.message().as_string(), 'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\n...
'Make sure we can manually set the From header (#9214)'
def test_from_header(self):
email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) message = email.message() self.assertEqual(message['From'], 'from@example.com')
'Make sure we can manually set the To header (#17444)'
def test_to_header(self):
email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['list-subscriber@example.com', 'list-subscriber2@example.com'], headers={'To': 'mailing-list@example.com'}) message = email.message() self.assertEqual(message['To'], 'mailing-list@example.com') self.assertEqual(email.to, ['list-subscriber...
'Regression for #13259 - Make sure that headers are not changed when calling EmailMessage.message()'
def test_multiple_message_call(self):
email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) message = email.message() self.assertEqual(message['From'], 'from@example.com') message = email.message() self.assertEqual(message['From'], 'from@example.com')
'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('Subject', 'Content', 'from@example.com', ['"Firstname S\xc3\xbcrname" <to@example.com>', 'other@example.com']) self.assertEqual(email.message()['To'], '=?utf-8?q?Firstname_S=C3=BCrname?= <to@example.com>, other@example.com') email = EmailMessage('Subject', 'Content', 'from@...
'Make sure headers can be set with a different encoding than utf-8 in SafeMIMEMultipart as well'
def test_safe_mime_multipart(self):
headers = {'Date': 'Fri, 09 Nov 2001 01:08:47 -0000', 'Message-ID': 'foo'} (subject, from_email, to) = ('hello', 'from@example.com', '"S\xc3\xbcrname, Firstname" <to@example.com>') text_content = 'This is an important message.' html_content = '<p>This is an <str...
'Regression for #12791 - Encode body correctly with other encodings than utf-8'
def test_encoding(self):
email = EmailMessage('Subject', 'Firstname S\xc3\xbcrname is a great guy.', 'from@example.com', ['other@example.com']) email.encoding = 'iso-8859-1' message = email.message() self.assertTrue(message.as_string().startswith('Content-Type: text/plain; charset="iso-8859-1"\nMIME-Version...
'Regression test for #9367'
def test_attachments(self):
headers = {'Date': 'Fri, 09 Nov 2001 01:08:47 -0000', 'Message-ID': 'foo'} (subject, from_email, to) = ('hello', 'from@example.com', 'to@example.com') text_content = 'This is an important message.' html_content = '<p>This is an <strong>important</strong> message.</...
'Regression test for #14964'
def test_non_ascii_attachment_filename(self):
headers = {'Date': 'Fri, 09 Nov 2001 01:08:47 -0000', 'Message-ID': 'foo'} (subject, from_email, to) = ('hello', 'from@example.com', 'to@example.com') content = 'This is the message.' msg = EmailMessage(subject, content, from_email, [to], headers=headers) msg.attach(u'une ...
'Make sure that dummy backends returns correct number of sent messages'
def test_dummy_backend(self):
connection = dummy.EmailBackend() email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) 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='bar') self.assertTrue(c.fail_silently)
'Test custom backend defined in this suite.'
def test_custom_backend(self):
conn = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') self.assertTrue(hasattr(conn, 'test_outbox')) email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) conn.send_messages([email]) self.assertEqual(len(conn...
'Test backend argument of mail.get_connection()'
def test_backend_arg(self):
self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.smtp.EmailBackend'), smtp.EmailBackend)) self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends.locmem.EmailBackend'), locmem.EmailBackend)) self.assertTrue(isinstance(mail.get_connection('django.core.mail.backends....
'Test connection argument to send_mail(), et. al.'
@override_settings(EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend', ADMINS=[('nobody', 'nobody@example.com')], MANAGERS=[('nobody', 'nobody@example.com')]) def test_connection_arg(self):
mail.outbox = [] connection = mail.get_connection('regressiontests.mail.custombackend.EmailBackend') send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection) self.assertEqual(mail.outbox, []) self.assertEqual(len(connection.test_outbox), 1) self.assertEqual(...
'Test html_message argument to mail_managers'
@override_settings(MANAGERS=[('nobody', 'nobody@example.com')]) def test_html_mail_managers(self):
mail_managers('Subject', 'Content', html_message='HTML Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.assertEqual(message.get_all('to'), ['nobody@example.com']) self.assertTrue(message.is_multipart()) self.assertEqual(len(messag...
'Test html_message argument to mail_admins'
@override_settings(ADMINS=[('nobody', 'nobody@example.com')]) def test_html_mail_admins(self):
mail_admins('Subject', 'Content', html_message='HTML Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.assertEqual(message.get_all('to'), ['nobody@example.com']) self.assertTrue(message.is_multipart()) self.assertEqual(len(message....
'String prefix + lazy translated subject = bad output Regression for #13494'
@override_settings(ADMINS=[('nobody', 'nobody+admin@example.com')], MANAGERS=[('nobody', 'nobody+manager@example.com')]) def test_manager_and_admin_mail_prefix(self):
mail_managers(ugettext_lazy('Subject'), 'Content') message = self.get_the_message() self.assertEqual(message.get('subject'), '[Django] Subject') self.flush_mailbox() mail_admins(ugettext_lazy('Subject'), 'Content') message = self.get_the_message() self.assertEqual(message.get('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('hi', 'there') self.assertEqual(self.get_mailbox_content(), []) mail_managers('hi', 'there') self.assertEqual(self.get_mailbox_content(), [])
'Regression test for #7722'
def test_message_cc_header(self):
email = EmailMessage('Subject', 'Content', 'from@example.com', ['to@example.com'], cc=['cc@example.com']) mail.get_connection().send_messages([email]) message = self.get_the_message() self.assertStartsWith(message.as_string(), 'Content-Type: text/plain; charset="utf-8"\nMIME-Version: 1.0\nConte...
'Regression test for #14301'
def test_idn_send(self):
self.assertTrue(send_mail('Subject', 'Content', 'from@\xc3\xb6\xc3\xa4\xc3\xbc.com', [u'to@\xf6\xe4\xfc.com'])) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), 'from@xn--4ca9at.com') self.assertEqual(message.get('to'), 'to@xn...
'Regression test for #15042'
def test_recipient_without_domain(self):
self.assertTrue(send_mail('Subject', 'Content', 'tester', ['django'])) message = self.get_the_message() self.assertEqual(message.get('subject'), 'Subject') self.assertEqual(message.get('from'), 'tester') self.assertEqual(message.get('to'), 'django')
'Make sure that the locmen backend populates the outbox.'
def test_locmem_shared_messages(self):
connection = locmem.EmailBackend() connection2 = locmem.EmailBackend() email = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) connection.send_messages([email]) connection2.send_messages([email]) self.assertEqual(len(mail.outbox)...
'Make sure opening a connection creates a new file'
def test_file_sessions(self):
msg = EmailMessage('Subject', 'Content', 'bounce@example.com', ['to@example.com'], headers={'From': 'from@example.com'}) connection = mail.get_connection() connection.send_messages([msg]) self.assertEqual(len(os.listdir(self.tmp_dir)), 1) message = email.message_from_file(open(os.path.join(self.tmp_...
'Test that the console backend can be pointed at an arbitrary stream.'
def test_console_stream_kwarg(self):
s = StringIO() connection = mail.get_connection('django.core.mail.backends.console.EmailBackend', stream=s) send_mail('Subject', 'Content', 'from@example.com', ['to@example.com'], connection=connection) self.assertTrue(s.getvalue().startswith('Content-Type: text/plain; charset="utf-8"\nMIME-Versio...
'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 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['params'], {'foo': 'bar'})
'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['params'], {'foo': 'bar'}) self.assertEqual(response.context['key'], 'value')
'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) response...
'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) ...
'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/')