desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Make sure inlineformsets respect commit=False regression for #10750'
def test_save_new(self):
ChildFormSet = inlineformset_factory(School, Child, exclude=[u'father', u'mother']) school = School.objects.create(name=u'test') mother = Parent.objects.create(name=u'mother') father = Parent.objects.create(name=u'father') data = {u'child_set-TOTAL_FORMS': u'1', u'child_set-INITIAL_FORMS': u'0', u'child_set-MAX_NUM_FORMS': u'0', u'child_set-0-name': u'child'} formset = ChildFormSet(data, instance=school) self.assertEqual(formset.is_valid(), True) objects = formset.save(commit=False) for obj in objects: obj.mother = mother obj.father = father obj.save() self.assertEqual(school.child_set.count(), 1)
'These should both work without a problem.'
def test_inline_formset_factory(self):
inlineformset_factory(Parent, Child, fk_name=u'mother') inlineformset_factory(Parent, Child, fk_name=u'father')
'Child has two ForeignKeys to Parent, so if we don\'t specify which one to use for the inline formset, we should get an exception.'
def test_exception_on_unspecified_foreign_key(self):
six.assertRaisesRegex(self, Exception, u"<class 'regressiontests.inline_formsets.models.Child'> has more than 1 ForeignKey to <class 'regressiontests.inline_formsets.models.Parent'>", inlineformset_factory, Parent, Child)
'If we specify fk_name, but it isn\'t a ForeignKey from the child model to the parent model, we should get an exception.'
def test_fk_name_not_foreign_key_field_from_child(self):
self.assertRaises(Exception, u"fk_name 'school' is not a ForeignKey to <class 'regressiontests.inline_formsets.models.Parent'>", inlineformset_factory, Parent, Child, fk_name=u'school')
'If the field specified in fk_name is not a ForeignKey, we should get an exception.'
def test_non_foreign_key_field(self):
six.assertRaisesRegex(self, Exception, u"<class 'regressiontests.inline_formsets.models.Child'> has no field named 'test'", inlineformset_factory, Parent, Child, fk_name=u'test')
'Dummy cache backend ignores cache set calls'
def test_simple(self):
self.cache.set(u'key', u'value') self.assertEqual(self.cache.get(u'key'), None)
'Add doesn\'t do anything in dummy cache backend'
def test_add(self):
self.cache.add(u'addkey1', u'value') result = self.cache.add(u'addkey1', u'newvalue') self.assertEqual(result, True) self.assertEqual(self.cache.get(u'addkey1'), None)
'Non-existent keys aren\'t found in the dummy cache backend'
def test_non_existent(self):
self.assertEqual(self.cache.get(u'does_not_exist'), None) self.assertEqual(self.cache.get(u'does_not_exist', u'bang!'), u'bang!')
'get_many returns nothing for the dummy cache backend'
def test_get_many(self):
self.cache.set(u'a', u'a') self.cache.set(u'b', u'b') self.cache.set(u'c', u'c') self.cache.set(u'd', u'd') self.assertEqual(self.cache.get_many([u'a', u'c', u'd']), {}) self.assertEqual(self.cache.get_many([u'a', u'b', u'e']), {})
'Cache deletion is transparently ignored on the dummy cache backend'
def test_delete(self):
self.cache.set(u'key1', u'spam') self.cache.set(u'key2', u'eggs') self.assertEqual(self.cache.get(u'key1'), None) self.cache.delete(u'key1') self.assertEqual(self.cache.get(u'key1'), None) self.assertEqual(self.cache.get(u'key2'), None)
'The has_key method doesn\'t ever return True for the dummy cache backend'
def test_has_key(self):
self.cache.set(u'hello1', u'goodbye1') self.assertEqual(self.cache.has_key(u'hello1'), False) self.assertEqual(self.cache.has_key(u'goodbye1'), False)
'The in operator doesn\'t ever return True for the dummy cache backend'
def test_in(self):
self.cache.set(u'hello2', u'goodbye2') self.assertEqual((u'hello2' in self.cache), False) self.assertEqual((u'goodbye2' in self.cache), False)
'Dummy cache values can\'t be incremented'
def test_incr(self):
self.cache.set(u'answer', 42) self.assertRaises(ValueError, self.cache.incr, u'answer') self.assertRaises(ValueError, self.cache.incr, u'does_not_exist')
'Dummy cache values can\'t be decremented'
def test_decr(self):
self.cache.set(u'answer', 42) self.assertRaises(ValueError, self.cache.decr, u'answer') self.assertRaises(ValueError, self.cache.decr, u'does_not_exist')
'All data types are ignored equally by the dummy cache'
def test_data_types(self):
stuff = {u'string': u'this is a string', u'int': 42, u'list': [1, 2, 3, 4], u'tuple': (1, 2, 3, 4), u'dict': {u'A': 1, u'B': 2}, u'function': f, u'class': C} self.cache.set(u'stuff', stuff) self.assertEqual(self.cache.get(u'stuff'), None)
'Expiration has no effect on the dummy cache'
def test_expiration(self):
self.cache.set(u'expire1', u'very quickly', 1) self.cache.set(u'expire2', u'very quickly', 1) self.cache.set(u'expire3', u'very quickly', 1) time.sleep(2) self.assertEqual(self.cache.get(u'expire1'), None) self.cache.add(u'expire2', u'newvalue') self.assertEqual(self.cache.get(u'expire2'), None) self.assertEqual(self.cache.has_key(u'expire3'), False)
'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'ascii2': {u'x': 1}} for (key, value) in stuff.items(): self.cache.set(key, value) self.assertEqual(self.cache.get(key), None)
'set_many does nothing for the dummy cache backend'
def test_set_many(self):
self.cache.set_many({u'a': 1, u'b': 2}) self.cache.set_many({u'a': 1, u'b': 2}, timeout=2, version=u'1')
'delete_many does nothing for the dummy cache backend'
def test_delete_many(self):
self.cache.delete_many([u'a', u'b'])
'clear does nothing for the dummy cache backend'
def test_clear(self):
self.cache.clear()
'Dummy cache versions can\'t be incremented'
def test_incr_version(self):
self.cache.set(u'answer', 42) self.assertRaises(ValueError, self.cache.incr_version, u'answer') self.assertRaises(ValueError, self.cache.incr_version, u'does_not_exist')
'Dummy cache versions can\'t be decremented'
def test_decr_version(self):
self.cache.set(u'answer', 42) self.assertRaises(ValueError, self.cache.decr_version, u'answer') self.assertRaises(ValueError, self.cache.decr_version, u'does_not_exist')
'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(u'key1', u'eggs', ((((60 * 60) * 24) * 30) + 1)) self.assertEqual(self.cache.get(u'key1'), u'eggs') self.cache.add(u'key2', u'ham', ((((60 * 60) * 24) * 30) + 1)) self.assertEqual(self.cache.get(u'key2'), u'ham') self.cache.set_many({u'key3': u'sausage', u'key4': u'lobster bisque'}, ((((60 * 60) * 24) * 30) + 1)) self.assertEqual(self.cache.get(u'key3'), u'sausage') self.assertEqual(self.cache.get(u'key4'), u'lobster bisque')
'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((u'cull%d' % i), u'value', 1000) count = 0 for i in range(1, initial_count): if self.cache.has_key((u'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):
def func(key, *args): return key old_func = self.cache.key_func self.cache.key_func = func try: with warnings.catch_warnings(record=True) as w: warnings.simplefilter(u'always') self.cache.set(u'key with spaces', u'value') self.assertEqual(len(w), 2) self.assertTrue(isinstance(w[0].message, CacheKeyWarning)) with warnings.catch_warnings(record=True) as w: warnings.simplefilter(u'always') self.cache.set((u'a' * 251), u'value') self.assertEqual(len(w), 1) self.assertTrue(isinstance(w[0].message, CacheKeyWarning)) finally: self.cache.key_func = old_func
'Check that multiple locmem caches are isolated'
def test_multiple_caches(self):
mirror_cache = get_cache(self.backend_name) other_cache = get_cache(self.backend_name, LOCATION=u'other') self.cache.set(u'value1', 42) self.assertEqual(mirror_cache.get(u'value1'), 42) self.assertEqual(other_cache.get(u'value1'), None)
'incr/decr does not modify expiry time (matches memcached behavior)'
def test_incr_decr_timeout(self):
key = u'value' _key = self.cache.make_key(key) self.cache.set(key, 1, timeout=(self.cache.default_timeout * 10)) expire = self.cache._expire_info[_key] self.cache.incr(key) self.assertEqual(expire, self.cache._expire_info[_key]) self.cache.decr(key) self.assertEqual(expire, self.cache._expire_info[_key])
'On memcached, we don\'t introduce a duplicate key validation step (for speed reasons), we just let the memcached API library raise its own exception on bad keys. Refs #6447. In order to be memcached-API-library agnostic, we only assert that a generic exception of some kind is raised.'
def test_invalid_keys(self):
self.assertRaises(Exception, self.cache.set, u'key with spaces', u'value') self.assertRaises(Exception, self.cache.set, (u'a' * 251), u'value')
'Test that keys are hashed into subdirectories correctly'
def test_hashing(self):
self.cache.set(u'foo', u'bar') key = self.cache.make_key(u'foo') keyhash = hashlib.md5(key.encode()).hexdigest() keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:]) self.assertTrue(os.path.exists(keypath))
'Make sure that the created subdirectories are correctly removed when empty.'
def test_subdirectory_removal(self):
self.cache.set(u'foo', u'bar') key = self.cache.make_key(u'foo') keyhash = hashlib.md5(key.encode()).hexdigest() keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:]) self.assertTrue(os.path.exists(keypath)) self.cache.delete(u'foo') self.assertTrue((not os.path.exists(keypath))) self.assertTrue((not os.path.exists(os.path.dirname(keypath)))) self.assertTrue((not os.path.exists(os.path.dirname(os.path.dirname(keypath)))))
'Ensure the constructor is correctly distinguishing between usage of CacheMiddleware as Middleware vs. usage of CacheMiddleware as view decorator and setting attributes appropriately.'
def test_constructor(self):
middleware = CacheMiddleware() self.assertEqual(middleware.cache_timeout, 30) self.assertEqual(middleware.key_prefix, u'middlewareprefix') self.assertEqual(middleware.cache_alias, u'other') self.assertEqual(middleware.cache_anonymous_only, False) as_view_decorator = CacheMiddleware(cache_alias=None, key_prefix=None) self.assertEqual(as_view_decorator.cache_timeout, 300) self.assertEqual(as_view_decorator.key_prefix, u'') self.assertEqual(as_view_decorator.cache_alias, u'default') self.assertEqual(as_view_decorator.cache_anonymous_only, False) as_view_decorator_with_custom = CacheMiddleware(cache_anonymous_only=True, cache_timeout=60, cache_alias=u'other', key_prefix=u'foo') self.assertEqual(as_view_decorator_with_custom.cache_timeout, 60) self.assertEqual(as_view_decorator_with_custom.key_prefix, u'foo') self.assertEqual(as_view_decorator_with_custom.cache_alias, u'other') self.assertEqual(as_view_decorator_with_custom.cache_anonymous_only, True)
'The cache middleware shouldn\'t cause a session access due to CACHE_MIDDLEWARE_ANONYMOUS_ONLY if nothing else has accessed the session. Refs 13283'
@override_settings(CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True) def test_cache_middleware_anonymous_only_wont_cause_session_access(self):
from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.auth.middleware import AuthenticationMiddleware middleware = CacheMiddleware() session_middleware = SessionMiddleware() auth_middleware = AuthenticationMiddleware() request = self.factory.get(u'/view_anon/') session_middleware.process_request(request) auth_middleware.process_request(request) result = middleware.process_request(request) self.assertEqual(result, None) response = hello_world_view(request, u'1') session_middleware.process_response(request, response) response = middleware.process_response(request, response) self.assertEqual(request.session.accessed, False)
'CACHE_MIDDLEWARE_ANONYMOUS_ONLY should still be effective when used with the cache_page decorator: the response to a request from an authenticated user should not be cached.'
@override_settings(CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True) def test_cache_middleware_anonymous_only_with_cache_page(self):
request = self.factory.get(u'/view_anon/') class MockAuthenticatedUser(object, ): def is_authenticated(self): return True class MockAccessedSession(object, ): accessed = True request.user = MockAuthenticatedUser() request.session = MockAccessedSession() response = cache_page(hello_world_view)(request, u'1') self.assertFalse((u'Cache-Control' in response))
'Make sure a transaction consisting of raw SQL execution gets committed by the commit_on_success decorator.'
def test_raw_committed_on_success(self):
@commit_on_success def raw_sql(): 'Write a record using raw sql under a commit_on_success decorator' cursor = connection.cursor() cursor.execute('INSERT into transactions_regress_mod (fld) values (18)') raw_sql() transaction.rollback() self.assertEqual(Mod.objects.count(), 1) obj = Mod.objects.all()[0] self.assertEqual(obj.fld, 18)
'Make sure that under commit_manually, even "read-only" transaction require closure (commit or rollback), and a transaction left pending is treated as an error.'
def test_commit_manually_enforced(self):
@commit_manually def non_comitter(): 'Execute a managed transaction with read-only operations and fail to commit' _ = Mod.objects.count() self.assertRaises(TransactionManagementError, non_comitter)
'Test that under commit_manually, a committed transaction is accepted by the transaction management mechanisms'
def test_commit_manually_commit_ok(self):
@commit_manually def committer(): '\n Perform a database query, then commit the transaction\n ' _ = Mod.objects.count() transaction.commit() try: committer() except TransactionManagementError: self.fail('Commit did not clear the transaction state')
'Test that under commit_manually, a rolled-back transaction is accepted by the transaction management mechanisms'
def test_commit_manually_rollback_ok(self):
@commit_manually def roller_back(): '\n Perform a database query, then rollback the transaction\n ' _ = Mod.objects.count() transaction.rollback() try: roller_back() except TransactionManagementError: self.fail('Rollback did not clear the transaction state')
'Test that under commit_manually, if a transaction is committed and an operation is performed later, we still require the new transaction to be closed'
def test_commit_manually_enforced_after_commit(self):
@commit_manually def fake_committer(): 'Query, commit, then query again, leaving with a pending transaction' _ = Mod.objects.count() transaction.commit() _ = Mod.objects.count() self.assertRaises(TransactionManagementError, fake_committer)
'Make sure transaction closure is enforced even when the queries are performed through a single cursor reference retrieved in the beginning (this is to show why it is wrong to set the transaction dirty only when a cursor is fetched from the connection).'
@skipUnlessDBFeature('supports_transactions') def test_reuse_cursor_reference(self):
@commit_on_success def reuse_cursor_ref(): '\n Fetch a cursor, perform an query, rollback to close the transaction,\n then write a record (in a new transaction) using the same cursor object\n (reference). All this under commit_on_success, so the second insert should\n be committed.\n ' cursor = connection.cursor() cursor.execute('INSERT into transactions_regress_mod (fld) values (2)') transaction.rollback() cursor.execute('INSERT into transactions_regress_mod (fld) values (2)') reuse_cursor_ref() transaction.rollback() self.assertEqual(Mod.objects.count(), 1) obj = Mod.objects.all()[0] self.assertEqual(obj.fld, 2)
'Make sure that under commit_on_success, a transaction is rolled back even if the first database-modifying operation fails. This is prompted by http://code.djangoproject.com/ticket/6669 (and based on sample code posted there to exemplify the problem): Before Django 1.3, transactions were only marked "dirty" by the save() function after it successfully wrote the object to the database.'
def test_failing_query_transaction_closed(self):
from django.contrib.auth.models import User @transaction.commit_on_success def create_system_user(): 'Create a user in a transaction' user = User.objects.create_user(username='system', password='iamr00t', email='[email protected]') Mod.objects.create(fld=user.pk) create_system_user() with self.assertRaises(DatabaseError): create_system_user() User.objects.all()[0]
'Regression for #6669. Same test as above, with DEBUG=True.'
@override_settings(DEBUG=True) def test_failing_query_transaction_closed_debug(self):
self.test_failing_query_transaction_closed()
'Test for https://code.djangoproject.com/ticket/16818'
def test_manyrelated_add_commit(self):
a = M2mA.objects.create() b = M2mB.objects.create(fld=10) a.others.add(b) transaction.rollback() self.assertEqual(a.others.count(), 1)
'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 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(u'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.assertRaisesMessage(ImproperlyConfigured, u"NonExistingStorage isn't a storage module.", get_storage_class, u'NonExistingStorage')
'get_storage_class raises an error if the requested class don\'t exist.'
def test_get_nonexisting_storage_class(self):
self.assertRaisesMessage(ImproperlyConfigured, u'Storage module "django.core.files.storage" does not define a "NonExistingStorage" class.', get_storage_class, u'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):
six.assertRaisesRegex(self, ImproperlyConfigured, u'Error importing storage module django.core.files.non_existing_storage: "No module named .*non_existing_storage', get_storage_class, u'django.core.files.non_existing_storage.NonExistingStorage')
'Makes sure an exception is raised if the location is empty'
def test_emtpy_location(self):
storage = self.storage_class(location=u'') self.assertEqual(storage.base_location, u'') self.assertEqual(storage.location, upath(os.getcwd()))
'Standard file access options are available, and work as expected.'
def test_file_access_options(self):
self.assertFalse(self.storage.exists(u'storage_test')) f = self.storage.open(u'storage_test', u'w') f.write(u'storage contents') f.close() self.assertTrue(self.storage.exists(u'storage_test')) f = self.storage.open(u'storage_test', u'r') self.assertEqual(f.read(), u'storage contents') f.close() self.storage.delete(u'storage_test') self.assertFalse(self.storage.exists(u'storage_test'))
'File storage returns a Datetime object for the last accessed time of a file.'
def test_file_accessed_time(self):
self.assertFalse(self.storage.exists(u'test.file')) f = ContentFile(u'custom contents') f_name = self.storage.save(u'test.file', f) atime = self.storage.accessed_time(f_name) self.assertEqual(atime, datetime.fromtimestamp(os.path.getatime(self.storage.path(f_name)))) self.assertTrue(((datetime.now() - self.storage.accessed_time(f_name)) < timedelta(seconds=2))) self.storage.delete(f_name)
'File storage returns a Datetime object for the creation time of a file.'
def test_file_created_time(self):
self.assertFalse(self.storage.exists(u'test.file')) f = ContentFile(u'custom contents') f_name = self.storage.save(u'test.file', f) ctime = self.storage.created_time(f_name) self.assertEqual(ctime, datetime.fromtimestamp(os.path.getctime(self.storage.path(f_name)))) self.assertTrue(((datetime.now() - self.storage.created_time(f_name)) < timedelta(seconds=2))) self.storage.delete(f_name)
'File storage returns a Datetime object for the last modified time of a file.'
def test_file_modified_time(self):
self.assertFalse(self.storage.exists(u'test.file')) f = ContentFile(u'custom contents') f_name = self.storage.save(u'test.file', f) mtime = self.storage.modified_time(f_name) self.assertEqual(mtime, datetime.fromtimestamp(os.path.getmtime(self.storage.path(f_name)))) self.assertTrue(((datetime.now() - self.storage.modified_time(f_name)) < timedelta(seconds=2))) self.storage.delete(f_name)
'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(u'test.file')) f = ContentFile(u'custom contents') f.name = u'test.file' storage_f_name = self.storage.save(None, f) self.assertEqual(storage_f_name, f.name) self.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name))) self.storage.delete(storage_f_name)
'Saving a pathname should create intermediate directories as necessary.'
def test_file_save_with_path(self):
self.assertFalse(self.storage.exists(u'path/to')) self.storage.save(u'path/to/test.file', ContentFile(u'file saved with path')) self.assertTrue(self.storage.exists(u'path/to')) with self.storage.open(u'path/to/test.file') as f: self.assertEqual(f.read(), 'file saved with path') self.assertTrue(os.path.exists(os.path.join(self.temp_dir, u'path', u'to', u'test.file'))) self.storage.delete(u'path/to/test.file')
'File storage returns the full path of a file'
def test_file_path(self):
self.assertFalse(self.storage.exists(u'test.file')) f = ContentFile(u'custom contents') f_name = self.storage.save(u'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(u'test.file'), (u'%s%s' % (self.storage.base_url, u'test.file'))) self.assertEqual(self.storage.url(u"~!*()'@#$%^&*abc`+ =.file"), u"/test_media_url/~!*()'%40%23%24%25%5E%26*abc%60%2B%20%3D.file") self.assertEqual(self.storage.url(u'a/b\\c.file'), u'/test_media_url/a/b/c.file') self.storage.base_url = None self.assertRaises(ValueError, self.storage.url, u'test.file')
'File storage returns a tuple containing directories and files.'
def test_listdir(self):
self.assertFalse(self.storage.exists(u'storage_test_1')) self.assertFalse(self.storage.exists(u'storage_test_2')) self.assertFalse(self.storage.exists(u'storage_dir_1')) f = self.storage.save(u'storage_test_1', ContentFile(u'custom content')) f = self.storage.save(u'storage_test_2', ContentFile(u'custom content')) os.mkdir(os.path.join(self.temp_dir, u'storage_dir_1')) (dirs, files) = self.storage.listdir(u'') self.assertEqual(set(dirs), set([u'storage_dir_1'])) self.assertEqual(set(files), set([u'storage_test_1', u'storage_test_2'])) self.storage.delete(u'storage_test_1') self.storage.delete(u'storage_test_2') os.rmdir(os.path.join(self.temp_dir, u'storage_dir_1'))
'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, u'..') self.assertRaises(SuspiciousOperation, self.storage.exists, u'/etc/passwd')
'The storage backend should preserve case of filenames.'
def test_file_storage_preserves_filename_case(self):
temp_storage = self.storage_class(location=self.temp_dir2) mixed_case = u'CaSe_SeNsItIvE' file = temp_storage.open(mixed_case, u'w') file.write(u'storage contents') file.close() self.assertEqual(os.path.join(self.temp_dir2, mixed_case), temp_storage.path(mixed_case)) temp_storage.delete(mixed_case)
'File storage should be robust against directory creation race conditions.'
def test_makedirs_race_handling(self):
real_makedirs = os.makedirs def fake_makedirs(path): if (path == os.path.join(self.temp_dir, u'normal')): real_makedirs(path) elif (path == os.path.join(self.temp_dir, u'raced')): real_makedirs(path) raise OSError(errno.EEXIST, u'simulated EEXIST') elif (path == os.path.join(self.temp_dir, u'error')): raise OSError(errno.EACCES, u'simulated EACCES') else: self.fail((u'unexpected argument %r' % path)) try: os.makedirs = fake_makedirs self.storage.save(u'normal/test.file', ContentFile(u'saved normally')) with self.storage.open(u'normal/test.file') as f: self.assertEqual(f.read(), 'saved normally') self.storage.save(u'raced/test.file', ContentFile(u'saved with race')) with self.storage.open(u'raced/test.file') as f: self.assertEqual(f.read(), 'saved with race') self.assertRaises(OSError, self.storage.save, u'error/test.file', ContentFile(u'not saved')) finally: os.makedirs = real_makedirs
'File storage should be robust against file removal race conditions.'
def test_remove_race_handling(self):
real_remove = os.remove def fake_remove(path): if (path == os.path.join(self.temp_dir, u'normal.file')): real_remove(path) elif (path == os.path.join(self.temp_dir, u'raced.file')): real_remove(path) raise OSError(errno.ENOENT, u'simulated ENOENT') elif (path == os.path.join(self.temp_dir, u'error.file')): raise OSError(errno.EACCES, u'simulated EACCES') else: self.fail((u'unexpected argument %r' % path)) try: os.remove = fake_remove self.storage.save(u'normal.file', ContentFile(u'delete normally')) self.storage.delete(u'normal.file') self.assertFalse(self.storage.exists(u'normal.file')) self.storage.save(u'raced.file', ContentFile(u'delete with race')) self.storage.delete(u'raced.file') self.assertFalse(self.storage.exists(u'normal.file')) self.storage.save(u'error.file', ContentFile(u'delete with error')) self.assertRaises(OSError, self.storage.delete, u'error.file') finally: os.remove = real_remove
'Test behaviour when file.chunks() is raising an error'
def test_file_chunks_error(self):
f1 = ContentFile(u'chunks fails') def failing_chunks(): raise IOError f1.chunks = failing_chunks with self.assertRaises(IOError): self.storage.save(u'error.file', f1)
'Append numbers to duplicate files rather than underscores, like Trac.'
def get_available_name(self, name):
parts = name.split(u'.') (basename, ext) = (parts[0], parts[1:]) number = 2 while self.exists(name): name = u'.'.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=u'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(u'dotted.path/test', ContentFile(u'1')) self.storage.save(u'dotted.path/test', ContentFile(u'2')) self.assertFalse(os.path.exists(os.path.join(self.storage_dir, u'dotted_.path'))) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, u'dotted.path/test'))) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, u'dotted.path/test_1')))
'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(u'dotted.path/.test', ContentFile(u'1')) self.storage.save(u'dotted.path/.test', ContentFile(u'2')) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, u'dotted.path/.test'))) self.assertTrue(os.path.exists(os.path.join(self.storage_dir, u'dotted.path/.test_1')))
'Open files passed into get_image_dimensions() should stay opened.'
@unittest.skipUnless(Image, u'PIL not installed') def test_not_closing_of_files(self):
empty_io = BytesIO() 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, u'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 FileWrapper(open(*args)) from django.core.files import images images.open = catching_open try: get_image_dimensions(os.path.join(os.path.dirname(upath(__file__)), u'test1.png')) finally: del images.open self.assertTrue(FileWrapper._closed)
'Multiple calls of get_image_dimensions() should return the same size.'
@unittest.skipUnless(Image, u'PIL not installed') def test_multiple_calls(self):
from django.core.files.images import ImageFile img_path = os.path.join(os.path.dirname(upath(__file__)), u'test.png') image = ImageFile(open(img_path, u'rb')) image_pil = Image.open(img_path) (size_1, size_2) = (get_image_dimensions(image), get_image_dimensions(image)) self.assertEqual(image_pil.size, size_1) self.assertEqual(size_1, size_2)
'Test that the constructor of ContentFile accepts \'name\' (#16590).'
def test_content_file_custom_name(self):
name = u'I can have a name too!' self.assertEqual(ContentFile('content', name=name).name, name)
'Test that ContentFile can accept both bytes and unicode and that the retrieved content is of the same type.'
def test_content_file_input_type(self):
self.assertTrue(isinstance(ContentFile('content').read(), bytes)) if six.PY3: self.assertTrue(isinstance(ContentFile(u'espa\xf1ol').read(), six.text_type)) else: self.assertTrue(isinstance(ContentFile(u'espa\xf1ol').read(), bytes))
'Test that ContentFile can be saved correctly with the filesystem storage, both if it was initialized with string or unicode content'
def test_content_saving(self):
self.storage.save(u'bytes.txt', ContentFile('content')) self.storage.save(u'unicode.txt', ContentFile(u'espa\xf1ol'))
'Test the File storage API with a file like object coming from urllib2.urlopen()'
def test_urllib2_urlopen(self):
file_like_object = self.urlopen(u'/example_view/') f = File(file_like_object) stored_filename = self.storage.save(u'remote_file.html', f) stored_file = self.storage.open(stored_filename) remote_file = self.urlopen(u'/example_view/') self.assertEqual(stored_file.read(), remote_file.read())
'Any filter must define a title.'
def test_listfilter_without_title(self):
modeladmin = DecadeFilterBookAdminWithoutTitle(Book, site) request = self.request_factory.get(u'/', {}) six.assertRaisesRegex(self, ImproperlyConfigured, u"The list filter 'DecadeListFilterWithoutTitle' does not specify a 'title'.", self.get_changelist, request, Book, modeladmin)
'Any SimpleListFilter must define a parameter_name.'
def test_simplelistfilter_without_parameter(self):
modeladmin = DecadeFilterBookAdminWithoutParameter(Book, site) request = self.request_factory.get(u'/', {}) six.assertRaisesRegex(self, ImproperlyConfigured, u"The list filter 'DecadeListFilterWithoutParameter' does not specify a 'parameter_name'.", self.get_changelist, request, Book, modeladmin)
'A SimpleListFilter lookups method can return None but disables the filter completely.'
def test_simplelistfilter_with_none_returning_lookups(self):
modeladmin = DecadeFilterBookAdminWithNoneReturningLookups(Book, site) request = self.request_factory.get(u'/', {}) changelist = self.get_changelist(request, Book, modeladmin) filterspec = changelist.get_filters(request)[0] self.assertEqual(len(filterspec), 0)
'Ensure that when a filter\'s queryset method fails, it fails loudly and the corresponding exception doesn\'t get swallowed. Refs #17828.'
def test_filter_with_failing_queryset(self):
modeladmin = DecadeFilterBookAdminWithFailingQueryset(Book, site) request = self.request_factory.get(u'/', {}) self.assertRaises(ZeroDivisionError, self.get_changelist, request, Book, modeladmin)
'Ensure that list_filter works with two-characters long field names. Refs #16080.'
def test_two_characters_long_field(self):
modeladmin = BookAdmin(Book, site) request = self.request_factory.get(u'/', {u'no': u'207'}) changelist = self.get_changelist(request, Book, modeladmin) queryset = changelist.get_query_set(request) self.assertEqual(list(queryset), [self.bio_book]) filterspec = changelist.get_filters(request)[0][(-1)] self.assertEqual(force_text(filterspec.title), u'number') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[2][u'selected'], True) self.assertEqual(choices[2][u'query_string'], u'?no=207')
'Ensure that a SimpleListFilter\'s parameter name is not mistaken for a model field if it ends with \'__isnull\' or \'__in\'. Refs #17091.'
def test_parameter_ends_with__in__or__isnull(self):
modeladmin = DecadeFilterBookAdminParameterEndsWith__In(Book, site) request = self.request_factory.get(u'/', {u'decade__in': u'the 90s'}) changelist = self.get_changelist(request, Book, modeladmin) queryset = changelist.get_query_set(request) self.assertEqual(list(queryset), [self.bio_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_text(filterspec.title), u'publication decade') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[2][u'display'], u"the 1990's") self.assertEqual(choices[2][u'selected'], True) self.assertEqual(choices[2][u'query_string'], u'?decade__in=the+90s') modeladmin = DecadeFilterBookAdminParameterEndsWith__Isnull(Book, site) request = self.request_factory.get(u'/', {u'decade__isnull': u'the 90s'}) changelist = self.get_changelist(request, Book, modeladmin) queryset = changelist.get_query_set(request) self.assertEqual(list(queryset), [self.bio_book]) filterspec = changelist.get_filters(request)[0][0] self.assertEqual(force_text(filterspec.title), u'publication decade') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[2][u'display'], u"the 1990's") self.assertEqual(choices[2][u'selected'], True) self.assertEqual(choices[2][u'query_string'], u'?decade__isnull=the+90s')
'Ensure choices are set the selected class when using non-string values for lookups in SimpleListFilters. Refs #19318'
def test_lookup_with_non_string_value(self):
modeladmin = DepartmentFilterEmployeeAdmin(Employee, site) request = self.request_factory.get(u'/', {u'department': self.john.pk}) changelist = self.get_changelist(request, Employee, modeladmin) queryset = changelist.get_query_set(request) self.assertEqual(list(queryset), [self.john]) filterspec = changelist.get_filters(request)[0][(-1)] self.assertEqual(force_text(filterspec.title), u'department') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[1][u'display'], u'DEV') self.assertEqual(choices[1][u'selected'], True) self.assertEqual(choices[1][u'query_string'], (u'?department=%s' % self.john.pk))
'Ensure that a filter on a FK respects the FK\'s to_field attribute. Refs #17972.'
def test_fk_with_to_field(self):
modeladmin = EmployeeAdmin(Employee, site) request = self.request_factory.get(u'/', {}) changelist = self.get_changelist(request, Employee, modeladmin) queryset = changelist.get_query_set(request) self.assertEqual(list(queryset), [self.jack, self.john]) filterspec = changelist.get_filters(request)[0][(-1)] self.assertEqual(force_text(filterspec.title), u'department') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[0][u'display'], u'All') self.assertEqual(choices[0][u'selected'], True) self.assertEqual(choices[0][u'query_string'], u'?') self.assertEqual(choices[1][u'display'], u'Development') self.assertEqual(choices[1][u'selected'], False) self.assertEqual(choices[1][u'query_string'], u'?department__code__exact=DEV') self.assertEqual(choices[2][u'display'], u'Design') self.assertEqual(choices[2][u'selected'], False) self.assertEqual(choices[2][u'query_string'], u'?department__code__exact=DSN') request = self.request_factory.get(u'/', {u'department__code__exact': u'DEV'}) changelist = self.get_changelist(request, Employee, modeladmin) queryset = changelist.get_query_set(request) self.assertEqual(list(queryset), [self.john]) filterspec = changelist.get_filters(request)[0][(-1)] self.assertEqual(force_text(filterspec.title), u'department') choices = list(filterspec.choices(changelist)) self.assertEqual(choices[0][u'display'], u'All') self.assertEqual(choices[0][u'selected'], False) self.assertEqual(choices[0][u'query_string'], u'?') self.assertEqual(choices[1][u'display'], u'Development') self.assertEqual(choices[1][u'selected'], True) self.assertEqual(choices[1][u'query_string'], u'?department__code__exact=DEV') self.assertEqual(choices[2][u'display'], u'Design') self.assertEqual(choices[2][u'selected'], False) self.assertEqual(choices[2][u'query_string'], u'?department__code__exact=DSN')
'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 for #18432: Chained foreign keys with to_field produce incorrect query'
def test_chained_fks(self):
m1 = Model1.objects.create(pkey=1000) m2 = Model2.objects.create(model1=m1) m3 = Model3.objects.create(model2=m2) m3 = Model3.objects.get(model2=1000) m3.model2
'Ensures that you can filter by objects that have an \'evaluate\' attr'
def test_model_with_evaluate_method(self):
dept = Department.objects.create(pk=1, name=u'abc') dept.evaluate = u'abc' Worker.objects.filter(department=dept)
'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) request = self.factory.get('/child/') 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_max_show_all, 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 = self.factory.get('/child/') m = ChildAdmin(Child, admin.site) list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) cl = ChangeList(request, Child, list_display, list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_max_show_all, m.list_editable, m) cl.formset = None template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl}) table_output = template.render(context) link = reverse('admin:admin_changelist_child_change', args=(new_child.id,)) row_html = ('<tbody><tr class="row1"><th><a href="%s">name</a></th><td class="nowrap">(None)</td></tr></tbody>' % link) self.assertFalse((table_output.find(row_html) == (-1)), ('Failed to find expected row element: %s' % table_output))
'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 = self.factory.get('/child/') m = ChildAdmin(Child, admin.site) list_display = m.get_list_display(request) list_display_links = m.get_list_display_links(request, list_display) cl = ChangeList(request, Child, list_display, list_display_links, m.list_filter, m.date_hierarchy, m.search_fields, m.list_select_related, m.list_per_page, m.list_max_show_all, m.list_editable, m) cl.formset = None template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl}) table_output = template.render(context) link = reverse('admin:admin_changelist_child_change', args=(new_child.id,)) row_html = ('<tbody><tr class="row1"><th><a href="%s">name</a></th><td class="nowrap">Parent object</td></tr></tbody>' % link) self.assertFalse((table_output.find(row_html) == (-1)), ('Failed to find expected row element: %s' % table_output))
'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 = self.factory.get('/child/') m = ChildAdmin(Child, admin.site) m.list_display = ['id', 'name', 'parent'] m.list_display_links = ['id'] m.list_editable = ['name'] 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_max_show_all, m.list_editable, m) FormSet = m.get_changelist_formset(request) cl.formset = FormSet(queryset=cl.result_list) template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl}) table_output = template.render(context) hiddenfields_div = ('<div class="hiddenfields"><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></div>' % new_child.id) self.assertInHTML(hiddenfields_div, table_output, msg_prefix='Failed to find hidden fields') editable_name_field = '<input name="form-0-name" value="name" class="vTextField" maxlength="30" type="text" id="id_form-0-name" />' self.assertInHTML(('<td>%s</td>' % editable_name_field), table_output, msg_prefix='Failed to find "name" list_editable field')
'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 = self.factory.get('/child/', data={'p': (-1)}) m = ChildAdmin(Child, admin.site) m.list_display = ['id', 'name', 'parent'] m.list_display_links = ['id'] m.list_editable = ['name'] self.assertRaises(IncorrectLookupParameters, (lambda : 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_max_show_all, m.list_editable, m)))
'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 = self.factory.get('/band/', data={'genres': blues.pk}) cl = ChangeList(request, Band, 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_max_show_all, m.list_editable, m) cl.get_results(request) self.assertEqual(cl.result_count, 1)
'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 = self.factory.get('/group/', data={'members': lead.pk}) cl = ChangeList(request, Group, 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_max_show_all, m.list_editable, m) cl.get_results(request) self.assertEqual(cl.result_count, 1)
'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 = self.factory.get('/quartet/', data={'members': lead.pk}) cl = ChangeList(request, Quartet, 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_max_show_all, m.list_editable, m) cl.get_results(request) self.assertEqual(cl.result_count, 1)
'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.site) request = self.factory.get('/chordsband/', data={'members': lead.pk}) cl = ChangeList(request, ChordsBand, 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_max_show_all, m.list_editable, m) cl.get_results(request) self.assertEqual(cl.result_count, 1)