desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Errors found when rendering 404 error templates are re-raised'
| def test_bad_404_template(self):
| settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'bad_templates'),)
try:
response = self.client.get('/no_such_view/')
self.fail('Should get error about syntax error in template')
except TemplateSyntaxError:
pass
|
'TestCase can enforce a custom URLconf on a per-test basis'
| def test_urlconf_was_changed(self):
| url = reverse('arg_view', args=['somename'])
self.assertEquals(url, '/arg_view/somename/')
|
'URLconf is reverted to original value after modification in a TestCase'
| def test_urlconf_was_reverted(self):
| url = reverse('arg_view', args=['somename'])
self.assertEquals(url, '/test_client_regress/arg_view/somename/')
|
'Context variables can be retrieved from a single context'
| def test_single_context(self):
| response = self.client.get('/test_client_regress/request_data/', data={'foo': 'whiz'})
self.assertEqual(response.context.__class__, Context)
self.assertTrue(('get-foo' in response.context))
self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['request-foo'], 'whiz'... |
'Context variables can be retrieved from a list of contexts'
| def test_inherited_context(self):
| response = self.client.get('/test_client_regress/request_data_extended/', data={'foo': 'whiz'})
self.assertEqual(response.context.__class__, ContextList)
self.assertEqual(len(response.context), 2)
self.assertTrue(('get-foo' in response.context))
self.assertEqual(response.context['get-foo'], 'whiz')
... |
'The session isn\'t lost if a user logs in'
| def test_session(self):
| response = self.client.get('/test_client_regress/check_session/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'NO')
response = self.client.get('/test_client_regress/set_session/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 's... |
'Logout should work whether the user is logged in or not (#9978).'
| def test_logout(self):
| self.client.logout()
login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in')
self.client.logout()
self.client.logout()
|
'Request a view via request method GET'
| def test_get(self):
| response = self.client.get('/test_client_regress/request_methods/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'request method: GET')
|
'Request a view via request method POST'
| def test_post(self):
| response = self.client.post('/test_client_regress/request_methods/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'request method: POST')
|
'Request a view via request method HEAD'
| def test_head(self):
| response = self.client.head('/test_client_regress/request_methods/')
self.assertEqual(response.status_code, 200)
self.assertNotEqual(response.content, 'request method: HEAD')
self.assertEqual(response.content, '')
|
'Request a view via request method OPTIONS'
| def test_options(self):
| response = self.client.options('/test_client_regress/request_methods/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'request method: OPTIONS')
|
'Request a view via request method PUT'
| def test_put(self):
| response = self.client.put('/test_client_regress/request_methods/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'request method: PUT')
|
'Request a view via request method DELETE'
| def test_delete(self):
| response = self.client.delete('/test_client_regress/request_methods/')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'request method: DELETE')
|
'Request a view with string data via request method POST'
| def test_post(self):
| data = u'{"test": "json"}'
response = self.client.post('/test_client_regress/request_methods/', data=data, content_type='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'request method: POST')
|
'Request a view with string data via request method PUT'
| def test_put(self):
| data = u'{"test": "json"}'
response = self.client.put('/test_client_regress/request_methods/', data=data, content_type='application/json')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.content, 'request method: PUT')
|
'A simple ASCII-only unicode JSON document can be POSTed'
| def test_simple_unicode_payload(self):
| json = u'{"english": "mountain pass"}'
response = self.client.post('/test_client_regress/parse_unicode_json/', json, content_type='application/json')
self.assertEqual(response.content, json)
|
'A non-ASCII unicode data encoded as UTF-8 can be POSTed'
| def test_unicode_payload_utf8(self):
| json = u'{"dog": "\u0441\u043e\u0431\u0430\u043a\u0430"}'
response = self.client.post('/test_client_regress/parse_unicode_json/', json, content_type='application/json; charset=utf-8')
self.assertEqual(response.content, json.encode('utf-8'))
|
'A non-ASCII unicode data encoded as UTF-16 can be POSTed'
| def test_unicode_payload_utf16(self):
| json = u'{"dog": "\u0441\u043e\u0431\u0430\u043a\u0430"}'
response = self.client.post('/test_client_regress/parse_unicode_json/', json, content_type='application/json; charset=utf-16')
self.assertEqual(response.content, json.encode('utf-16'))
|
'A non-ASCII unicode data as a non-UTF based encoding can be POSTed'
| def test_unicode_payload_non_utf(self):
| json = u'{"dog": "\u0441\u043e\u0431\u0430\u043a\u0430"}'
response = self.client.post('/test_client_regress/parse_unicode_json/', json, content_type='application/json; charset=koi8-r')
self.assertEqual(response.content, json.encode('koi8-r'))
|
'A test client can receive custom headers'
| def test_client_headers(self):
| response = self.client.get('/test_client_regress/check_headers/', HTTP_X_ARG_CHECK='Testing 123')
self.assertEquals(response.content, 'HTTP_X_ARG_CHECK: Testing 123')
self.assertEquals(response.status_code, 200)
|
'Test client headers are preserved through redirects'
| def test_client_headers_redirect(self):
| response = self.client.get('/test_client_regress/check_headers_redirect/', follow=True, HTTP_X_ARG_CHECK='Testing 123')
self.assertEquals(response.content, 'HTTP_X_ARG_CHECK: Testing 123')
self.assertRedirects(response, '/test_client_regress/check_headers/', status_code=301, target_status_code=200)... |
'Tests that URLs with slashes go unmolested.'
| def test_append_slash_have_slash(self):
| settings.APPEND_SLASH = True
request = self._get_request('slash/')
self.assertEquals(CommonMiddleware().process_request(request), None)
|
'Tests that matches to explicit slashless URLs go unmolested.'
| def test_append_slash_slashless_resource(self):
| settings.APPEND_SLASH = True
request = self._get_request('noslash')
self.assertEquals(CommonMiddleware().process_request(request), None)
|
'Tests that APPEND_SLASH doesn\'t redirect to unknown resources.'
| def test_append_slash_slashless_unknown(self):
| settings.APPEND_SLASH = True
request = self._get_request('unknown')
self.assertEquals(CommonMiddleware().process_request(request), None)
|
'Tests that APPEND_SLASH redirects slashless URLs to a valid pattern.'
| def test_append_slash_redirect(self):
| settings.APPEND_SLASH = True
request = self._get_request('slash')
r = CommonMiddleware().process_request(request)
self.assertEquals(r.status_code, 301)
self.assertEquals(r['Location'], 'http://testserver/middleware/slash/')
|
'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(self):
| settings.APPEND_SLASH = True
settings.DEBUG = True
request = self._get_request('slash')
request.method = 'POST'
self.assertRaises(RuntimeError, CommonMiddleware().process_request, request)
try:
CommonMiddleware().process_request(request)
except RuntimeError as e:
self.assertT... |
'Tests disabling append slash functionality.'
| def test_append_slash_disabled(self):
| settings.APPEND_SLASH = False
request = self._get_request('slash')
self.assertEquals(CommonMiddleware().process_request(request), None)
|
'Tests that URLs which require quoting are redirected to their slash
version ok.'
| def test_append_slash_quoted(self):
| settings.APPEND_SLASH = True
request = self._get_request('needsquoting#')
r = CommonMiddleware().process_request(request)
self.assertEquals(r.status_code, 301)
self.assertEquals(r['Location'], 'http://testserver/middleware/needsquoting%23/')
|
'Tests that URLs with slashes go unmolested.'
| def test_append_slash_have_slash_custom_urlconf(self):
| settings.APPEND_SLASH = True
request = self._get_request('customurlconf/slash/')
request.urlconf = 'regressiontests.middleware.extra_urls'
self.assertEquals(CommonMiddleware().process_request(request), None)
|
'Tests that matches to explicit slashless URLs go unmolested.'
| def test_append_slash_slashless_resource_custom_urlconf(self):
| settings.APPEND_SLASH = True
request = self._get_request('customurlconf/noslash')
request.urlconf = 'regressiontests.middleware.extra_urls'
self.assertEquals(CommonMiddleware().process_request(request), None)
|
'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.assertEquals(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.assertEquals(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... |
'# 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 #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)
|
'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 an empty feed_dict raises a 404.'
| def test_empty_feed_dict(self):
| response = self.client.get('/syndication/depr-feeds-empty/aware-dates/')
self.assertEquals(response.status_code, 404)
|
'Test that a non-existent slug raises a 404.'
| def test_nonexistent_slug(self):
| response = self.client.get('/syndication/depr-feeds/foobar/')
self.assertEquals(response.status_code, 404)
|
'A simple test for Rss201rev2Feed feeds generated by the deprecated
system.'
| def test_rss_feed(self):
| response = self.client.get('/syndication/depr-feeds/rss/')
doc = minidom.parseString(response.content)
feed = doc.getElementsByTagName('rss')[0]
self.assertEqual(feed.getAttribute('version'), '2.0')
chan = feed.getElementsByTagName('channel')[0]
self.assertChildNodes(chan, ['title', 'link', 'des... |
'Tests that the base url for a complex feed doesn\'t raise a 500
exception.'
| def test_complex_base_url(self):
| response = self.client.get('/syndication/depr-feeds/complex/')
self.assertEquals(response.status_code, 404)
|
'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 behaviour in Outlook and Thunderbird', 'Content', 'from@example.com', ['to@example.com'])
message = email.message()
self.assertEqual(me... |
'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')
|
'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.</... |
'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.'
| @with_django_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(... |
'String prefix + lazy translated subject = bad output
Regression for #13494'
| @with_django_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)'
| @with_django_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 #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... |
'Uploaded file names should be sanitized before ever reaching the view.'
| def test_dangerous_file_names(self):
| scary_file_names = ['/tmp/hax0rd.txt', 'C:\\Windows\\hax0rd.txt', 'C:/Windows/hax0rd.txt', '\\tmp\\hax0rd.txt', '/tmp\\hax0rd.txt', 'subdir/hax0rd.txt', 'subdir\\hax0rd.txt', 'sub/dir\\hax0rd.txt', '../../hax0rd.txt', '..\\..\\hax0rd.txt', '../..\\hax0rd.txt']
payload = []
for (i, name) in enumerate(scary_f... |
'File names over 256 characters (dangerous on some platforms) get fixed up.'
| def test_filename_overflow(self):
| name = ('%s.txt' % ('f' * 500))
payload = '\r\n'.join([('--' + client.BOUNDARY), ('Content-Disposition: form-data; name="file"; filename="%s"' % name), 'Content-Type: application/octet-stream', '', (('Oops.--' + client.BOUNDARY) + '--'), ''])
r = {'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': ... |
'The server should not block when there are upload errors (bug #8622).
This can happen if something -- i.e. an exception handler -- tries to
access POST while handling an error in parsing POST. This shouldn\'t
cause an infinite loop!'
| def test_file_error_blocking(self):
| class POSTAccessingHandler(client.ClientHandler, ):
"A handler that'll access POST during an exception."
def handle_uncaught_exception(self, request, resolver, exc_info):
ret = super(POSTAccessingHandler, self).handle_uncaught_exception(request, resolver, exc_info)
... |
'Permission errors are not swallowed'
| def test_readonly_root(self):
| os.chmod(temp_storage.location, 320)
try:
self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
except OSError as err:
self.assertEquals(err.errno, errno.EACCES)
except Exception as err:
self.fail(('OSError [Errno %s] not raised.' % errno.EACCES))
|
'The correct IOError is raised when the upload directory name exists but isn\'t a directory'
| def test_not_a_directory(self):
| fd = open(UPLOAD_TO, 'w')
fd.close()
try:
self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', 'x'))
except IOError as err:
self.assertEquals(err.args[0], ('%s exists and is not a directory.' % UPLOAD_TO))
except:
self.fail('IOError not rais... |
'Test that Django cascades deletes through generic-related
objects to their reverse relations.
This might falsely succeed if the database cascades deletes
itself immediately; the postgresql_psycopg2 backend does not
give such a false success because ForeignKeys are created with
DEFERRABLE INITIALLY DEFERRED, so its int... | def test_generic_relation_cascade(self):
| person = Person.objects.create(name='Nelson Mandela')
award = Award.objects.create(name='Nobel', content_object=person)
note = AwardNote.objects.create(note='a peace prize', award=award)
self.assertEquals(AwardNote.objects.count(), 1)
person.delete()
self.assertEquals(Award.objects.coun... |
'Test that if a M2M relationship has an explicitly-specified
through model, and some other model has an FK to that through
model, deletion is cascaded from one of the participants in
the M2M, to the through model, to its related model.
Like the above test, this could in theory falsely succeed if
the DB cascades deletes... | def test_fk_to_m2m_through(self):
| juan = Child.objects.create(name='Juan')
paints = Toy.objects.create(name='Paints')
played = PlayedWith.objects.create(child=juan, toy=paints, date=datetime.date.today())
note = PlayedWithNote.objects.create(played=played, note='the next Jackson Pollock')
self.assertEquals(PlayedWithNote.ob... |
'Regression for #13309 -- if the number of objects > chunk size, deletion still occurs'
| def test_large_deletes(self):
| for x in range(300):
track = Book.objects.create(pagecount=(x + 100))
Book.objects.all().delete()
self.assertEquals(Book.objects.count(), 0)
|
'Models module can be loaded from an app in an egg'
| def test_egg1(self):
| egg_name = ('%s/modelapp.egg' % self.egg_dir)
sys.path.append(egg_name)
models = load_app('app_with_models')
self.assertFalse((models is None))
|
'Loading an app from an egg that has no models returns no models (and no error)'
| def test_egg2(self):
| egg_name = ('%s/nomodelapp.egg' % self.egg_dir)
sys.path.append(egg_name)
models = load_app('app_no_models')
self.assertTrue((models is None))
|
'Models module can be loaded from an app located under an egg\'s top-level package'
| def test_egg3(self):
| egg_name = ('%s/omelet.egg' % self.egg_dir)
sys.path.append(egg_name)
models = load_app('omelet.app_with_models')
self.assertFalse((models is None))
|
'Loading an app with no models from under the top-level egg package generates no error'
| def test_egg4(self):
| egg_name = ('%s/omelet.egg' % self.egg_dir)
sys.path.append(egg_name)
models = load_app('omelet.app_no_models')
self.assertTrue((models is None))
|
'Loading an app from an egg that has an import error in its models module raises that error'
| def test_egg5(self):
| egg_name = ('%s/brokenapp.egg' % self.egg_dir)
sys.path.append(egg_name)
self.assertRaises(ImportError, load_app, 'broken_app')
try:
load_app('broken_app')
except ImportError as e:
self.assertTrue(('modelz' in e.args[0]))
|
'The default ordering should be by name, as specified in the inner Meta
class.'
| def test_default_ordering(self):
| ma = ModelAdmin(Band, None)
names = [b.name for b in ma.queryset(None)]
self.assertEqual([u'Aerosmith', u'Radiohead', u'Van Halen'], names)
|
'Let\'s use a custom ModelAdmin that changes the ordering, and make sure
it actually changes.'
| def test_specified_ordering(self):
| class BandAdmin(ModelAdmin, ):
ordering = ('rank',)
ma = BandAdmin(Band, None)
names = [b.name for b in ma.queryset(None)]
self.assertEqual([u'Radiohead', u'Van Halen', u'Aerosmith'], names)
|
'Regression test for #6755'
| def test_issue_6755(self):
| r = Restaurant(serves_pizza=False)
r.save()
self.assertEqual(r.id, r.place_ptr_id)
orig_id = r.id
r = Restaurant(place_ptr_id=orig_id, serves_pizza=True)
r.save()
self.assertEqual(r.id, orig_id)
self.assertEqual(r.id, r.place_ptr_id)
|
'Regression test for #11764'
| def test_issue_11764(self):
| wholesalers = list(Wholesaler.objects.all().select_related())
self.assertEqual(wholesalers, [])
|
'Regression test for #7853
If the parent class has a self-referential link, make sure that any
updates to that link via the child update the right table.'
| def test_issue_7853(self):
| obj = SelfRefChild.objects.create(child_data=37, parent_data=42)
obj.delete()
|
'Regression tests for #8076
get_(next/previous)_by_date should work'
| def test_get_next_previous_by_date(self):
| c1 = ArticleWithAuthor(headline='ArticleWithAuthor 1', author='Person 1', pub_date=datetime.datetime(2005, 8, 1, 3, 0))
c1.save()
c2 = ArticleWithAuthor(headline='ArticleWithAuthor 2', author='Person 2', pub_date=datetime.datetime(2005, 8, 1, 10, 0))
c2.save()
c3 = ArticleWithAuthor(head... |
'Regression test for #8825 and #9390
Make sure all inherited fields (esp. m2m fields, in this case) appear
on the child class.'
| def test_inherited_fields(self):
| m2mchildren = list(M2MChild.objects.filter(articles__isnull=False))
self.assertEqual(m2mchildren, [])
qs = ArticleWithAuthor.objects.order_by('pub_date', 'pk')
sql = qs.query.get_compiler(qs.db).as_sql()[0]
fragment = sql[sql.find('ORDER BY'):]
pos = fragment.find('pub_date')
self.assertE... |
'Regression test for #10362
It is possible to call update() and only change a field in
an ancestor model.'
| def test_queryset_update_on_parent_model(self):
| article = ArticleWithAuthor.objects.create(author='fred', headline='Hey there!', pub_date=datetime.datetime(2009, 3, 1, 8, 0, 0))
update = ArticleWithAuthor.objects.filter(author='fred').update(headline='Oh, no!')
self.assertEqual(update, 1)
update = ArticleWithAuthor.objects.filter(pk=article.pk)... |
'Regression tests for #10406
If there\'s a one-to-one link between a child model and the parent and
no explicit pk declared, we can use the one-to-one link as the pk on
the child.'
| def test_use_explicit_o2o_to_parent_as_pk(self):
| self.assertEqual(ParkingLot2._meta.pk.name, 'parent')
self.assertEqual(ParkingLot3._meta.pk.name, 'primary_key')
self.assertEqual(ParkingLot3._meta.get_ancestor_link(Place).name, 'parent')
|
'Regression tests for #7588'
| def test_all_fields_from_abstract_base_class(self):
| QualityControl.objects.create(headline='Problems in Django', pub_date=datetime.datetime.now(), quality=10, assignee='adrian')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.