desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Dummy cache values can\'t be decremented'
| def test_decr(self):
| self.cache.set('answer', 42)
self.assertRaises(ValueError, self.cache.decr, 'answer')
self.assertRaises(ValueError, self.cache.decr, 'does_not_exist')
|
'All data types are ignored equally by the dummy cache'
| def test_data_types(self):
| stuff = {'string': 'this is a string', 'int': 42, 'list': [1, 2, 3, 4], 'tuple': (1, 2, 3, 4), 'dict': {'A': 1, 'B': 2}, 'function': f, 'class': C}
self.cache.set('stuff', stuff)
self.assertEqual(self.cache.get('stuff'), None)
|
'Expiration has no effect on the dummy cache'
| def test_expiration(self):
| self.cache.set('expire1', 'very quickly', 1)
self.cache.set('expire2', 'very quickly', 1)
self.cache.set('expire3', 'very quickly', 1)
time.sleep(2)
self.assertEqual(self.cache.get('expire1'), None)
self.cache.add('expire2', 'newvalue')
self.assertEqual(self.cache.get('expire2'), No... |
'Unicode values are ignored by the dummy cache'
| def test_unicode(self):
| stuff = {u'ascii': u'ascii_value', u'unicode_ascii': u'I\xf1t\xebrn\xe2ti\xf4n\xe0liz\xe6ti\xf8n1', u'I\xf1t\xebrn\xe2ti\xf4n\xe0liz\xe6ti\xf8n': u'I\xf1t\xebrn\xe2ti\xf4n\xe0liz\xe6ti\xf8n2', u'ascii': {u'x': 1}}
for (key, value) in stuff.items():
self.cache.set(key, value)
self.assertEqual(sel... |
'set_many does nothing for the dummy cache backend'
| def test_set_many(self):
| self.cache.set_many({'a': 1, 'b': 2})
|
'delete_many does nothing for the dummy cache backend'
| def test_delete_many(self):
| self.cache.delete_many(['a', 'b'])
|
'clear does nothing for the dummy cache backend'
| def test_clear(self):
| self.cache.clear()
|
'Using a timeout greater than 30 days makes memcached think
it is an absolute expiration timestamp instead of a relative
offset. Test that we honour this convention. Refs #12399.'
| def test_long_timeout(self):
| self.cache.set('key1', 'eggs', ((((60 * 60) * 24) * 30) + 1))
self.assertEqual(self.cache.get('key1'), 'eggs')
self.cache.add('key2', 'ham', ((((60 * 60) * 24) * 30) + 1))
self.assertEqual(self.cache.get('key2'), 'ham')
self.cache.set_many({'key3': 'sausage', 'key4': 'lobster bisque'}, ((((60 * 6... |
'This is implemented as a utility method, because only some of the backends
implement culling. The culling algorithm also varies slightly, so the final
number of entries will vary between backends'
| def perform_cull_test(self, initial_count, final_count):
| for i in range(1, initial_count):
self.cache.set(('cull%d' % i), 'value', 1000)
count = 0
for i in range(1, initial_count):
if self.cache.has_key(('cull%d' % i)):
count = (count + 1)
self.assertEqual(count, final_count)
|
'All the builtin backends (except memcached, see below) should warn on
keys that would be refused by memcached. This encourages portable
caching code without making it too difficult to use production backends
with more liberal key rules. Refs #6447.'
| def test_invalid_keys(self):
| _warnings_state = get_warnings_state()
warnings.simplefilter('error', CacheKeyWarning)
try:
self.assertRaises(CacheKeyWarning, self.cache.set, 'key with spaces', 'value')
self.assertRaises(CacheKeyWarning, self.cache.set, ('a' * 251), 'value')
finally:
restore_warnings_stat... |
'Test that keys are hashed into subdirectories correctly'
| def test_hashing(self):
| self.cache.set('foo', 'bar')
keyhash = md5_constructor('foo').hexdigest()
keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
self.assert_(os.path.exists(keypath))
|
'Make sure that the created subdirectories are correctly removed when empty.'
| def test_subdirectory_removal(self):
| self.cache.set('foo', 'bar')
keyhash = md5_constructor('foo').hexdigest()
keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:])
self.assert_(os.path.exists(keypath))
self.cache.delete('foo')
self.assert_((not os.path.exists(keypath)))
self.assert_((not os.path.exists(o... |
'Helper method that instantiates a Paginator object from the passed
params and then checks that its attributes match the passed output.'
| def check_paginator(self, params, output):
| (count, num_pages, page_range) = output
paginator = Paginator(*params)
self.check_attribute('count', paginator, count, params)
self.check_attribute('num_pages', paginator, num_pages, params)
self.check_attribute('page_range', paginator, page_range, params)
|
'Helper method that checks a single attribute and gives a nice error
message upon test failure.'
| def check_attribute(self, name, paginator, expected, params):
| got = getattr(paginator, name)
self.assertEqual(expected, got, ("For '%s', expected %s but got %s. Paginator parameters were: %s" % (name, expected, got, params)))
|
'Tests the paginator attributes using varying inputs.'
| def test_paginator(self):
| nine = [1, 2, 3, 4, 5, 6, 7, 8, 9]
ten = (nine + [10])
eleven = (ten + [11])
tests = (((ten, 4, 0, False), (10, 3, [1, 2, 3])), ((ten, 4, 1, False), (10, 3, [1, 2, 3])), ((ten, 4, 2, False), (10, 2, [1, 2])), ((ten, 4, 5, False), (10, 2, [1, 2])), ((ten, 4, 6, False), (10, 1, [1])), ((ten, 4, 0, True), ... |
'Helper method that instantiates a Paginator object from the passed
params and then checks that the start and end indexes of the passed
page_num match those given as a 2-tuple in indexes.'
| def check_indexes(self, params, page_num, indexes):
| paginator = Paginator(*params)
if (page_num == 'first'):
page_num = 1
elif (page_num == 'last'):
page_num = paginator.num_pages
page = paginator.page(page_num)
(start, end) = indexes
msg = 'For %s of page %s, expected %s but got %s. Paginator para... |
'Tests that paginator pages have the correct start and end indexes.'
| def test_page_indexes(self):
| ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
tests = (((ten, 1, 0, True), (1, 1), (10, 10)), ((ten, 2, 0, True), (1, 2), (9, 10)), ((ten, 3, 0, True), (1, 3), (10, 10)), ((ten, 5, 0, True), (1, 5), (6, 10)), ((ten, 1, 1, True), (1, 1), (9, 10)), ((ten, 1, 2, True), (1, 1), (8, 10)), ((ten, 3, 1, True), (1, 3), (7, 10)... |
'django_admin.py will autocomplete option flags'
| def test_django_admin_py(self):
| self._user_input('django-admin.py sqlall --v')
output = self._run_autocomplete()
self.assertEqual(output, ['--verbosity='])
|
'manage.py will autocomplete option flags'
| def test_manage_py(self):
| self._user_input('manage.py sqlall --v')
output = self._run_autocomplete()
self.assertEqual(output, ['--verbosity='])
|
'A custom command can autocomplete option flags'
| def test_custom_command(self):
| self._user_input('django-admin.py test_command --l')
output = self._run_autocomplete()
self.assertEqual(output, ['--list'])
|
'Subcommands can be autocompleted'
| def test_subcommands(self):
| self._user_input('django-admin.py sql')
output = self._run_autocomplete()
self.assertEqual(output, ['sql sqlall sqlclear sqlcustom sqlflush sqlindexes sqlinitialdata sqlreset sqlsequencereset'])
|
'No errors, just an empty list if there are no autocomplete options'
| def test_help(self):
| self._user_input('django-admin.py help --')
output = self._run_autocomplete()
self.assertEqual(output, [''])
|
'Command arguments will be autocompleted'
| def test_runfcgi(self):
| self._user_input('django-admin.py runfcgi h')
output = self._run_autocomplete()
self.assertEqual(output, ['host='])
|
'Application names will be autocompleted for an AppCommand'
| def test_app_completion(self):
| self._user_input('django-admin.py sqlall a')
output = self._run_autocomplete()
app_labels = [name.split('.')[(-1)] for name in settings.INSTALLED_APPS]
self.assertEqual(output, sorted((label for label in app_labels if label.startswith('a'))))
|
'get_storage_class returns the class for a storage backend name/path.'
| def test_get_filesystem_storage(self):
| self.assertEqual(get_storage_class('django.core.files.storage.FileSystemStorage'), FileSystemStorage)
|
'get_storage_class raises an error if the requested import don\'t exist.'
| def test_get_invalid_storage_module(self):
| self.assertRaisesErrorWithMessage(ImproperlyConfigured, "NonExistingStorage isn't a storage module.", get_storage_class, 'NonExistingStorage')
|
'get_storage_class raises an error if the requested class don\'t exist.'
| def test_get_nonexisting_storage_class(self):
| self.assertRaisesErrorWithMessage(ImproperlyConfigured, 'Storage module "django.core.files.storage" does not define a "NonExistingStorage" class.', get_storage_class, 'django.core.files.storage.NonExistingStorage')
|
'get_storage_class raises an error if the requested module don\'t exist.'
| def test_get_nonexisting_storage_module(self):
| self.assertRaisesErrorWithMessage(ImproperlyConfigured, 'Error importing storage module django.core.files.non_existing_storage: "No module named non_existing_storage"', get_storage_class, 'django.core.files.non_existing_storage.NonExistingStorage')
|
'Standard file access options are available, and work as expected.'
| def test_file_access_options(self):
| self.assertFalse(self.storage.exists('storage_test'))
f = self.storage.open('storage_test', 'w')
f.write('storage contents')
f.close()
self.assert_(self.storage.exists('storage_test'))
f = self.storage.open('storage_test', 'r')
self.assertEqual(f.read(), 'storage contents')
f.close... |
'File storage extracts the filename from the content object if no
name is given explicitly.'
| def test_file_save_without_name(self):
| self.assertFalse(self.storage.exists('test.file'))
f = ContentFile('custom contents')
f.name = 'test.file'
storage_f_name = self.storage.save(None, f)
self.assertEqual(storage_f_name, f.name)
self.assert_(os.path.exists(os.path.join(self.temp_dir, f.name)))
self.storage.delete(storage_f_n... |
'File storage returns the full path of a file'
| def test_file_path(self):
| self.assertFalse(self.storage.exists('test.file'))
f = ContentFile('custom contents')
f_name = self.storage.save('test.file', f)
self.assertEqual(self.storage.path(f_name), os.path.join(self.temp_dir, f_name))
self.storage.delete(f_name)
|
'File storage returns a url to access a given file from the Web.'
| def test_file_url(self):
| self.assertEqual(self.storage.url('test.file'), ('%s%s' % (self.storage.base_url, 'test.file')))
self.assertEqual(self.storage.url("~!*()'@#$%^&*abc`+=.file"), "/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%3D.file")
self.assertEqual(self.storage.url('a/b\\c.file'), '/test_media_url/a/b/c.file')
se... |
'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.assert_(isinstance(self.storage.open('test.file', mixin=TestFileMixin), TestFileMixin))
self.storage.del... |
'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.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/test')))
self.assert_(os.path.exist... |
'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.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.path/.test')))
if (sys.version_info < (2, 6)):
self.assert_(os.path.exists(os.path.join(self.storage_dir, 'dotted.p... |
'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 #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))
|
'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])
|
'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.assert_(('BMW M3' not in response.content))
self.assert_(('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)
|
'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')
|
'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.assertEquals(timesince(self.t, self.t), u'0 minutes')
|
'Microseconds and seconds are ignored.'
| def test_ignore_microseconds_and_seconds(self):
| self.assertEquals(timesince(self.t, (self.t + self.onemicrosecond)), u'0 minutes')
self.assertEquals(timesince(self.t, (self.t + self.onesecond)), u'0 minutes')
|
'Test other units.'
| def test_other_units(self):
| self.assertEquals(timesince(self.t, (self.t + self.oneminute)), u'1 minute')
self.assertEquals(timesince(self.t, (self.t + self.onehour)), u'1 hour')
self.assertEquals(timesince(self.t, (self.t + self.oneday)), u'1 day')
self.assertEquals(timesince(self.t, (self.t + self.oneweek)), u'1 week'... |
'Test multiple units.'
| def test_multiple_units(self):
| self.assertEquals(timesince(self.t, ((self.t + (2 * self.oneday)) + (6 * self.onehour))), u'2 days, 6 hours')
self.assertEquals(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.assertEquals(timesince(self.t, (((self.t + (2 * self.oneweek)) + (3 * self.onehour)) + (4 * self.oneminute))), u'2 weeks')
self.assertEquals(timesince(self.t, ((self.t + (4 * self.oneday)) + (5 * self.oneminute))), u'4 days')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.