desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test the use of a lazy callable for ForeignKey.default'
def test_callable_default(self):
a = Foo.objects.create(id=1, a='abc', d=Decimal('12.34')) b = Bar.objects.create(b='bcd') self.assertEqual(b.a, a)
'DateTimeField.to_python should support usecs'
def test_datetimefield_to_python_usecs(self):
f = models.DateTimeField() self.assertEqual(f.to_python('2001-01-02 03:04:05.000006'), datetime.datetime(2001, 1, 2, 3, 4, 5, 6)) self.assertEqual(f.to_python('2001-01-02 03:04:05.999999'), datetime.datetime(2001, 1, 2, 3, 4, 5, 999999))
'TimeField.to_python should support usecs'
def test_timefield_to_python_usecs(self):
f = models.TimeField() self.assertEqual(f.to_python('01:02:03.000004'), datetime.time(1, 2, 3, 4)) self.assertEqual(f.to_python('01:02:03.999999'), datetime.time(1, 2, 3, 999999))
'Test that BooleanField with choices and defaults doesn\'t generate a formfield with the blank option (#9640, #10549).'
def test_booleanfield_choices_blank(self):
choices = [(1, u'Si'), (2, 'No')] f = models.BooleanField(choices=choices, default=1, null=True) self.assertEqual(f.formfield().choices, ([('', '---------')] + choices)) f = models.BooleanField(choices=choices, default=1, null=False) self.assertEqual(f.formfield().choices, choices)
'Check that get_choices and get_flatchoices interact with get_FIELD_display to return the expected values (#7913).'
def test_choices_and_field_display(self):
self.assertEqual(Whiz(c=1).get_c_display(), 'First') self.assertEqual(Whiz(c=0).get_c_display(), 'Other') self.assertEqual(Whiz(c=9).get_c_display(), 9) self.assertEqual(Whiz(c=None).get_c_display(), None) self.assertEqual(Whiz(c='').get_c_display(), '')
'Make sure SlugField honors max_length (#9706)'
def test_slugfield_max_length(self):
bs = BigS.objects.create(s=('slug' * 50)) bs = BigS.objects.get(pk=bs.pk) self.assertEqual(bs.s, ('slug' * 50))
'Test that FileField.save_form_data will clear its instance attribute value if passed False.'
def test_clearable(self):
d = Document(myfile='something.txt') self.assertEqual(d.myfile, 'something.txt') field = d._meta.get_field('myfile') field.save_form_data(d, False) self.assertEqual(d.myfile, '')
'Test that FileField.save_form_data considers None to mean "no change" rather than "clear".'
def test_unchanged(self):
d = Document(myfile='something.txt') self.assertEqual(d.myfile, 'something.txt') field = d._meta.get_field('myfile') field.save_form_data(d, None) self.assertEqual(d.myfile, 'something.txt')
'Test that FileField.save_form_data, if passed a truthy value, updates its instance attribute.'
def test_changed(self):
d = Document(myfile='something.txt') self.assertEqual(d.myfile, 'something.txt') field = d._meta.get_field('myfile') field.save_form_data(d, 'else.txt') self.assertEqual(d.myfile, 'else.txt')
'Ensure that message contexts are correctly extracted for the {% trans %} and {% blocktrans %} template tags. Refs #14806.'
def test_template_message_context_extractor(self):
os.chdir(self.test_dir) management.call_command('makemessages', locale=LOCALE, verbosity=0) self.assertTrue(os.path.exists(self.PO_FILE)) with open(self.PO_FILE, 'r') as fp: po_contents = fp.read() self.assertTrue(('msgctxt "Special trans context #1"' in po_contents)) ...
'Test that DeprecationWarning is generated when a deprecated project level locale/ subdir is present.'
def test_warn_if_project_has_locale_subdir(self):
project_path = join(dirname(abspath(__file__)), '..') warnings.filterwarnings('error', "Translations in the project directory aren't supported anymore\\. Use the LOCALE_PATHS setting instead\\.", DeprecationWarning) _trans.__dict__ = {} self.assertRaises(DeprecationWa...
'Test that DeprecationWarning isn\'t generated when a deprecated project level locale/ subdir is also included in LOCALE_PATHS.'
def test_no_warn_if_project_and_locale_paths_overlap(self):
project_path = join(dirname(abspath(__file__)), '..') settings.LOCALE_PATHS += (normpath(join(project_path, 'locale')),) warnings.filterwarnings('error', "Translations in the project directory aren't supported anymore\\. Use the LOCALE_PATHS setting instead\\.", Deprecati...
'Format string interpolation should work with *_lazy objects.'
def test_lazy_objects(self):
s = ugettext_lazy('Add %(name)s') d = {'name': 'Ringo'} self.assertEqual(u'Add Ringo', (s % d)) with translation.override('de', deactivate=True): self.assertEqual(u'Ringo hinzuf\xfcgen', (s % d)) with translation.override('pl'): self.assertEqual(u'Dodaj Ringo', (s...
'Ensure that message contexts are taken into account the {% trans %} and {% blocktrans %} template tags. Refs #14806.'
def test_template_tags_pgettext(self):
extended_locale_paths = (settings.LOCALE_PATHS + (os.path.join(here, 'other', 'locale'),)) with self.settings(LOCALE_PATHS=extended_locale_paths): from django.utils.translation import trans_real trans_real._active = local() trans_real._translations = {} with translation.override(...
'unicode(string_concat(...)) should not raise a TypeError - #4796'
def test_string_concat(self):
import django.utils.translation self.assertEqual(u'django', unicode(django.utils.translation.string_concat('dja', 'ngo')))
'Translating a string requiring no auto-escaping shouldn\'t change the "safe" status.'
def test_safe_status(self):
s = mark_safe('Password') self.assertEqual(SafeString, type(s)) with translation.override('de', deactivate=True): self.assertEqual(SafeUnicode, type(ugettext(s))) self.assertEqual('aPassword', (SafeString('a') + s)) self.assertEqual('Passworda', (s + SafeString('a'))) self.assertEqual('P...
'Translations on files with mac or dos end of lines will be converted to unix eof in .po catalogs, and they have to match when retrieved'
def test_maclines(self):
from django.utils.translation.trans_real import translation as Trans ca_translation = Trans('ca') ca_translation._catalog[u'Mac\nEOF\n'] = u'Catalan Mac\nEOF\n' ca_translation._catalog[u'Win\nEOF\n'] = u'Catalan Win\nEOF\n' with translation.override('ca', deactivate=True): self.assertE...
'Tests the to_locale function and the special case of Serbian Latin (refs #12230 and r11299)'
def test_to_locale(self):
self.assertEqual(to_locale('en-us'), 'en_US') self.assertEqual(to_locale('sr-lat'), 'sr_Lat')
'Test the to_language function'
def test_to_language(self):
from django.utils.translation.trans_real import to_language self.assertEqual(to_language('en_US'), 'en-us') self.assertEqual(to_language('sr_Lat'), 'sr-lat')
'Error in translation file should not crash template rendering (%(person)s is translated as %(personne)s in fr.po)'
@override_settings(LOCALE_PATHS=(os.path.join(here, 'other', 'locale'),)) def test_bad_placeholder(self):
from django.template import Template, Context with translation.override('fr'): t = Template('{% load i18n %}{% blocktrans %}My name is {{ person }}.{% endblocktrans %}') rendered = t.render(Context({'person': 'James'})) self.assertEqual(rendered, 'My ...
'Localization of numbers'
def test_locale_independent(self):
with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False): self.assertEqual(u'66666.66', nformat(self.n, decimal_sep='.', decimal_pos=2, grouping=3, thousand_sep=',')) self.assertEqual(u'66666A6', nformat(self.n, decimal_sep='A', decimal_pos=1, grouping=1, thousand_sep='B')) self.asser...
'Catalan locale with format i18n disabled translations will be used, but not formats'
def test_l10n_disabled(self):
settings.USE_L10N = False with translation.override('ca', deactivate=True): self.assertEqual(u'N j, Y', get_format('DATE_FORMAT')) self.assertEqual(0, get_format('FIRST_DAY_OF_WEEK')) self.assertEqual(u'.', get_format('DECIMAL_SEPARATOR')) self.assertEqual(u'10:15 a.m.',...
'Ensure that the active locale\'s formats take precedence over the default settings even if they would be interpreted as False in a conditional test (e.g. 0 or empty string). Refs #16938.'
def test_false_like_locale_formats(self):
from django.conf.locale.fr import formats as fr_formats backup_THOUSAND_SEPARATOR = fr_formats.THOUSAND_SEPARATOR backup_FIRST_DAY_OF_WEEK = fr_formats.FIRST_DAY_OF_WEEK fr_formats.THOUSAND_SEPARATOR = '' fr_formats.FIRST_DAY_OF_WEEK = 0 with translation.override('fr'): with self.setting...
'Check if sublocales fall back to the main locale'
def test_sub_locales(self):
with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True): with translation.override('de-at', deactivate=True): self.assertEqual(u'66.666,666', Template('{{ n }}').render(self.ctxt)) with translation.override('es-us', deactivate=True): self.assertEqual(u'31 de ...
'Tests if form input is correctly localized'
def test_localized_input(self):
settings.USE_L10N = True with translation.override('de-at', deactivate=True): form6 = CompanyForm({'name': u'acme', 'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0), 'cents_paid': decimal.Decimal('59.47'), 'products_delivered': 12000}) self.assertEqual(True, form6.is_valid()) self....
'Tests the iter_format_modules function.'
def test_iter_format_modules(self):
settings.USE_L10N = True with translation.override('de-at', deactivate=True): de_format_mod = import_module('django.conf.locale.de.formats') self.assertEqual(list(iter_format_modules('de')), [de_format_mod]) with self.settings(FORMAT_MODULE_PATH='regressiontests.i18n.other.locale'): ...
'Tests the iter_format_modules function always yields format modules in a stable and correct order in presence of both base ll and ll_CC formats.'
def test_iter_format_modules_stability(self):
settings.USE_L10N = True en_format_mod = import_module('django.conf.locale.en.formats') en_gb_format_mod = import_module('django.conf.locale.en_GB.formats') self.assertEqual(list(iter_format_modules('en-gb')), [en_gb_format_mod, en_format_mod])
'Tests the {% localize %} templatetag'
def test_localize_templatetag_and_filter(self):
context = Context({'value': 3.14}) template1 = Template('{% load l10n %}{% localize %}{{ value }}{% endlocalize %};{% localize on %}{{ value }}{% endlocalize %}') template2 = Template('{% load l10n %}{{ value }};{% localize off %}{{ ...
'Testing HTTP header parsing. First, we test that we can parse the values according to the spec (and that we extract all the pieces in the right order).'
def test_parse_spec_http_header(self):
from django.utils.translation.trans_real import parse_accept_lang_header p = parse_accept_lang_header self.assertEqual([('de', 1.0)], p('de')) self.assertEqual([('en-AU', 1.0)], p('en-AU')) self.assertEqual([('*', 1.0)], p('*;q=1.00')) self.assertEqual([('en-AU', 0.123)], p('en-AU;q=0.123')) ...
'Now test that we parse a literal HTTP header correctly.'
def test_parse_literal_http_header(self):
g = get_language_from_request r = self.rf.get('/') r.COOKIES = {} r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt-br'} self.assertEqual('pt-br', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt'} self.assertEqual('pt', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'es,de'} self.assertEqual('es', g(r)) ...
'Now test that we parse language preferences stored in a cookie correctly.'
def test_parse_language_cookie(self):
g = get_language_from_request r = self.rf.get('/') r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt-br'} r.META = {} self.assertEqual('pt-br', g(r)) r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt'} r.META = {} self.assertEqual('pt', g(r)) r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: '...
'Simple baseline behavior with one locale for all the supported i18n constructs.'
def test_single_locale_activation(self):
with translation.override('fr'): self.assertEqual(Template("{{ _('Yes') }}").render(Context({})), 'Oui') self.assertEqual(Template("{% load i18n %}{% trans 'Yes' %}").render(Context({})), 'Oui') self.assertEqual(Template('{% load i18n %}{% blocktrans %}...
'Helper to call formfield_for_dbfield for a given model and field name and verify that the returned formfield is appropriate.'
def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides):
class MyModelAdmin(admin.ModelAdmin, ): pass for k in admin_overrides: setattr(MyModelAdmin, k, admin_overrides[k]) ma = MyModelAdmin(model, admin.site) ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None) if isinstance(ff.widget, widgets.RelatedFieldWidgetWr...
'Ensure the user can only see their own cars in the foreign key dropdown.'
def testFilterChoicesByRequestUser(self):
self.client.login(username='super', password='secret') response = self.client.get('/widget_admin/admin_widgets/cartire/add/') self.assertTrue(('BMW M3' not in response.content)) self.assertTrue(('Volkswagon Passat' in response.content))
'Ensure that user-supplied attrs are used. Refs #12073.'
def test_attrs(self):
w = widgets.AdminDateWidget() self.assertHTMLEqual(conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<input value="2007-12-01" type="text" class="vDateField" name="test" size="10" />') w = widgets.AdminDateWidget(attrs={'size': 20, 'class': 'myDateField'}) self.asser...
'Ensure that user-supplied attrs are used. Refs #12073.'
def test_attrs(self):
w = widgets.AdminTimeWidget() self.assertHTMLEqual(conditional_escape(w.render('test', datetime(2007, 12, 1, 9, 30))), '<input value="09:30:00" type="text" class="vTimeField" name="test" size="8" />') w = widgets.AdminTimeWidget(attrs={'size': 20, 'class': 'myTimeField'}) self.assertHT...
'Ensure that pressing the ESC key closes the date and time picker widgets. Refs #17064.'
def test_show_hide_date_time_picker_widgets(self):
from selenium.webdriver.common.keys import Keys self.admin_login(username='super', password='secret', login_url='/') self.selenium.get(('%s%s' % (self.live_server_url, '/admin_widgets/member/add/'))) self.assertEqual(self.get_css_value('#calendarbox0', 'display'), 'none') self.selenium.find_element_...
'Ensure that typing in the search box filters out options displayed in the \'from\' box.'
def test_filter(self):
from selenium.webdriver.common.keys import Keys self.school.students = [self.lisa, self.peter] self.school.alumni = [self.lisa, self.peter] self.school.save() self.admin_login(username='super', password='secret', login_url='/') self.selenium.get(('%s%s' % (self.live_server_url, ('/admin_widgets/...
'Simulate a file upload and check how many times Model.save() gets called.'
def testBug639(self):
filename = os.path.join(os.path.dirname(__file__), 'test.jpg') img = open(filename, 'rb').read() data = {'title': 'Testing'} files = {'image': SimpleUploadedFile('test.jpg', img, 'image/jpeg')} form = PhotoForm(data=data, files=files) p = form.save() self.assertEqual(p._savecount, 1)
'Make sure to delete the "uploaded" file to avoid clogging /tmp.'
def tearDown(self):
p = Photo.objects.get() p.image.delete(save=False) shutil.rmtree(temp_storage_dir)
'Exception is raised when trying to register an abstract model. Refs #12004.'
def test_abstract_model(self):
self.assertRaises(ImproperlyConfigured, self.site.register, Location)
'A smoke test to ensure GET on the add_view works.'
def testBasicAddGet(self):
response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episode/add/') self.assertEqual(response.status_code, 200)
'A smoke test to ensure GET on the change_view works.'
def testBasicEditGet(self):
response = self.client.get(('/generic_inline_admin/admin/generic_inline_admin/episode/%d/' % self.episode_pk)) self.assertEqual(response.status_code, 200)
'A smoke test to ensure POST on add_view works.'
def testBasicAddPost(self):
post_data = {'name': u'This Week in Django', 'generic_inline_admin-media-content_type-object_id-TOTAL_FORMS': u'1', 'generic_inline_admin-media-content_type-object_id-INITIAL_FORMS': u'0', 'generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS': u'0'} response = self.client.post('/generic_inl...
'A smoke test to ensure POST on edit_view works.'
def testBasicEditPost(self):
post_data = {'name': u'This Week in Django', 'generic_inline_admin-media-content_type-object_id-TOTAL_FORMS': u'3', 'generic_inline_admin-media-content_type-object_id-INITIAL_FORMS': u'2', 'generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS': u'0', 'generic_inline_admin-media-content_type-obje...
'Create a model with an attached Media object via GFK. We can\'t load content via a fixture (since the GenericForeignKey relies on content type IDs, which will vary depending on what other tests have been run), thus we do it here.'
def _create_object(self, model):
e = model.objects.create(name='This Week in Django') Media.objects.create(content_object=e, url='http://example.com/podcast.mp3') return e
'With one initial form, extra (default) at 3, there should be 4 forms.'
def testNoParam(self):
e = self._create_object(Episode) response = self.client.get(('/generic_inline_admin/admin/generic_inline_admin/episode/%s/' % e.pk)) formset = response.context['inline_admin_formsets'][0].formset self.assertEqual(formset.total_form_count(), 4) self.assertEqual(formset.initial_form_count(), 1)
'With extra=0, there should be one form.'
def testExtraParam(self):
e = self._create_object(EpisodeExtra) response = self.client.get(('/generic_inline_admin/admin/generic_inline_admin/episodeextra/%s/' % e.pk)) formset = response.context['inline_admin_formsets'][0].formset self.assertEqual(formset.total_form_count(), 1) self.assertEqual(formset.initial_form_count(),...
'With extra=5 and max_num=2, there should be only 2 forms.'
def testMaxNumParam(self):
e = self._create_object(EpisodeMaxNum) inline_form_data = '<input type="hidden" name="generic_inline_admin-media-content_type-object_id-TOTAL_FORMS" value="2" id="id_generic_inline_admin-media-content_type-object_id-TOTAL_FORMS" /><input type="hidden" name="generic_inline_admin-media-conten...
'Ensure that the custom ModelForm\'s `Meta.exclude` is respected when used in conjunction with `GenericInlineModelAdmin.readonly_fields` and when no `ModelAdmin.exclude` is defined.'
def test_custom_form_meta_exclude_with_readonly(self):
class MediaForm(ModelForm, ): class Meta: model = Media exclude = ['url'] class MediaInline(GenericTabularInline, ): readonly_fields = ['description'] form = MediaForm model = Media class EpisodeAdmin(admin.ModelAdmin, ): inlines = [MediaInline...
'Ensure that the custom ModelForm\'s `Meta.exclude` is respected by `GenericInlineModelAdmin.get_formset`, and overridden if `ModelAdmin.exclude` or `GenericInlineModelAdmin.exclude` are defined. Refs #15907.'
def test_custom_form_meta_exclude(self):
class MediaForm(ModelForm, ): class Meta: model = Media exclude = ['url'] class MediaInline(GenericTabularInline, ): exclude = ['description'] form = MediaForm model = Media class EpisodeAdmin(admin.ModelAdmin, ): inlines = [MediaInline] ma...
'Test get_tag_uri() correctly generates TagURIs.'
def test_get_tag_uri(self):
self.assertEqual(feedgenerator.get_tag_uri('http://example.org/foo/bar#headline', datetime.date(2004, 10, 25)), u'tag:example.org,2004-10-25:/foo/bar/headline')
'Test that get_tag_uri() correctly generates TagURIs from URLs with port numbers.'
def test_get_tag_uri_with_port(self):
self.assertEqual(feedgenerator.get_tag_uri('http://www.example.org:8000/2008/11/14/django#headline', datetime.datetime(2008, 11, 14, 13, 37, 0)), u'tag:www.example.org,2008-11-14:/2008/11/14/django/headline')
'Test rfc2822_date() correctly formats datetime objects.'
def test_rfc2822_date(self):
self.assertEqual(feedgenerator.rfc2822_date(datetime.datetime(2008, 11, 14, 13, 37, 0)), 'Fri, 14 Nov 2008 13:37:00 -0000')
'Test rfc2822_date() correctly formats datetime objects with tzinfo.'
def test_rfc2822_date_with_timezone(self):
self.assertEqual(feedgenerator.rfc2822_date(datetime.datetime(2008, 11, 14, 13, 37, 0, tzinfo=tzinfo.FixedOffset(datetime.timedelta(minutes=60)))), 'Fri, 14 Nov 2008 13:37:00 +0100')
'Test rfc2822_date() correctly formats date objects.'
def test_rfc2822_date_without_time(self):
self.assertEqual(feedgenerator.rfc2822_date(datetime.date(2008, 11, 14)), 'Fri, 14 Nov 2008 00:00:00 -0000')
'Test rfc3339_date() correctly formats datetime objects.'
def test_rfc3339_date(self):
self.assertEqual(feedgenerator.rfc3339_date(datetime.datetime(2008, 11, 14, 13, 37, 0)), '2008-11-14T13:37:00Z')
'Test rfc3339_date() correctly formats datetime objects with tzinfo.'
def test_rfc3339_date_with_timezone(self):
self.assertEqual(feedgenerator.rfc3339_date(datetime.datetime(2008, 11, 14, 13, 37, 0, tzinfo=tzinfo.FixedOffset(datetime.timedelta(minutes=120)))), '2008-11-14T13:37:00+02:00')
'Test rfc3339_date() correctly formats date objects.'
def test_rfc3339_date_without_time(self):
self.assertEqual(feedgenerator.rfc3339_date(datetime.date(2008, 11, 14)), '2008-11-14T00:00:00Z')
'Test to make sure Atom MIME type has UTF8 Charset parameter set'
def test_atom1_mime_type(self):
atom_feed = feedgenerator.Atom1Feed('title', 'link', 'description') self.assertEqual(atom_feed.mime_type, 'application/atom+xml; charset=utf-8')
'Test to make sure RSS MIME type has UTF8 Charset parameter set'
def test_rss_mime_type(self):
rss_feed = feedgenerator.Rss201rev2Feed('title', 'link', 'description') self.assertEqual(rss_feed.mime_type, 'application/rss+xml; charset=utf-8')
'Check that function(value) equals output. If output is None, check that function(value) equals value.'
def check_output(self, function, value, output=None):
if (output is None): output = value self.assertEqual(function(value), output)
'equal datetimes.'
def test_equal_datetimes(self):
self.assertEqual(timesince(self.t, self.t), u'0 minutes')
'Microseconds and seconds are ignored.'
def test_ignore_microseconds_and_seconds(self):
self.assertEqual(timesince(self.t, (self.t + self.onemicrosecond)), u'0 minutes') self.assertEqual(timesince(self.t, (self.t + self.onesecond)), u'0 minutes')
'Test other units.'
def test_other_units(self):
self.assertEqual(timesince(self.t, (self.t + self.oneminute)), u'1 minute') self.assertEqual(timesince(self.t, (self.t + self.onehour)), u'1 hour') self.assertEqual(timesince(self.t, (self.t + self.oneday)), u'1 day') self.assertEqual(timesince(self.t, (self.t + self.oneweek)), u'1 week') ...
'Test multiple units.'
def test_multiple_units(self):
self.assertEqual(timesince(self.t, ((self.t + (2 * self.oneday)) + (6 * self.onehour))), u'2 days, 6 hours') self.assertEqual(timesince(self.t, ((self.t + (2 * self.oneweek)) + (2 * self.oneday))), u'2 weeks, 2 days')
'If the two differing units aren\'t adjacent, only the first unit is displayed.'
def test_display_first_unit(self):
self.assertEqual(timesince(self.t, (((self.t + (2 * self.oneweek)) + (3 * self.onehour)) + (4 * self.oneminute))), u'2 weeks') self.assertEqual(timesince(self.t, ((self.t + (4 * self.oneday)) + (5 * self.oneminute))), u'4 days')
'When the second date occurs before the first, we should always get 0 minutes.'
def test_display_second_before_first(self):
self.assertEqual(timesince(self.t, (self.t - self.onemicrosecond)), u'0 minutes') self.assertEqual(timesince(self.t, (self.t - self.onesecond)), u'0 minutes') self.assertEqual(timesince(self.t, (self.t - self.oneminute)), u'0 minutes') self.assertEqual(timesince(self.t, (self.t - self.onehour))...
'When using two different timezones.'
def test_different_timezones(self):
now = datetime.datetime.now() now_tz = datetime.datetime.now(LocalTimezone(now)) now_tz_i = datetime.datetime.now(FixedOffset(((3 * 60) + 15))) self.assertEqual(timesince(now), u'0 minutes') self.assertEqual(timesince(now_tz), u'0 minutes') self.assertEqual(timeuntil(now_tz, now_tz_i), u'0...
'Both timesince and timeuntil should work on date objects (#17937).'
def test_date_objects(self):
today = datetime.date.today() self.assertEqual(timesince((today + self.oneday)), u'0 minutes') self.assertEqual(timeuntil((today - self.oneday)), u'0 minutes')
'Timesince should work with both date objects (#9672)'
def test_both_date_objects(self):
today = datetime.date.today() self.assertEqual(timeuntil((today + self.oneday), today), u'1 day') self.assertEqual(timeuntil((today - self.oneday), today), u'0 minutes') self.assertEqual(timeuntil((today + self.oneweek), today), u'1 week')
'Overwriting an item keeps it\'s place.'
def test_overwrite_ordering(self):
self.d1[1] = 'ONE' self.assertEqual(self.d1.values(), ['seven', 'ONE', 'nine'])
'New items go to the end.'
def test_append_items(self):
self.d1[0] = 'nil' self.assertEqual(self.d1.keys(), [7, 1, 9, 0])
'Deleting an item, then inserting the same key again will place it at the end.'
def test_delete_and_insert(self):
del self.d2[7] self.assertEqual(self.d2.keys(), [1, 9, 0]) self.d2[7] = 'lucky number 7' self.assertEqual(self.d2.keys(), [1, 9, 0, 7])
'Changing the keys won\'t do anything, it\'s only a copy of the keys dict.'
def test_change_keys(self):
k = self.d2.keys() k.remove(9) self.assertEqual(self.d2.keys(), [1, 9, 0, 7])
'Initialising a SortedDict with two keys will just take the first one. A real dict will actually take the second value so we will too, but we\'ll keep the ordering from the first key found.'
def test_init_keys(self):
tuples = ((2, 'two'), (1, 'one'), (2, 'second-two')) d = SortedDict(tuples) self.assertEqual(d.keys(), [2, 1]) real_dict = dict(tuples) self.assertEqual(sorted(real_dict.values()), ['one', 'second-two']) self.assertEqual(d.values(), ['second-two', 'one'])
'MergeDict can merge MultiValueDicts'
def test_mergedict_merges_multivaluedict(self):
multi1 = MultiValueDict({'key1': ['value1'], 'key2': ['value2', 'value3']}) multi2 = MultiValueDict({'key2': ['value4'], 'key4': ['value5', 'value6']}) mm = MergeDict(multi1, multi2) self.assertEqual(mm.getlist('key2'), ['value2', 'value3']) self.assertEqual(mm.getlist('key4'), ['value5', 'value6'])...
'Create temporary directory for testing extraction.'
def setUp(self):
self.old_cwd = os.getcwd() self.tmpdir = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.tmpdir) self.archive_path = os.path.join(TEST_DIR, self.archive) os.chdir(TEST_DIR)
'Normal module existence can be tested'
def test_loader(self):
test_module = import_module('regressiontests.utils.test_module') test_no_submodule = import_module('regressiontests.utils.test_no_submodule') self.assertTrue(module_has_submodule(test_module, 'good_module')) mod = import_module('regressiontests.utils.test_module.good_module') self.assertEqual(mod.co...
'Module existence can be tested inside eggs'
def test_shallow_loader(self):
egg_name = ('%s/test_egg.egg' % self.egg_dir) sys.path.append(egg_name) egg_module = import_module('egg_module') self.assertTrue(module_has_submodule(egg_module, 'good_module')) mod = import_module('egg_module.good_module') self.assertEqual(mod.content, 'Good Module') self.assertTrue(modu...
'Modules deep inside an egg can still be tested for existence'
def test_deep_loader(self):
egg_name = ('%s/test_egg.egg' % self.egg_dir) sys.path.append(egg_name) egg_module = import_module('egg_module.sub1.sub2') self.assertTrue(module_has_submodule(egg_module, 'good_module')) mod = import_module('egg_module.sub1.sub2.good_module') self.assertEqual(mod.content, 'Deep Good Modul...
'Regression for #12524 Check that pre-1000AD dates are padded with zeros if necessary'
def test_zero_padding(self):
self.assertEqual(date(1, 1, 1).strftime('%Y/%m/%d was a %A'), '0001/01/01 was a Monday')
'Theory: If you run with 100 iterations, it should take 100 times as long as running with 1 iteration.'
def test_performance_scalability(self):
(n1, n2) = (200000, 800000) elapsed = (lambda f: timeit.Timer(f, 'from django.utils.crypto import pbkdf2').timeit(number=1)) t1 = elapsed(('pbkdf2("password", "salt", iterations=%d)' % n1)) t2 = elapsed(('pbkdf2("password", "salt", iterations=%d)' % n2)) measured_scale_exponent ...
'Test that lazy also finds base class methods in the proxy object'
def test_lazy_base_class(self):
class Base(object, ): def base_method(self): pass class Klazz(Base, ): pass t = lazy((lambda : Klazz()), Klazz)() self.assertTrue(('base_method' in dir(t)))
'Test a middleware that implements process_view.'
def test_process_view_middleware(self):
process_view(self.rf.get('/'))
'Test a middleware that implements process_view, operating on a callable class.'
def test_callable_process_view_middleware(self):
class_process_view(self.rf.get('/'))
'Test that all methods of middleware are called for normal HttpResponses'
def test_full_dec_normal(self):
@full_dec def normal_view(request): t = Template('Hello world') return HttpResponse(t.render(Context({}))) request = self.rf.get('/') response = normal_view(request) self.assertTrue(getattr(request, 'process_request_reached', False)) self.assertTrue(getattr(request, 'process_v...
'Test that all methods of middleware are called for TemplateResponses in the right sequence.'
def test_full_dec_templateresponse(self):
@full_dec def template_response_view(request): t = Template('Hello world') return TemplateResponse(request, t, {}) request = self.rf.get('/') response = template_response_view(request) self.assertTrue(getattr(request, 'process_request_reached', False)) self.assertTrue(getattr(...
'Check that function(value) equals output. If output is None, check that function(value) equals value.'
def check_output(self, function, value, output=None):
if (output is None): output = value self.assertEqual(function(value), output)
'Regression for #16632. `fix_IE_for_vary` shouldn\'t crash when there\'s no Content-Type header.'
def test_fix_IE_for_vary(self):
def response_with_unsafe_content_type(): r = HttpResponse(content_type='text/unsafe') r['Vary'] = 'Cookie' return r def no_content_response_with_unsafe_content_type(): r = response_with_unsafe_content_type() del r['Content-Type'] return r rf = RequestFactory()...
'Issue 13864: force_update fails on subclassed models, if they don\'t specify custom fields.'
def test_force_update_on_inherited_model_without_fields(self):
a = SubCounter(name='count', value=1) a.save() a.value = 2 a.save(force_update=True)
'Test that signals that disconnect when being called don\'t mess future dispatching.'
def test_disconnect_in_dispatch(self):
(a, b) = (MyReceiver(1), MyReceiver(2)) signals.post_save.connect(sender=Person, receiver=a) signals.post_save.connect(sender=Person, receiver=b) p = Person.objects.create(first_name='John', last_name='Smith') self.assertTrue(a._run) self.assertTrue(b._run) self.assertEqual(signals.post_save...
'Test that the backend\'s FOR UPDATE variant appears in generated SQL when select_for_update is invoked.'
@skipUnlessDBFeature('has_select_for_update') def test_for_update_sql_generated(self):
list(Person.objects.all().select_for_update()) self.assertTrue(self.has_for_update_sql(connection))
'Test that the backend\'s FOR UPDATE NOWAIT variant appears in generated SQL when select_for_update is invoked.'
@skipUnlessDBFeature('has_select_for_update_nowait') def test_for_update_sql_generated_nowait(self):
list(Person.objects.all().select_for_update(nowait=True)) self.assertTrue(self.has_for_update_sql(connection, nowait=True))
'If nowait is specified, we expect an error to be raised rather than blocking.'
@requires_threading @skipUnlessDBFeature('has_select_for_update_nowait') @unittest.skipIf((sys.version_info[:3] == (2, 6, 1)), 'Python version is 2.6.1') def test_nowait_raises_error_on_block(self):
self.start_blocking_transaction() status = [] thread = threading.Thread(target=self.run_select_for_update, args=(status,), kwargs={'nowait': True}) thread.start() time.sleep(1) thread.join() self.end_blocking_transaction() self.check_exc(status[(-1)])
'If a SELECT...FOR UPDATE NOWAIT is run on a database backend that supports FOR UPDATE but not NOWAIT, then we should find that a DatabaseError is raised.'
@skipIfDBFeature('has_select_for_update_nowait') @skipUnlessDBFeature('has_select_for_update') @unittest.skipIf((sys.version_info[:3] == (2, 6, 1)), 'Python version is 2.6.1') def test_unsupported_nowait_raises_error(self):
self.assertRaises(DatabaseError, list, Person.objects.all().select_for_update(nowait=True))
'Utility method that runs a SELECT FOR UPDATE against all Person instances. After the select_for_update, it attempts to update the name of the only record, save, and commit. This function expects to run in a separate thread.'
def run_select_for_update(self, status, nowait=False):
status.append('started') try: transaction.enter_transaction_management(True) transaction.managed(True) people = list(Person.objects.all().select_for_update(nowait=nowait)) people[0].name = 'Fred' people[0].save() transaction.commit() except DatabaseError as e:...
'Check that a thread running a select_for_update that accesses rows being touched by a similar operation on another connection blocks correctly.'
@requires_threading @skipUnlessDBFeature('has_select_for_update') @skipUnlessDBFeature('supports_transactions') def test_block(self):
self.start_blocking_transaction() status = [] thread = threading.Thread(target=self.run_select_for_update, args=(status,)) thread.start() sanity_count = 0 while ((len(status) != 1) and (sanity_count < 10)): sanity_count += 1 time.sleep(1) if (sanity_count >= 10): rais...
'Check that running a raw query which can\'t obtain a FOR UPDATE lock raises the correct exception'
@requires_threading @skipUnlessDBFeature('has_select_for_update') def test_raw_lock_not_available(self):
self.start_blocking_transaction() def raw(status): try: list(Person.objects.raw(('SELECT * FROM %s %s' % (Person._meta.db_table, connection.ops.for_update_sql(nowait=True))))) except DatabaseError as e: status.append(e) finally: connection....
'Check that a select_for_update sets the transaction to be dirty when executed under txn management. Setting the txn dirty means that it will be either committed or rolled back by Django, which will release any locks held by the SELECT FOR UPDATE.'
@skipUnlessDBFeature('has_select_for_update') def test_transaction_dirty_managed(self):
people = list(Person.objects.select_for_update()) self.assertTrue(transaction.is_dirty())