desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Regression test for #8039: Ordering sometimes removed relevant tables from extra(). This test is the critical case: ordering uses a table, but then removes the reference because of an optimisation. The table should still be present because of the extra() call.'
def test_regression_8039(self):
self.assertQuerysetEqual(Order.objects.extra(where=['username=%s'], params=['fred'], tables=['auth_user']).order_by('created_by'), [])
'Regression test for #8819: Fields in the extra(select=...) list should be available to extra(order_by=...).'
def test_regression_8819(self):
self.assertQuerysetEqual(User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}).distinct(), ['<User: fred>']) self.assertQuerysetEqual(User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}, order_by=['extra_field']), ['<User: fred>']) self.assertQuerysetEqual(User.objects.filte...
'When calling the dates() method on a queryset with extra selection columns, we can (and should) ignore those columns. They don\'t change the result and cause incorrect SQL to be produced otherwise.'
def test_dates_query(self):
rm = RevisionableModel.objects.create(title='First Revision', when=datetime.datetime(2008, 9, 28, 10, 30, 0)) self.assertQuerysetEqual(RevisionableModel.objects.extra(select={'the_answer': 'id'}).dates('when', 'month'), ['datetime.datetime(2008, 9, 1, 0, 0)'])
'Regression test for #10256... If there is a values() clause, Extra columns are only returned if they are explicitly mentioned.'
def test_values_with_extra(self):
obj = TestObject(first='first', second='second', third='third') obj.save() self.assertEqual(list(TestObject.objects.extra(select=SortedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values()), [{'bar': u'second', 'third': u'third', 'second': u'second', 'whiz': u'third', 'foo': u'first', 'id...
'Regression for #10847: the list of extra columns can always be accurately evaluated. Using an inner query ensures that as_sql() is producing correct output without requiring full evaluation and execution of the inner query.'
def test_regression_10847(self):
obj = TestObject(first='first', second='second', third='third') obj.save() self.assertEqual(list(TestObject.objects.extra(select={'extra': 1}).values('pk')), [{'pk': obj.pk}]) self.assertQuerysetEqual(TestObject.objects.filter(pk__in=TestObject.objects.extra(select={'extra': 1}).values('pk')), ['<TestOb...
'This is a regression test for ticket #3790.'
def test_duplicate_pk(self):
management.call_command('loaddata', 'sequence', verbosity=0, commit=False) animal = Animal(name='Platypus', latin_name='Ornithorhynchus anatinus', count=2, weight=2.2) animal.save() self.assertTrue((animal.id > 1))
'Regression test for ticket #6436 -- os.path.join will throw away the initial parts of a path if it encounters an absolute path. This means that if a fixture is specified as an absolute path, we need to make sure we don\'t discover the absolute path in every fixture directory.'
def test_absolute_path(self):
load_absolute_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'absolute.json') management.call_command('loaddata', load_absolute_path, verbosity=0, commit=False) self.assertEqual(Absolute.load_count, 1)
'Test for ticket #4371 -- Loading data of an unknown format should fail Validate that error conditions are caught correctly'
def test_unknown_format(self):
stderr = StringIO() management.call_command('loaddata', 'bad_fixture1.unkn', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "Problem installing fixture 'bad_fixture1': unkn is not a known serialization format.\n")
'Test for ticket #4371 -- Loading a fixture file with invalid data using explicit filename. Validate that error conditions are caught correctly'
def test_invalid_data(self):
stderr = StringIO() management.call_command('loaddata', 'bad_fixture2.xml', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n")
'Test for ticket #4371 -- Loading a fixture file with invalid data without file extension. Validate that error conditions are caught correctly'
def test_invalid_data_no_ext(self):
stderr = StringIO() management.call_command('loaddata', 'bad_fixture2', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n")
'Test for ticket #4371 -- Loading a fixture file with no data returns an error. Validate that error conditions are caught correctly'
def test_empty(self):
stderr = StringIO() management.call_command('loaddata', 'empty', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "No fixture data found for 'empty'. (File format may be invalid.)\n")
'Test for ticket #4371 -- If any of the fixtures contain an error, loading is aborted. Validate that error conditions are caught correctly'
def test_abort_loaddata_on_error(self):
stderr = StringIO() management.call_command('loaddata', 'empty', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "No fixture data found for 'empty'. (File format may be invalid.)\n")
'(Regression for #9011 - error message is correct)'
def test_error_message(self):
stderr = StringIO() management.call_command('loaddata', 'bad_fixture2', 'animal', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n")
'Test for ticket #7565 -- PostgreSQL sequence resetting checks shouldn\'t ascend to parent models when inheritance is used (since they are treated individually).'
def test_pg_sequence_resetting_checks(self):
management.call_command('loaddata', 'model-inheritance.json', verbosity=0, commit=False) self.assertEqual(Parent.objects.all()[0].id, 1) self.assertEqual(Child.objects.all()[0].id, 1)
'Test for ticket #7572 -- MySQL has a problem if the same connection is used to create tables, load data, and then query over that data. To compensate, we close the connection after running loaddata. This ensures that a new connection is opened when test queries are issued.'
def test_close_connection_after_loaddata(self):
management.call_command('loaddata', 'big-fixture.json', verbosity=0, commit=False) articles = Article.objects.exclude(id=9) self.assertEqual(list(articles.values_list('id', flat=True)), [1, 2, 3, 4, 5, 6, 7, 8]) self.assertEqual(list(articles.values_list('id', flat=True)), [1, 2, 3, 4, 5, 6, 7, 8])
'Test for tickets #8298, #9942 - Field values should be coerced into the correct type by the deserializer, not as part of the database write.'
def test_field_value_coerce(self):
global pre_save_checks pre_save_checks = [] signals.pre_save.connect(animal_pre_save_check) management.call_command('loaddata', 'animal.xml', verbosity=0, commit=False) self.assertEqual(pre_save_checks, [("Count = 42 (<type 'int'>)", "Weight = 1.2 (<type 'float'>)")]) sig...
'Regression for #11286 Ensure that dumpdata honors the default manager Dump the current contents of the database as a JSON fixture'
def test_dumpdata_uses_default_manager(self):
management.call_command('loaddata', 'animal.xml', verbosity=0, commit=False) management.call_command('loaddata', 'sequence.json', verbosity=0, commit=False) animal = Animal(name='Platypus', latin_name='Ornithorhynchus anatinus', count=2, weight=2.2) animal.save() stdout = StringIO() managemen...
'Regression for #11428 - Proxy models aren\'t included when you dumpdata'
def test_proxy_model_included(self):
stdout = StringIO() Widget(name='grommet').save() management.call_command('dumpdata', 'fixtures_regress.widget', 'fixtures_regress.widgetproxy', format='json', stdout=stdout) self.assertEqual(stdout.getvalue(), '[{"pk": 1, "model": "fixtures_regress.widget", "fields": {"name": "grommet...
'Test for ticket #13030 - Python based parser version natural keys deserialize with fk to inheriting model'
def test_nk_deserialize(self):
management.call_command('loaddata', 'model-inheritance.json', verbosity=0, commit=False) management.call_command('loaddata', 'nk-inheritance.json', verbosity=0, commit=False) self.assertEqual(NKChild.objects.get(pk=1).data, 'apple') self.assertEqual(RefToNKChild.objects.get(pk=1).nk_fk.data, 'apple')
'Test for ticket #13030 - XML version natural keys deserialize with fk to inheriting model'
def test_nk_deserialize_xml(self):
management.call_command('loaddata', 'model-inheritance.json', verbosity=0, commit=False) management.call_command('loaddata', 'nk-inheritance.json', verbosity=0, commit=False) management.call_command('loaddata', 'nk-inheritance2.xml', verbosity=0, commit=False) self.assertEqual(NKChild.objects.get(pk=2)....
'Check that natural key requirements are taken into account when serializing models'
def test_nk_on_serialize(self):
management.call_command('loaddata', 'forward_ref_lookup.json', verbosity=0, commit=False) stdout = StringIO() management.call_command('dumpdata', 'fixtures_regress.book', 'fixtures_regress.person', 'fixtures_regress.store', verbosity=0, format='json', use_natural_keys=True, stdout=stdout) self.assertEqu...
'Now lets check the dependency sorting explicitly It doesn\'t matter what order you mention the models Store *must* be serialized before then Person, and both must be serialized before Book.'
def test_dependency_sorting(self):
sorted_deps = sort_dependencies([('fixtures_regress', [Book, Person, Store])]) self.assertEqual(sorted_deps, [Store, Person, Book])
'Check that normal primary keys still work on a model with natural key capabilities'
def test_normal_pk(self):
management.call_command('loaddata', 'non_natural_1.json', verbosity=0, commit=False) management.call_command('loaddata', 'forward_ref_lookup.json', verbosity=0, commit=False) management.call_command('loaddata', 'non_natural_2.xml', verbosity=0, commit=False) books = Book.objects.all() self.assertEqu...
'Test that the request object is available in the template and that its attributes can\'t be overridden by GET and POST parameters (#3828).'
def test_request_attributes(self):
url = '/request_attrs/' response = self.client.get(url) self.assertContains(response, 'Have request') response = self.client.get(url) self.assertContains(response, 'Not secure') response = self.client.get(url, {'is_secure': 'blah'}) self.assertContains(response, 'Not secure') re...
'Tests that the session is not accessed simply by including the auth context processor'
def test_session_not_accessed(self):
response = self.client.get('/auth_processor_no_attr_access/') self.assertContains(response, 'Session not accessed')
'Tests that the session is accessed if the auth context processor is used and relevant attributes accessed.'
def test_session_is_accessed(self):
response = self.client.get('/auth_processor_attr_access/') self.assertContains(response, 'Session accessed')
'Test that the lazy objects returned behave just like the wrapped objects.'
def test_user_attrs(self):
self.client.login(username='super', password='secret') user = authenticate(username='super', password='secret') response = self.client.get('/auth_processor_user/') self.assertContains(response, 'unicode: super') self.assertContains(response, 'id: 100') self.assertContains(response, 'userna...
'Check that querysets will use the default databse by default'
def test_db_selection(self):
self.assertEquals(Book.objects.db, DEFAULT_DB_ALIAS) self.assertEquals(Book.objects.all().db, DEFAULT_DB_ALIAS) self.assertEquals(Book.objects.using('other').db, 'other') self.assertEquals(Book.objects.db_manager('other').db, 'other') self.assertEquals(Book.objects.db_manager('other').all().db, 'oth...
'Objects created on the default database don\'t leak onto other databases'
def test_default_creation(self):
Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) dive = Book() dive.title = 'Dive into Python' dive.published = datetime.date(2009, 5, 4) dive.save() try: Book.objects.get(title='Pro Django') Book.objects.using('default').get(title='Pro ...
'Objects created on another database don\'t leak onto the default database'
def test_other_creation(self):
Book.objects.using('other').create(title='Pro Django', published=datetime.date(2008, 12, 16)) dive = Book() dive.title = 'Dive into Python' dive.published = datetime.date(2009, 5, 4) dive.save(using='other') try: Book.objects.using('other').get(title='Pro Django') except ...
'Queries are constrained to a single database'
def test_basic_queries(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4)) self.assertEqual(dive.title, 'Dive into Python') self.assertRaises(Book.DoesNotExist, Book.objects.using('defau...
'M2M fields are constrained to a single database'
def test_m2m_separation(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name='Marty Alchin') dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='M...
'M2M forward manipulations are all constrained to a single DB'
def test_m2m_forward_operations(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='Mark Pilgrim') dive.authors = [mark] john = Person.objects.using('other').create(name='John Smith') self.assertEquals(list(Book.objec...
'M2M reverse manipulations are all constrained to a single DB'
def test_m2m_reverse_operations(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='Mark Pilgrim') dive.authors = [mark] grease = Book.objects.using('other').create(title='Greasemonkey Hacks', published=datetime.date(2005...
'Operations that involve sharing M2M objects across databases raise an error'
def test_m2m_cross_database_protection(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name='Marty Alchin') dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='M...
'Cascaded deletions of m2m relations issue queries on the right database'
def test_m2m_deletion(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='Mark Pilgrim') dive.authors = [mark] self.assertEquals(Person.objects.using('default').count(), 0) self.assertEquals(Book.objects.using(...
'FK fields are constrained to a single database'
def test_foreign_key_separation(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name='Marty Alchin') george = Person.objects.create(name='George Vilches') dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5...
'FK reverse manipulations are all constrained to a single DB'
def test_foreign_key_reverse_operations(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='Mark Pilgrim') chris = Person.objects.using('other').create(name='Chris Mills') dive.editor = chris dive.save() html5 = Book.obje...
'Operations that involve sharing FK objects across databases raise an error'
def test_foreign_key_cross_database_protection(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name='Marty Alchin') dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='M...
'Cascaded deletions of Foreign Key relations issue queries on the right database'
def test_foreign_key_deletion(self):
mark = Person.objects.using('other').create(name='Mark Pilgrim') fido = Pet.objects.using('other').create(name='Fido', owner=mark) self.assertEquals(Person.objects.using('default').count(), 0) self.assertEquals(Pet.objects.using('default').count(), 0) self.assertEquals(Person.objects.using('other...
'ForeignKey.validate() uses the correct database'
def test_foreign_key_validation(self):
mickey = Person.objects.using('other').create(name='Mickey') pluto = Pet.objects.using('other').create(name='Pluto', owner=mickey) self.assertEquals(None, pluto.full_clean())
'OneToOne fields are constrained to a single database'
def test_o2o_separation(self):
alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com') alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate') bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com') bob_profile = UserProfile.objects.using('other').c...
'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.using('default').create(user=alice, flavor='chocolate') try: bob.userprofile = alice_profile ...
'Generic fields are constrained to a single database'
def test_generic_key_separation(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) review1 = Review.objects.create(source='Python Monthly', content_object=pro) dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) review2 = Review.objects....
'Generic reverse manipulations are all constrained to a single DB'
def test_generic_key_reverse_operations(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) temp = Book.objects.using('other').create(title='Temp', published=datetime.date(2009, 5, 4)) review1 = Review.objects.using('other').create(source='Python Weekly', content_object=dive) revie...
'Operations that involve sharing generic key objects across databases raise an error'
def test_generic_key_cross_database_protection(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) review1 = Review.objects.create(source='Python Monthly', content_object=pro) dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) review2 = Review.objects....
'Cascaded deletions of Generic Key relations issue queries on the right database'
def test_generic_key_deletion(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) review = Review.objects.using('other').create(source='Python Weekly', content_object=dive) self.assertEquals(Book.objects.using('default').count(), 0) self.assertEquals(Review.objects.using(...
'get_next_by_XXX commands stick to a single database'
def test_ordering(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) learn = Book.objects.using('other').create(title='Learning Python', published=datetime.date(2008, 7, 16)) ...
'test the raw() method across databases'
def test_raw(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) val = Book.objects.db_manager('other').raw('SELECT id FROM multiple_database_book') self.assertEqual(map((lambda o: o.pk), val), [dive.pk]) val = Book.objects.raw('SELECT id FROM...
'Database assignment is retained if an object is retrieved with select_related()'
def test_select_related(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) book = Book.objects.using('other').select_related('editor').get(title='Dive into Python') self.assertEqual...
'Make sure as_sql works with subqueries and master/slave.'
def test_subquery(self):
sub = Person.objects.using('other').filter(name='fff') qs = Book.objects.filter(editor__in=sub) self.assertRaises(ValueError, str, qs.query) try: for obj in qs: pass self.fail('Iterating over query should raise ValueError') except ValueError: pass
'Related managers return managers, not querysets'
def test_related_manager(self):
mark = Person.objects.using('other').create(name='Mark Pilgrim') mark.book_set.create(title='Dive into Python', published=datetime.date(2009, 5, 4), extra_arg=True) mark.book_set.get_or_create(title='Dive into Python', published=datetime.date(2009, 5, 4), extra_arg=True) mark.edited.creat...
'Point all read operations on auth models to \'default\''
def db_for_read(self, model, **hints):
if (model._meta.app_label == 'auth'): return 'default' return None
'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.assertEquals(Book.objects.db, 'other') self.assertEquals(Book.objects.all().db, 'other') self.assertEquals(Book.objects.using('default').db, 'default') self.assertEquals(Book.objects.db_manager('default').db, 'default') self.assertEquals(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.assertEquals(router.db_for_read(User), 'other') self.assertEquals(router.db_for_read(Book), 'other') self.assertEquals(router.db_for_write(User), 'default') self.assertEquals(router.db...
'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.assertEquals(pro.authors.db, 'other') self.assertEquals(pro.authors.db_manager('default')...
'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.assertEquals(marty.edited.db, 'other') self.assertEquals(marty.edited.db_manager('default').db, 'defa...
'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.assertEquals(pro.reviews.db, 'other') self.assertEquals(pro.reviews.db_manager('default').db, 'defaul...
'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.assertEquals(alice.username, 'alice') self.assertEquals(alice._state.db, 'other') self.assertRaises(User....
'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.assertTrue(('Installed 0 object(s) (of 2) from 1 fixture(s)' in command_output))
'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.assertEquals(self.p1.restaurant, self.r1) self.assertEquals(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.assertEquals(label_for_field('title', Article), 'title') self.assertEquals(label_for_field('title2', Article), 'another name') self.assertEquals(label_for_field('title2', Article, return_attr=True), ('another name', None)) self.assertEquals(label_for_field('__unicode__', Article), 'article') ...
'Regression test for #13963'
def test_related_name(self):
self.assertEquals(label_for_field('location', Event, return_attr=True), ('location', None)) self.assertEquals(label_for_field('event', Location, return_attr=True), ('awesome event', None)) self.assertEquals(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') 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': u'1', 'poem_set-0-poem': u'1', 'poem_s...
'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.assertRaisesErrorWithMessage(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.assertRaisesErrorWithMessage(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.assertRaisesErrorWithMessage(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')