desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Point all operations on auth models to \'other\''
def db_for_write(self, model, **hints):
if (model._meta.app_label == 'auth'): return 'other' return None
'Allow any relation if a model in Auth is involved'
def allow_relation(self, obj1, obj2, **hints):
if ((obj1._meta.app_label == 'auth') or (obj2._meta.app_label == 'auth')): return True return None
'Make sure the auth app only appears on the \'other\' db'
def allow_syncdb(self, db, model):
if (db == 'other'): return (model._meta.app_label == 'auth') elif (model._meta.app_label == 'auth'): return False return None
'Check that querysets obey the router for db suggestions'
def test_db_selection(self):
self.assertEqual(Book.objects.db, 'other') self.assertEqual(Book.objects.all().db, 'other') self.assertEqual(Book.objects.using('default').db, 'default') self.assertEqual(Book.objects.db_manager('default').db, 'default') self.assertEqual(Book.objects.db_manager('default').all().db, 'default')
'Synchronization behaviour is predicatable'
def test_syncdb_selection(self):
self.assertTrue(router.allow_syncdb('default', User)) self.assertTrue(router.allow_syncdb('default', Book)) self.assertTrue(router.allow_syncdb('other', User)) self.assertTrue(router.allow_syncdb('other', Book)) router.routers = [TestRouter(), AuthRouter()] self.assertTrue(router.allow_syncdb('d...
'A router can choose to implement a subset of methods'
def test_partial_router(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) self.assertEqual(router.db_for_read(User), 'other') self.assertEqual(router.db_for_read(Book), 'other') self.assertEqual(router.db_for_write(User), 'default') self.assertEqual(router.db_for...
'Foreign keys can cross databases if they two databases have a common source'
def test_foreign_key_cross_database_protection(self):
pro = Book.objects.using('default').create(title='Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.using('default').create(name='Marty Alchin') dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.obj...
'M2M relations can cross databases if the database share a source'
def test_m2m_cross_database_protection(self):
pro = Book.objects.using('other').create(pk=1, title='Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.using('other').create(pk=1, name='Marty Alchin') dive = Book.objects.using('default').create(pk=2, title='Dive into Python', published=datetime.date(2009, 5, 4)) m...
'Operations that involve sharing FK objects across databases raise an error'
def test_o2o_cross_database_protection(self):
alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com') bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com') alice_profile = UserProfile.objects.create(user=alice, flavor='chocolate') try: bob.userprofile = alice_profile except ValueError:...
'Generic Key operations can span databases if they share a source'
def test_generic_key_cross_database_protection(self):
pro = Book.objects.using('default').create(title='Pro Django', published=datetime.date(2008, 12, 16)) review1 = Review.objects.using('default').create(source='Python Monthly', content_object=pro) dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5,...
'M2M relations are represented by managers, and can be controlled like managers'
def test_m2m_managers(self):
pro = Book.objects.using('other').create(pk=1, title='Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.using('other').create(pk=1, name='Marty Alchin') pro.authors = [marty] self.assertEqual(pro.authors.db, 'other') self.assertEqual(pro.authors.db_manager('default').d...
'FK reverse relations are represented by managers, and can be controlled like managers'
def test_foreign_key_managers(self):
marty = Person.objects.using('other').create(pk=1, name='Marty Alchin') pro = Book.objects.using('other').create(pk=1, title='Pro Django', published=datetime.date(2008, 12, 16), editor=marty) self.assertEqual(marty.edited.db, 'other') self.assertEqual(marty.edited.db_manager('default').db, 'defaul...
'Generic key relations are represented by managers, and can be controlled like managers'
def test_generic_key_managers(self):
pro = Book.objects.using('other').create(title='Pro Django', published=datetime.date(2008, 12, 16)) review1 = Review.objects.using('other').create(source='Python Monthly', content_object=pro) self.assertEqual(pro.reviews.db, 'other') self.assertEqual(pro.reviews.db_manager('default').db, 'default'...
'Make sure as_sql works with subqueries and master/slave.'
def test_subquery(self):
mark = Person.objects.using('other').create(name='Mark Pilgrim') dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4), editor=mark) sub = Person.objects.filter(name='Mark Pilgrim') qs = Book.objects.filter(editor__in=sub) str(qs.query) ...
'The methods on the auth manager obey database hints'
def test_auth_manager(self):
User.objects.create_user('alice', 'alice@example.com') User.objects.db_manager('default').create_user('bob', 'bob@example.com') alice = User.objects.using('other').get(username='alice') self.assertEqual(alice.username, 'alice') self.assertEqual(alice._state.db, 'other') self.assertRaises(User.Do...
'Check that dumpdata honors allow_syncdb restrictions on the router'
def test_dumpdata(self):
User.objects.create_user('alice', 'alice@example.com') User.objects.db_manager('default').create_user('bob', 'bob@example.com') new_io = StringIO() management.call_command('dumpdata', 'auth', format='json', database='default', stdout=new_io) command_output = new_io.getvalue().strip() self.assert...
'Make sure the auth app only appears on the \'other\' db'
def allow_syncdb(self, db, model):
if (db == 'other'): return (model._meta.object_name == 'Pet') else: return (model._meta.object_name != 'Pet') return None
'Multi-db fixtures are loaded correctly'
def test_fixture_loading(self):
try: Book.objects.get(title='Pro Django') Book.objects.using('default').get(title='Pro Django') except Book.DoesNotExist: self.fail('"Pro Django" should exist on default database') self.assertRaises(Book.DoesNotExist, Book.objects.using('other').get, title='Pr...
'A fixture can contain entries, but lead to nothing in the database; this shouldn\'t raise an error (ref #14068)'
def test_pseudo_empty_fixtures(self):
new_io = StringIO() management.call_command('loaddata', 'pets', stdout=new_io, stderr=new_io) command_output = new_io.getvalue().strip() self.assertEqual(command_output, 'Installed 0 object(s) (of 2) from 1 fixture(s)')
'Sends all writes to \'other\'.'
def _write_to_other(self):
router.routers = [WriteToOtherRouter()]
'Sends all writes to the default DB'
def _write_to_default(self):
router.routers = self.old_routers
'Tests that the pre/post_save signal contains the correct database. (#13552)'
def test_database_arg_save_and_delete(self):
pre_save_receiver = DatabaseReceiver() post_save_receiver = DatabaseReceiver() pre_delete_receiver = DatabaseReceiver() post_delete_receiver = DatabaseReceiver() signals.pre_save.connect(sender=Person, receiver=pre_save_receiver) signals.post_save.connect(sender=Person, receiver=post_save_receiv...
'Test that the m2m_changed signal has a correct database arg (#13552)'
def test_database_arg_m2m(self):
receiver = DatabaseReceiver() signals.m2m_changed.connect(receiver=receiver) b = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) p = Person.objects.create(name='Marty Alchin') b.authors.add(p) self.assertEqual(receiver._database, DEFAULT_DB_ALIAS) self._w...
'Check that the AttributeError from AttributeErrorRouter bubbles up'
def test_attribute_error_read(self):
router.routers = [] b = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) router.routers = [AttributeErrorRouter()] self.assertRaises(AttributeError, Book.objects.get, pk=b.pk)
'Check that the AttributeError from AttributeErrorRouter bubbles up'
def test_attribute_error_save(self):
dive = Book() dive.title = 'Dive into Python' dive.published = datetime.date(2009, 5, 4) self.assertRaises(AttributeError, dive.save)
'Check that the AttributeError from AttributeErrorRouter bubbles up'
def test_attribute_error_delete(self):
router.routers = [] b = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) p = Person.objects.create(name='Marty Alchin') b.authors = [p] b.editor = p router.routers = [AttributeErrorRouter()] self.assertRaises(AttributeError, b.delete)
'Check that the AttributeError from AttributeErrorRouter bubbles up'
def test_attribute_error_m2m(self):
router.routers = [] b = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) p = Person.objects.create(name='Marty Alchin') router.routers = [AttributeErrorRouter()] self.assertRaises(AttributeError, setattr, b, 'authors', [p])
'Regression test for #9023: accessing the reverse relationship shouldn\'t result in a cascading delete().'
def test_reverse_relationship_cache_cascade(self):
bar = UndergroundBar.objects.create(place=self.p1, serves_cocktails=False) self.p1.undergroundbar bar.place.name = 'foo' bar.place = None bar.save() self.p1.delete() self.assertEqual(Place.objects.all().count(), 0) self.assertEqual(UndergroundBar.objects.all().count(), 1)
'Regression test for #1064 and #1506 Check that we create models via the m2m relation if the remote model has a OneToOneField.'
def test_create_models_m2m(self):
f = Favorites(name='Fred') f.save() f.restaurants = [self.r1] self.assertQuerysetEqual(f.restaurants.all(), ['<Restaurant: Demon Dogs the restaurant>'])
'Regression test for #7173 Check that the name of the cache for the reverse object is correct.'
def test_reverse_object_cache(self):
self.assertEqual(self.p1.restaurant, self.r1) self.assertEqual(self.p1.bar, self.b1)
'Regression test for #6886 (the related-object cache)'
def test_related_object_cache(self):
p = Place.objects.get(name='Demon Dogs') r = p.restaurant self.assertTrue((p.restaurant is r)) del p._restaurant_cache self.assertFalse((p.restaurant is r)) r2 = Restaurant.objects.get(pk=r.pk) p.restaurant = r2 self.assertTrue((p.restaurant is r2)) ug_bar = UndergroundBar.objects...
'Regression test for #9968 filtering reverse one-to-one relations with primary_key=True was misbehaving. We test both (primary_key=True & False) cases here to prevent any reappearance of the problem.'
def test_filter_one_to_one_relations(self):
t = Target.objects.create() self.assertQuerysetEqual(Target.objects.filter(pointer=None), ['<Target: Target object>']) self.assertQuerysetEqual(Target.objects.exclude(pointer=None), []) self.assertQuerysetEqual(Target.objects.filter(pointer2=None), ['<Target: Target object>']) self.asser...
'Regression test for #12654: lookup_field'
def test_values_from_lookup_field(self):
SITE_NAME = 'example.com' TITLE_TEXT = 'Some title' CREATED_DATE = datetime.min ADMIN_METHOD = 'admin method' SIMPLE_FUNCTION = 'function' INSTANCE_ATTRIBUTE = 'attr' class MockModelAdmin(object, ): def get_admin_value(self, obj): return ADMIN_METHOD simple_func...
'Regression test for #12550: display_for_field should handle None value.'
def test_null_display_for_field(self):
display_value = display_for_field(None, models.CharField()) self.assertEqual(display_value, EMPTY_CHANGELIST_VALUE) display_value = display_for_field(None, models.CharField(choices=((None, 'test_none'),))) self.assertEqual(display_value, 'test_none') display_value = display_for_field(None, models.Da...
'Tests for label_for_field'
def test_label_for_field(self):
self.assertEqual(label_for_field('title', Article), 'title') self.assertEqual(label_for_field('title2', Article), 'another name') self.assertEqual(label_for_field('title2', Article, return_attr=True), ('another name', None)) self.assertEqual(label_for_field('__unicode__', Article), 'article') ...
'Regression test for #13963'
def test_related_name(self):
self.assertEqual(label_for_field('location', Event, return_attr=True), ('location', None)) self.assertEqual(label_for_field('event', Location, return_attr=True), ('awesome event', None)) self.assertEqual(label_for_field('guest', Event, return_attr=True), ('awesome guest', None))
'Make sure that an add form that is filled out, but marked for deletion doesn\'t cause validation errors.'
def test_add_form_deletion_when_invalid(self):
PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True) poet = Poet.objects.create(name='test') data = {'poem_set-TOTAL_FORMS': u'1', 'poem_set-INITIAL_FORMS': u'0', 'poem_set-MAX_NUM_FORMS': u'0', 'poem_set-0-id': u'', 'poem_set-0-poem': u'1', 'poem_set-0-name': (u'x' * 1000)} formset = PoemFo...
'Make sure that a change form that is filled out, but marked for deletion doesn\'t cause validation errors.'
def test_change_form_deletion_when_invalid(self):
PoemFormSet = inlineformset_factory(Poet, Poem, can_delete=True) poet = Poet.objects.create(name='test') poem = poet.poem_set.create(name='test poem') data = {'poem_set-TOTAL_FORMS': u'1', 'poem_set-INITIAL_FORMS': u'1', 'poem_set-MAX_NUM_FORMS': u'0', 'poem_set-0-id': unicode(poem.id), 'poem_set-0-p...
'Make sure inlineformsets respect commit=False regression for #10750'
def test_save_new(self):
ChildFormSet = inlineformset_factory(School, Child, exclude=['father', 'mother']) school = School.objects.create(name=u'test') mother = Parent.objects.create(name=u'mother') father = Parent.objects.create(name=u'father') data = {'child_set-TOTAL_FORMS': u'1', 'child_set-INITIAL_FORMS': u'0', 'child_...
'These should both work without a problem.'
def test_inline_formset_factory(self):
inlineformset_factory(Parent, Child, fk_name='mother') inlineformset_factory(Parent, Child, fk_name='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):
self.assertRaisesRegexp(Exception, "<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, "fk_name 'school' is not a ForeignKey to <class 'regressiontests.inline_formsets.models.Parent'>", inlineformset_factory, Parent, Child, fk_name='school')
'If the field specified in fk_name is not a ForeignKey, we should get an exception.'
def test_non_foreign_key_field(self):
self.assertRaisesRegexp(Exception, "<class 'regressiontests.inline_formsets.models.Child'> has no field named 'test'", inlineformset_factory, Parent, Child, fk_name='test')
'Dummy cache backend ignores cache set calls'
def test_simple(self):
self.cache.set('key', 'value') self.assertEqual(self.cache.get('key'), None)
'Add doesn\'t do anything in dummy cache backend'
def test_add(self):
self.cache.add('addkey1', 'value') result = self.cache.add('addkey1', 'newvalue') self.assertEqual(result, True) self.assertEqual(self.cache.get('addkey1'), None)
'Non-existent keys aren\'t found in the dummy cache backend'
def test_non_existent(self):
self.assertEqual(self.cache.get('does_not_exist'), None) self.assertEqual(self.cache.get('does_not_exist', 'bang!'), 'bang!')
'get_many returns nothing for the dummy cache backend'
def test_get_many(self):
self.cache.set('a', 'a') self.cache.set('b', 'b') self.cache.set('c', 'c') self.cache.set('d', 'd') self.assertEqual(self.cache.get_many(['a', 'c', 'd']), {}) self.assertEqual(self.cache.get_many(['a', 'b', 'e']), {})
'Cache deletion is transparently ignored on the dummy cache backend'
def test_delete(self):
self.cache.set('key1', 'spam') self.cache.set('key2', 'eggs') self.assertEqual(self.cache.get('key1'), None) self.cache.delete('key1') self.assertEqual(self.cache.get('key1'), None) self.assertEqual(self.cache.get('key2'), None)
'The has_key method doesn\'t ever return True for the dummy cache backend'
def test_has_key(self):
self.cache.set('hello1', 'goodbye1') self.assertEqual(self.cache.has_key('hello1'), False) self.assertEqual(self.cache.has_key('goodbye1'), False)
'The in operator doesn\'t ever return True for the dummy cache backend'
def test_in(self):
self.cache.set('hello2', 'goodbye2') self.assertEqual(('hello2' in self.cache), False) self.assertEqual(('goodbye2' in self.cache), False)
'Dummy cache values can\'t be incremented'
def test_incr(self):
self.cache.set('answer', 42) self.assertRaises(ValueError, self.cache.incr, 'answer') self.assertRaises(ValueError, self.cache.incr, 'does_not_exist')
'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()
'Dummy cache versions can\'t be incremented'
def test_incr_version(self):
self.cache.set('answer', 42) self.assertRaises(ValueError, self.cache.incr_version, 'answer') self.assertRaises(ValueError, self.cache.incr_version, 'does_not_exist')
'Dummy cache versions can\'t be decremented'
def test_decr_version(self):
self.cache.set('answer', 42) self.assertRaises(ValueError, self.cache.decr_version, 'answer') self.assertRaises(ValueError, self.cache.decr_version, '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('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):
def func(key, *args): return key old_func = self.cache.key_func self.cache.key_func = func _warnings_state = get_warnings_state() warnings.simplefilter('error', CacheKeyWarning) try: self.assertRaises(CacheKeyWarning, self.cache.set, 'key with spaces', 'value') self...
'Check that multiple locmem caches are isolated'
def test_multiple_caches(self):
mirror_cache = get_cache('django.core.cache.backends.locmem.LocMemCache') other_cache = get_cache('django.core.cache.backends.locmem.LocMemCache', LOCATION='other') self.cache.set('value1', 42) self.assertEqual(mirror_cache.get('value1'), 42) self.assertEqual(other_cache.get('value1'), None)
'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, 'key with spaces', 'value') self.assertRaises(Exception, self.cache.set, ('a' * 251), 'value')
'Test that keys are hashed into subdirectories correctly'
def test_hashing(self):
self.cache.set('foo', 'bar') key = self.cache.make_key('foo') keyhash = md5_constructor(key).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('foo', 'bar') key = self.cache.make_key('foo') keyhash = md5_constructor(key).hexdigest() keypath = os.path.join(self.dirname, keyhash[:2], keyhash[2:4], keyhash[4:]) self.assertTrue(os.path.exists(keypath)) self.cache.delete('foo') self.assertTrue((not os.path.exists(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, 'middlewareprefix') self.assertEqual(middleware.cache_alias, 'other') self.assertEqual(middleware.cache_anonymous_only, False) as_view_decorator = CacheMiddleware(cache_alias=Non...
'The cache middleware shouldn\'t cause a session access due to CACHE_MIDDLEWARE_ANONYMOUS_ONLY if nothing else has accessed the session. Refs 13283'
def test_cache_middleware_anonymous_only_wont_cause_session_access(self):
settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.auth.middleware import AuthenticationMiddleware middleware = CacheMiddleware() session_middleware = SessionMiddleware() auth_middleware = AuthenticationMiddleware(...
'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.'
def test_cache_middleware_anonymous_only_with_cache_page(self):
settings.CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True request = self.factory.get('/view_anon/') class MockAuthenticatedUser(object, ): def is_authenticated(self): return True class MockAccessedSession(object, ): accessed = True request.user = MockAuthenticatedUser() request...
'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)...
'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 (id,fld) values (17,18)') raw_sql() transaction.rollbac...
'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() ...
'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_ba...
'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...
'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...
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='root@SITENAME.com') Mod.objects.create(fld=user.id) c...
'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.assertRaisesRegexp(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.assertTrue(self.storage.exists('storage_test')) f = self.storage.open('storage_test', 'r') self.assertEqual(f.read(), 'storage contents') f.cl...
'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('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('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.n...
'File storage returns a Datetime object for the creation time of a file.'
def test_file_created_time(self):
self.assertFalse(self.storage.exists('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('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.no...
'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('test.file')) f = ContentFile('custom contents') f_name = self.storage.save('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.n...
'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.assertTrue(os.path.exists(os.path.join(self.temp_dir, f.name))) self.storage.delete(storage_...
'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...