desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'File storage can get a mixin to extend the functionality of the returned file.'
def test_file_with_mixin(self):
self.assertFalse(self.storage.exists('test.file')) class TestFileMixin(object, ): mixed_in = True f = ContentFile('custom contents') f_name = self.storage.save('test.file', f) self.assertTrue(isinstance(self.storage.open('test.file', mixin=TestFileMixin), TestFileMixin)) self.storage....
'File storage returns a tuple containing directories and files.'
def test_listdir(self):
self.assertFalse(self.storage.exists('storage_test_1')) self.assertFalse(self.storage.exists('storage_test_2')) self.assertFalse(self.storage.exists('storage_dir_1')) f = self.storage.save('storage_test_1', ContentFile('custom content')) f = self.storage.save('storage_test_2', ContentFile('custom...
'File storage prevents directory traversal (files can only be accessed if they\'re below the storage location).'
def test_file_storage_prevents_directory_traversal(self):
self.assertRaises(SuspiciousOperation, self.storage.exists, '..') self.assertRaises(SuspiciousOperation, self.storage.exists, '/etc/passwd')
'Append numbers to duplicate files rather than underscores, like Trac.'
def get_available_name(self, name):
parts = name.split('.') (basename, ext) = (parts[0], parts[1:]) number = 2 while self.exists(name): name = '.'.join(([basename, str(number)] + ext)) number += 1 return name
'Regression test for #8156: files with unicode names I can\'t quite figure out the encoding situation between doctest and this file, but the actual repr doesn\'t matter; it just shouldn\'t return a unicode object.'
def test_unicode_file_names(self):
uf = UploadedFile(name=u'\xbfC\xf3mo?', content_type='text') self.assertEqual(type(uf.__repr__()), str)
'Regression test for #9610. If the directory name contains a dot and the file name doesn\'t, make sure we still mangle the file name instead of the directory name.'
def test_directory_with_dot(self):
self.storage.save('dotted.path/test', ContentFile('1')) self.storage.save('dotted.path/test', ContentFile('2')) self.assertFalse(os.path.exists(os.path.join(self.storage_dir, 'dotted_.path'))) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test'))) self.assertTrue(os.path...
'File names with a dot as their first character don\'t have an extension, and the underscore should get added to the end.'
def test_first_character_dot(self):
self.storage.save('dotted.path/.test', ContentFile('1')) self.storage.save('dotted.path/.test', ContentFile('2')) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test'))) if (sys.version_info < (2, 6)): self.assertTrue(os.path.exists(os.path.join(self.storage_dir, 'do...
'Open files passed into get_image_dimensions() should stay opened.'
@unittest.skipUnless(Image, 'PIL not installed') def test_not_closing_of_files(self):
empty_io = StringIO() try: get_image_dimensions(empty_io) finally: self.assertTrue((not empty_io.closed))
'get_image_dimensions() called with a filename should closed the file.'
@unittest.skipUnless(Image, 'PIL not installed') def test_closing_of_filenames(self):
class FileWrapper(object, ): _closed = [] def __init__(self, f): self.f = f def __getattr__(self, name): return getattr(self.f, name) def close(self): self._closed.append(True) self.f.close() def catching_open(*args): return...
'Multiple calls of get_image_dimensions() should return the same size.'
@unittest.skipUnless(Image, 'PIL not installed') def test_multiple_calls(self):
from django.core.files.images import ImageFile img_path = os.path.join(os.path.dirname(__file__), 'test.png') image = ImageFile(open(img_path, 'rb')) image_pil = Image.open(img_path) (size_1, size_2) = (get_image_dimensions(image), get_image_dimensions(image)) self.assertEqual(image_pil.size, si...
'Regression test for #10153: foreign key __gte lookups.'
def test_related_gte_lookup(self):
Worker.objects.filter(department__gte=0)
'Regression test for #10153: foreign key __lte lookups.'
def test_related_lte_lookup(self):
Worker.objects.filter(department__lte=0)
'Regression test for #10348: ChangeList.get_query_set() shouldn\'t overwrite a custom select_related provided by ModelAdmin.queryset().'
def test_select_related_preserved(self):
m = ChildAdmin(Child, admin.site) cl = ChangeList(MockRequest(), Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) self.assertEqual(cl.query_set.query.select_related, {'parent': {'name': {}}})
'Regression test for #14982: EMPTY_CHANGELIST_VALUE should be honored for relationship fields'
def test_result_list_empty_changelist_value(self):
new_child = Child.objects.create(name='name', parent=None) request = MockRequest() m = ChildAdmin(Child, admin.site) cl = ChangeList(request, Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) cl....
'Verifies that inclusion tag result_list generates a table when with default ModelAdmin settings.'
def test_result_list_html(self):
new_parent = Parent.objects.create(name='parent') new_child = Child.objects.create(name='name', parent=new_parent) request = MockRequest() m = ChildAdmin(Child, admin.site) cl = ChangeList(request, Child, m.list_display, m.list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_...
'Regression tests for #11791: Inclusion tag result_list generates a table and this checks that the items are nested within the table element tags. Also a regression test for #13599, verifies that hidden fields when list_editable is enabled are rendered in a div outside the table.'
def test_result_list_editable_html(self):
new_parent = Parent.objects.create(name='parent') new_child = Child.objects.create(name='name', parent=new_parent) request = MockRequest() m = ChildAdmin(Child, admin.site) m.list_display = ['id', 'name', 'parent'] m.list_display_links = ['id'] m.list_editable = ['name'] cl = ChangeList(...
'Regression test for #14312: list_editable with pagination'
def test_result_list_editable(self):
new_parent = Parent.objects.create(name='parent') for i in range(200): new_child = Child.objects.create(name=('name %s' % i), parent=new_parent) request = MockRequest() request.GET['p'] = (-1) m = ChildAdmin(Child, admin.site) m.list_display = ['id', 'name', 'parent'] m.list_displ...
'Regression test for #13902: When using a ManyToMany in list_filter, results shouldn\'t apper more than once. Basic ManyToMany.'
def test_distinct_for_m2m_in_list_filter(self):
blues = Genre.objects.create(name='Blues') band = Band.objects.create(name='B.B. King Review', nr_of_members=11) band.genres.add(blues) band.genres.add(blues) m = BandAdmin(Band, admin.site) request = MockFilterRequest('genres', blues.pk) cl = ChangeList(request, Band, m.list_display, ...
'Regression test for #13902: When using a ManyToMany in list_filter, results shouldn\'t apper more than once. With an intermediate model.'
def test_distinct_for_through_m2m_in_list_filter(self):
lead = Musician.objects.create(name='Vox') band = Group.objects.create(name='The Hype') Membership.objects.create(group=band, music=lead, role='lead voice') Membership.objects.create(group=band, music=lead, role='bass player') m = GroupAdmin(Group, admin.site) request = MockFilterReques...
'Regression test for #13902: When using a ManyToMany in list_filter, results shouldn\'t apper more than once. Model managed in the admin inherits from the one that defins the relationship.'
def test_distinct_for_inherited_m2m_in_list_filter(self):
lead = Musician.objects.create(name='John') four = Quartet.objects.create(name='The Beatles') Membership.objects.create(group=four, music=lead, role='lead voice') Membership.objects.create(group=four, music=lead, role='guitar player') m = QuartetAdmin(Quartet, admin.site) request = Mock...
'Regression test for #13902: When using a ManyToMany in list_filter, results shouldn\'t apper more than once. Target of the relationship inherits from another.'
def test_distinct_for_m2m_to_inherited_in_list_filter(self):
lead = ChordsMusician.objects.create(name='Player A') three = ChordsBand.objects.create(name='The Chords Trio') Invitation.objects.create(band=three, player=lead, instrument='guitar') Invitation.objects.create(band=three, player=lead, instrument='bass') m = ChordsBandAdmin(ChordsBand, admin...
'Regressions tests for #15819: If a field listed in list_filters is a non-unique related object, distinct() must be called.'
def test_distinct_for_non_unique_related_object_in_list_filter(self):
parent = Parent.objects.create(name='Mary') Child.objects.create(parent=parent, name='Daniel') Child.objects.create(parent=parent, name='Daniel') m = ParentAdmin(Parent, admin.site) request = MockFilterRequest('child__name', 'Daniel') cl = ChangeList(request, Parent, m.list_display, m.list_displ...
'Regressions tests for #15819: If a field listed in search_fields is a non-unique related object, distinct() must be called.'
def test_distinct_for_non_unique_related_object_in_search_fields(self):
parent = Parent.objects.create(name='Mary') Child.objects.create(parent=parent, name='Danielle') Child.objects.create(parent=parent, name='Daniel') m = ParentAdmin(Parent, admin.site) request = MockSearchRequest('daniel') cl = ChangeList(request, Parent, m.list_display, m.list_display_links, m.l...
'Regression tests for #12893: Pagination in admins changelist doesn\'t use queryset set by modeladmin.'
def test_pagination(self):
parent = Parent.objects.create(name='anything') for i in range(30): Child.objects.create(name=('name %s' % i), parent=parent) Child.objects.create(name=('filtered %s' % i), parent=parent) request = MockRequest() m = ChildAdmin(Child, admin.site) cl = ChangeList(request, Child, ...
'Regression test for #12913. Make sure fields with choices respect show_hidden_initial as a kwarg to models.Field.formfield()'
def test_show_hidden_initial(self):
choices = [(0, 0), (1, 1)] model_field = models.Field(choices=choices) form_field = model_field.formfield(show_hidden_initial=True) self.assertTrue(form_field.show_hidden_initial) form_field = model_field.formfield(show_hidden_initial=False) self.assertFalse(form_field.show_hidden_initial)
'Regression test for #13071: NullBooleanField should not throw a validation error when given a value of None.'
def test_nullbooleanfield_blank(self):
nullboolean = NullBooleanModel(nbfield=None) try: nullboolean.full_clean() except ValidationError as e: self.fail(('NullBooleanField failed validation with value of None: %s' % e.messages))
'We should be able to filter decimal fields using strings (#8023)'
def test_filter_with_strings(self):
Foo.objects.create(id=1, a='abc', d=Decimal('12.34')) self.assertEqual(list(Foo.objects.filter(d=u'1.23')), [])
'Ensure decimals don\'t go through a corrupting float conversion during save (#5079).'
def test_save_without_float_conversion(self):
bd = BigD(d='12.9') bd.save() bd = BigD.objects.get(pk=bd.pk) self.assertEqual(bd.d, Decimal('12.9'))
'Ensure that really big values can be used in a filter statement, even with older Python versions.'
def test_lookup_really_big_value(self):
Foo.objects.filter(d__gte=100000000000)
'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')
'Test that PendingDeprecationWarning 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\\.", PendingDeprecationWarning) _trans.__dict__ = {} self.assertRaises(Pendin...
'Test that PendingDeprecationWarning 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\\.", PendingDe...
'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)) activate('de') try: self.assertEqual(u'Ringo hinzuf\xfcgen', (s % d)) activate('pl') self.assertEqual(u'Dodaj Ringo', (s % d)) finally: deactivate() s1 ...
'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)) activate('de') try: self.assertEqual(SafeUnicode, type(ugettext(s))) finally: deactivate() self.assertEqual('aPassword', (SafeString('a') + s)) self.assertEqual('Passworda', (s + SafeString('a'))) self.assert...
'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 ca_translation = translation('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' activate('ca') try: self.assertEqual(u'Catalan Mac\nEOF\n'...
'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')
'Localization of numbers'
def test_locale_independent(self):
settings.USE_L10N = True settings.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')) settings.USE_THOUS...
'Catalan locale with format i18n disabled translations will be used, but not formats'
def test_l10n_disabled(self):
settings.USE_L10N = False activate('ca') try: 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.', time_format(self.t)) ...
'Check if sublocales fall back to the main locale'
def test_sub_locales(self):
settings.USE_L10N = True activate('de-at') settings.USE_THOUSAND_SEPARATOR = True try: self.assertEqual(u'66.666,666', Template('{{ n }}').render(self.ctxt)) finally: deactivate() activate('es-us') try: self.assertEqual(u'31 de diciembre de 2009', da...
'Tests if form input is correctly localized'
def test_localized_input(self):
settings.USE_L10N = True activate('de-at') try: form6 = CompanyForm({'name': u'acme', 'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0), 'cents_payed': decimal.Decimal('59.47'), 'products_delivered': 12000}) self.assertEqual(True, form6.is_valid()) self.assertEqual(form6.as_ul()...
'Tests the iter_format_modules function.'
def test_iter_format_modules(self):
activate('de-at') old_format_module_path = settings.FORMAT_MODULE_PATH try: settings.USE_L10N = True de_format_mod = import_module('django.conf.locale.de.formats') self.assertEqual(list(iter_format_modules('de')), [de_format_mod]) settings.FORMAT_MODULE_PATH = 'regressiontest...
'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):
from django.utils.translation.trans_real import get_language_from_request g = get_language_from_request from django.http import HttpRequest r = HttpRequest r.COOKIES = {} r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt-br'} self.assertEqual('pt-br', g(r)) r.META = {'HTTP_ACCEPT_LANGUAGE': 'pt'} ...
'Now test that we parse language preferences stored in a cookie correctly.'
def test_parse_language_cookie(self):
from django.utils.translation.trans_real import get_language_from_request g = get_language_from_request from django.http import HttpRequest r = HttpRequest r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: 'pt-br'} r.META = {} self.assertEqual('pt-br', g(r)) r.COOKIES = {settings.LANGUAGE_COOK...
'Simple baseline behavior with one locale for all the supported i18n constructs.'
def test_single_locale_activation(self):
activate('fr') self.assertEqual(Template("{{ _('Yes') }}").render(Context({})), 'Oui') self.assertEqual(Template("{% load i18n %}{% trans 'Yes' %}").render(Context({})), 'Oui') self.assertEqual(Template('{% load i18n %}{% blocktrans %}Yes{% endblocktrans %}')...
'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))
'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...
'Generic inline formsets should respect include.'
def testExcludeParam(self):
e = self._create_object(EpisodeExclude) response = self.client.get(('/generic_inline_admin/admin/generic_inline_admin/episodeexclude/%s/' % e.pk)) formset = response.context['inline_admin_formsets'][0].formset self.assertFalse(('url' in formset.forms[0]), 'The formset has excluded "url" f...
'Pull the appropriate field data from the context to pass to the next wizard step'
def grabFieldData(self, response):
previous_fields = response.context['previous_fields'] fields = {'wizard_step': response.context['step0']} def grab(m): fields[m.group(1)] = m.group(2) return '' self.input_re.sub(grab, previous_fields) return fields
'Helper function to test each step of the wizard - Make sure the call succeeded - Make sure response is the proper step number - return the result from the post for the next step'
def checkWizardStep(self, response, step_no):
step_count = len(self.wizard_step_data) self.assertEqual(response.status_code, 200) self.assertContains(response, ('Step %d of %d' % (step_no, step_count))) data = self.grabFieldData(response) data.update(self.wizard_step_data[(step_no - 1)]) return self.client.post(self.wizard_url, dat...
'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 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 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=utf8')
'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...
'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'])...
'Normal module existence can be tested'
def test_loader(self):
test_module = import_module('regressiontests.utils.test_module') self.assertTrue(module_has_submodule(test_module, 'good_module')) mod = import_module('regressiontests.utils.test_module.good_module') self.assertEqual(mod.content, 'Good Module') self.assertTrue(module_has_submodule(test_module, 'b...
'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')
'Test a middleware that implements process_view.'
def test_process_view_middleware(self):
xview(self.rf.get('/'))