desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'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(u'loaddata', u'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(u'loaddata', u'big-fixture.json', verbosity=0, commit=False) articles = Article.objects.exclude(id=9) self.assertEqual(list(articles.values_list(u'id', flat=True)), [1, 2, 3, 4, 5, 6, 7, 8]) self.assertEqual(list(articles.values_list(u'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):
self.pre_save_checks = [] signals.pre_save.connect(self.animal_pre_save_check) try: management.call_command(u'loaddata', u'animal.xml', verbosity=0, commit=False) self.assertEqual(self.pre_save_checks, [((u"Count = 42 (<%s 'int'>)" % (u'class' if PY3 else u'type')), (u"Weight ...
'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(u'loaddata', u'animal.xml', verbosity=0, commit=False) management.call_command(u'loaddata', u'sequence.json', verbosity=0, commit=False) animal = Animal(name=u'Platypus', latin_name=u'Ornithorhynchus anatinus', count=2, weight=2.2) animal.save() stdout = StringIO() man...
'Regression for #11428 - Proxy models aren\'t included when you dumpdata'
def test_proxy_model_included(self):
stdout = StringIO() widget = Widget.objects.create(name=u'grommet') management.call_command(u'dumpdata', u'fixtures_regress.widget', u'fixtures_regress.widgetproxy', format=u'json', stdout=stdout) self.assertJSONEqual(stdout.getvalue(), (u'[{"pk": %d, "model": "fixtures_regress.widget", "fie...
'Regression for #3615 - Forward references cause fixtures not to load in MySQL (InnoDB)'
def test_loaddata_works_when_fixture_has_forward_refs(self):
management.call_command(u'loaddata', u'forward_ref.json', verbosity=0, commit=False) self.assertEqual(Book.objects.all()[0].id, 1) self.assertEqual(Person.objects.all()[0].id, 4)
'Regression for #3615 - Ensure data with nonexistent child key references raises error'
def test_loaddata_raises_error_when_fixture_has_invalid_foreign_key(self):
with six.assertRaisesRegex(self, IntegrityError, u'Problem installing fixture'): management.call_command(u'loaddata', u'forward_ref_bad_data.json', verbosity=0, commit=False)
'Regression for #17530 - should be able to cope with forward references when the fixtures are not in the same files or directories.'
@override_settings(FIXTURE_DIRS=[os.path.join(_cur_dir, u'fixtures_1'), os.path.join(_cur_dir, u'fixtures_2')]) def test_loaddata_forward_refs_split_fixtures(self):
management.call_command(u'loaddata', u'forward_ref_1.json', u'forward_ref_2.json', verbosity=0, commit=False) self.assertEqual(Book.objects.all()[0].id, 1) self.assertEqual(Person.objects.all()[0].id, 4)
'Regression for #7043 - Error is quickly reported when no fixtures is provided in the command line.'
def test_loaddata_no_fixture_specified(self):
with six.assertRaisesRegex(self, management.CommandError, u'No database fixture specified. Please provide the path of at least one fixture in the command line.'): management.call_command(u'loaddata', verbosity=0, commit=False)
'Test for ticket #13030 - Python based parser version natural keys deserialize with fk to inheriting model'
def test_nk_deserialize(self):
management.call_command(u'loaddata', u'model-inheritance.json', verbosity=0, commit=False) management.call_command(u'loaddata', u'nk-inheritance.json', verbosity=0, commit=False) self.assertEqual(NKChild.objects.get(pk=1).data, u'apple') self.assertEqual(RefToNKChild.objects.get(pk=1).nk_fk.data, u'appl...
'Test for ticket #13030 - XML version natural keys deserialize with fk to inheriting model'
def test_nk_deserialize_xml(self):
management.call_command(u'loaddata', u'model-inheritance.json', verbosity=0, commit=False) management.call_command(u'loaddata', u'nk-inheritance.json', verbosity=0, commit=False) management.call_command(u'loaddata', u'nk-inheritance2.xml', verbosity=0, commit=False) self.assertEqual(NKChild.objects.get(...
'Check that natural key requirements are taken into account when serializing models'
def test_nk_on_serialize(self):
management.call_command(u'loaddata', u'forward_ref_lookup.json', verbosity=0, commit=False) stdout = StringIO() management.call_command(u'dumpdata', u'fixtures_regress.book', u'fixtures_regress.person', u'fixtures_regress.store', verbosity=0, format=u'json', use_natural_keys=True, stdout=stdout) self.as...
'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([(u'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(u'loaddata', u'non_natural_1.json', verbosity=0, commit=False) management.call_command(u'loaddata', u'forward_ref_lookup.json', verbosity=0, commit=False) management.call_command(u'loaddata', u'non_natural_2.xml', verbosity=0, commit=False) books = Book.objects.all() self.ass...
'Test that fixtures can be rolled back (ticket #11101).'
@skipUnlessDBFeature(u'supports_transactions') def test_ticket_11101(self):
ticket_11101 = transaction.commit_manually(self.ticket_11101) ticket_11101()
'Remove all entries named \'name\' from the ModelAdmin instance URL patterns list'
def remove_url(self, name):
return [url for url in super(ActionAdmin, self).get_urls() if (url.name != name)]
'Ensure GET on the add_view works.'
def testBasicAddGet(self):
response = self.client.get(u'/custom_urls/admin/admin_custom_urls/action/!add/') self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200)
'Ensure GET on the add_view plus specifying a field value in the query string works.'
def testAddWithGETArgs(self):
response = self.client.get(u'/custom_urls/admin/admin_custom_urls/action/!add/', {u'name': u'My Action'}) self.assertEqual(response.status_code, 200) self.assertContains(response, u'value="My Action"')
'Ensure POST on add_view works.'
def testBasicAddPost(self):
post_data = {u'_popup': u'1', u'name': u'Action added through a popup', u'description': u'Description of added action'} response = self.client.post(u'/custom_urls/admin/admin_custom_urls/action/!add/', post_data) self.assertEqual(response.status_code, 200) self.assertContains(respon...
'Test that some admin URLs work correctly.'
def testAdminUrlsNoClash(self):
response = self.client.get(u'/custom_urls/admin/admin_custom_urls/action/add/') self.assertEqual(response.status_code, 200) self.assertContains(response, u'Change action') url = reverse((u'admin:%s_action_change' % Action._meta.app_label), args=(quote(u'add'),)) response = self.client.get(url) ...
'Ensures that ModelAdmin.response_post_save_add() controls the redirection after the \'Save\' button has been pressed when adding a new object. Refs 8001, 18310, 19505.'
def test_post_save_add_redirect(self):
post_data = {u'name': u'John Doe'} self.assertEqual(Person.objects.count(), 0) response = self.client.post(reverse(u'admin:admin_custom_urls_person_add'), post_data) persons = Person.objects.all() self.assertEqual(len(persons), 1) self.assertRedirects(response, reverse(u'admin:admin_custom_ur...
'Ensures that ModelAdmin.response_post_save_change() controls the redirection after the \'Save\' button has been pressed when editing an existing object. Refs 8001, 18310, 19505.'
def test_post_save_change_redirect(self):
Person.objects.create(name=u'John Doe') self.assertEqual(Person.objects.count(), 1) person = Person.objects.all()[0] post_data = {u'name': u'Jack Doe'} response = self.client.post(reverse(u'admin:admin_custom_urls_person_change', args=[person.pk]), post_data) self.assertRedirects(response,...
'Ensures that the ModelAdmin.response_add()\'s parameter `post_url_continue` controls the redirection after an object has been created.'
def test_post_url_continue(self):
post_data = {u'name': u'SuperFast', u'_continue': u'1'} self.assertEqual(Car.objects.count(), 0) response = self.client.post(reverse(u'admin:admin_custom_urls_car_add'), post_data) cars = Car.objects.all() self.assertEqual(len(cars), 1) self.assertRedirects(response, reverse(u'admin:admin_custom...
'Ensures that string formats are accepted for post_url_continue. This is a deprecated functionality that will be removed in Django 1.6 along with this test.'
def test_post_url_continue_string_formats(self):
with warnings.catch_warnings(record=True) as w: post_data = {u'name': u'SuperFast', u'_continue': u'1'} self.assertEqual(Car.objects.count(), 0) response = self.client.post(reverse(u'admin:admin_custom_urls_cardeprecated_add'), post_data) cars = CarDeprecated.objects.all() se...
'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...
'Check that querysets will use the default database by default'
def test_db_selection(self):
self.assertEqual(Book.objects.db, DEFAULT_DB_ALIAS) self.assertEqual(Book.objects.all().db, DEFAULT_DB_ALIAS) self.assertEqual(Book.objects.using(u'other').db, u'other') self.assertEqual(Book.objects.db_manager(u'other').db, u'other') self.assertEqual(Book.objects.db_manager(u'other').all().db, u'ot...
'Objects created on the default database don\'t leak onto other databases'
def test_default_creation(self):
Book.objects.create(title=u'Pro Django', published=datetime.date(2008, 12, 16)) dive = Book() dive.title = u'Dive into Python' dive.published = datetime.date(2009, 5, 4) dive.save() try: Book.objects.get(title=u'Pro Django') Book.objects.using(u'default').get(title=u'...
'Objects created on another database don\'t leak onto the default database'
def test_other_creation(self):
Book.objects.using(u'other').create(title=u'Pro Django', published=datetime.date(2008, 12, 16)) dive = Book() dive.title = u'Dive into Python' dive.published = datetime.date(2009, 5, 4) dive.save(using=u'other') try: Book.objects.using(u'other').get(title=u'Pro Django') e...
'Queries are constrained to a single database'
def test_basic_queries(self):
dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) dive = Book.objects.using(u'other').get(published=datetime.date(2009, 5, 4)) self.assertEqual(dive.title, u'Dive into Python') self.assertRaises(Book.DoesNotExist, Book.objects.using(u'...
'M2M fields are constrained to a single database'
def test_m2m_separation(self):
pro = Book.objects.create(title=u'Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name=u'Marty Alchin') dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using(u'other').create(na...
'M2M forward manipulations are all constrained to a single DB'
def test_m2m_forward_operations(self):
dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using(u'other').create(name=u'Mark Pilgrim') dive.authors = [mark] john = Person.objects.using(u'other').create(name=u'John Smith') self.assertEqual(list(Book....
'M2M reverse manipulations are all constrained to a single DB'
def test_m2m_reverse_operations(self):
dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using(u'other').create(name=u'Mark Pilgrim') dive.authors = [mark] grease = Book.objects.using(u'other').create(title=u'Greasemonkey Hacks', published=datetime.dat...
'Operations that involve sharing M2M objects across databases raise an error'
def test_m2m_cross_database_protection(self):
pro = Book.objects.create(title=u'Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name=u'Marty Alchin') dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using(u'other').create(na...
'Cascaded deletions of m2m relations issue queries on the right database'
def test_m2m_deletion(self):
dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using(u'other').create(name=u'Mark Pilgrim') dive.authors = [mark] self.assertEqual(Person.objects.using(u'default').count(), 0) self.assertEqual(Book.objects.usi...
'FK fields are constrained to a single database'
def test_foreign_key_separation(self):
pro = Book.objects.create(title=u'Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name=u'Marty Alchin') george = Person.objects.create(name=u'George Vilches') dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(20...
'FK reverse manipulations are all constrained to a single DB'
def test_foreign_key_reverse_operations(self):
dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using(u'other').create(name=u'Mark Pilgrim') chris = Person.objects.using(u'other').create(name=u'Chris Mills') dive.editor = chris dive.save() html5 = Boo...
'Operations that involve sharing FK objects across databases raise an error'
def test_foreign_key_cross_database_protection(self):
pro = Book.objects.create(title=u'Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name=u'Marty Alchin') dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using(u'other').create(na...
'Cascaded deletions of Foreign Key relations issue queries on the right database'
def test_foreign_key_deletion(self):
mark = Person.objects.using(u'other').create(name=u'Mark Pilgrim') fido = Pet.objects.using(u'other').create(name=u'Fido', owner=mark) self.assertEqual(Person.objects.using(u'default').count(), 0) self.assertEqual(Pet.objects.using(u'default').count(), 0) self.assertEqual(Person.objects.using(u'o...
'ForeignKey.validate() uses the correct database'
def test_foreign_key_validation(self):
mickey = Person.objects.using(u'other').create(name=u'Mickey') pluto = Pet.objects.using(u'other').create(name=u'Pluto', owner=mickey) self.assertEqual(None, pluto.full_clean())
'OneToOne fields are constrained to a single database'
def test_o2o_separation(self):
alice = User.objects.db_manager(u'default').create_user(u'alice', u'alice@example.com') alice_profile = UserProfile.objects.using(u'default').create(user=alice, flavor=u'chocolate') bob = User.objects.db_manager(u'other').create_user(u'bob', u'bob@example.com') bob_profile = UserProfile.objects.using(u'...
'Operations that involve sharing FK objects across databases raise an error'
def test_o2o_cross_database_protection(self):
alice = User.objects.db_manager(u'default').create_user(u'alice', u'alice@example.com') bob = User.objects.db_manager(u'other').create_user(u'bob', u'bob@example.com') alice_profile = UserProfile.objects.using(u'default').create(user=alice, flavor=u'chocolate') try: bob.userprofile = alice_profi...
'Generic fields are constrained to a single database'
def test_generic_key_separation(self):
pro = Book.objects.create(title=u'Pro Django', published=datetime.date(2008, 12, 16)) review1 = Review.objects.create(source=u'Python Monthly', content_object=pro) dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) review2 = Review.obje...
'Generic reverse manipulations are all constrained to a single DB'
def test_generic_key_reverse_operations(self):
dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) temp = Book.objects.using(u'other').create(title=u'Temp', published=datetime.date(2009, 5, 4)) review1 = Review.objects.using(u'other').create(source=u'Python Weekly', content_object=dive) ...
'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=u'Pro Django', published=datetime.date(2008, 12, 16)) review1 = Review.objects.create(source=u'Python Monthly', content_object=pro) dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) review2 = Review.obje...
'Cascaded deletions of Generic Key relations issue queries on the right database'
def test_generic_key_deletion(self):
dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) review = Review.objects.using(u'other').create(source=u'Python Weekly', content_object=dive) self.assertEqual(Book.objects.using(u'default').count(), 0) self.assertEqual(Review.objects.usi...
'get_next_by_XXX commands stick to a single database'
def test_ordering(self):
pro = Book.objects.create(title=u'Pro Django', published=datetime.date(2008, 12, 16)) dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) learn = Book.objects.using(u'other').create(title=u'Learning Python', published=datetime.date(2008, 7, ...
'test the raw() method across databases'
def test_raw(self):
dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) val = Book.objects.db_manager(u'other').raw(u'SELECT id FROM multiple_database_book') self.assertQuerysetEqual(val, [dive.pk], attrgetter(u'pk')) val = Book.objects.raw(u'SELECT i...
'Database assignment is retained if an object is retrieved with select_related()'
def test_select_related(self):
mark = Person.objects.using(u'other').create(name=u'Mark Pilgrim') dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4), editor=mark) book = Book.objects.using(u'other').select_related(u'editor').get(title=u'Dive into Python') self.asse...
'Make sure as_sql works with subqueries and master/slave.'
def test_subquery(self):
sub = Person.objects.using(u'other').filter(name=u'fff') qs = Book.objects.filter(editor__in=sub) self.assertRaises(ValueError, str, qs.query) try: for obj in qs: pass self.fail(u'Iterating over query should raise ValueError') except ValueError: pas...
'Related managers return managers, not querysets'
def test_related_manager(self):
mark = Person.objects.using(u'other').create(name=u'Mark Pilgrim') mark.book_set.create(title=u'Dive into Python', published=datetime.date(2009, 5, 4), extra_arg=True) mark.book_set.get_or_create(title=u'Dive into Python', published=datetime.date(2009, 5, 4), extra_arg=True) mark.edited.c...
'Point all read operations on auth models to \'default\''
def db_for_read(self, model, **hints):
if (model._meta.app_label == u'auth'): return u'default' return None
'Point all operations on auth models to \'other\''
def db_for_write(self, model, **hints):
if (model._meta.app_label == u'auth'): return u'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 == u'auth') or (obj2._meta.app_label == u'auth')): return True return None
'Make sure the auth app only appears on the \'other\' db'
def allow_syncdb(self, db, model):
if (db == u'other'): return (model._meta.app_label == u'auth') elif (model._meta.app_label == u'auth'): return False return None
'Check that querysets obey the router for db suggestions'
def test_db_selection(self):
self.assertEqual(Book.objects.db, u'other') self.assertEqual(Book.objects.all().db, u'other') self.assertEqual(Book.objects.using(u'default').db, u'default') self.assertEqual(Book.objects.db_manager(u'default').db, u'default') self.assertEqual(Book.objects.db_manager(u'default').all().db, u'default'...
'Synchronization behavior is predictable'
def test_syncdb_selection(self):
self.assertTrue(router.allow_syncdb(u'default', User)) self.assertTrue(router.allow_syncdb(u'default', Book)) self.assertTrue(router.allow_syncdb(u'other', User)) self.assertTrue(router.allow_syncdb(u'other', Book)) router.routers = [TestRouter(), AuthRouter()] self.assertTrue(router.allow_syncd...
'A router can choose to implement a subset of methods'
def test_partial_router(self):
dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) self.assertEqual(router.db_for_read(User), u'other') self.assertEqual(router.db_for_read(Book), u'other') self.assertEqual(router.db_for_write(User), u'default') self.assertEqual(router.d...
'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(u'default').create(title=u'Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.using(u'default').create(name=u'Marty Alchin') dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4)) mark = Pers...
'M2M relations can cross databases if the database share a source'
def test_m2m_cross_database_protection(self):
pro = Book.objects.using(u'other').create(pk=1, title=u'Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.using(u'other').create(pk=1, name=u'Marty Alchin') dive = Book.objects.using(u'default').create(pk=2, title=u'Dive into Python', published=datetime.date(2009, 5, 4))...
'Operations that involve sharing FK objects across databases raise an error'
def test_o2o_cross_database_protection(self):
alice = User.objects.db_manager(u'default').create_user(u'alice', u'alice@example.com') bob = User.objects.db_manager(u'other').create_user(u'bob', u'bob@example.com') alice_profile = UserProfile.objects.create(user=alice, flavor=u'chocolate') try: bob.userprofile = alice_profile except Valu...
'Generic Key operations can span databases if they share a source'
def test_generic_key_cross_database_protection(self):
pro = Book.objects.using(u'default').create(title=u'Pro Django', published=datetime.date(2008, 12, 16)) review1 = Review.objects.using(u'default').create(source=u'Python Monthly', content_object=pro) dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(20...
'M2M relations are represented by managers, and can be controlled like managers'
def test_m2m_managers(self):
pro = Book.objects.using(u'other').create(pk=1, title=u'Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.using(u'other').create(pk=1, name=u'Marty Alchin') pro_authors = pro.authors.using(u'other') authors = [marty] self.assertEqual(pro.authors.db, u'other') self....
'FK reverse relations are represented by managers, and can be controlled like managers'
def test_foreign_key_managers(self):
marty = Person.objects.using(u'other').create(pk=1, name=u'Marty Alchin') pro = Book.objects.using(u'other').create(pk=1, title=u'Pro Django', published=datetime.date(2008, 12, 16), editor=marty) self.assertEqual(marty.edited.db, u'other') self.assertEqual(marty.edited.db_manager(u'default').db, u...
'Generic key relations are represented by managers, and can be controlled like managers'
def test_generic_key_managers(self):
pro = Book.objects.using(u'other').create(title=u'Pro Django', published=datetime.date(2008, 12, 16)) review1 = Review.objects.using(u'other').create(source=u'Python Monthly', content_object=pro) self.assertEqual(pro.reviews.db, u'other') self.assertEqual(pro.reviews.db_manager(u'default').db, u'd...
'Make sure as_sql works with subqueries and master/slave.'
def test_subquery(self):
mark = Person.objects.using(u'other').create(name=u'Mark Pilgrim') dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4), editor=mark) sub = Person.objects.filter(name=u'Mark Pilgrim') qs = Book.objects.filter(editor__in=sub) str(qs.que...
'The methods on the auth manager obey database hints'
def test_auth_manager(self):
User.objects.create_user(u'alice', u'alice@example.com') User.objects.db_manager(u'default').create_user(u'bob', u'bob@example.com') alice = User.objects.using(u'other').get(username=u'alice') self.assertEqual(alice.username, u'alice') self.assertEqual(alice._state.db, u'other') self.assertRaise...
'Check that dumpdata honors allow_syncdb restrictions on the router'
def test_dumpdata(self):
User.objects.create_user(u'alice', u'alice@example.com') User.objects.db_manager(u'default').create_user(u'bob', u'bob@example.com') new_io = StringIO() management.call_command(u'dumpdata', u'auth', format=u'json', database=u'default', stdout=new_io) command_output = new_io.getvalue().strip() se...
'Make sure the auth app only appears on the \'other\' db'
def allow_syncdb(self, db, model):
if (db == u'other'): return (model._meta.object_name == u'Pet') else: return (model._meta.object_name != u'Pet')
'Multi-db fixtures are loaded correctly'
def test_fixture_loading(self):
try: Book.objects.get(title=u'Pro Django') Book.objects.using(u'default').get(title=u'Pro Django') except Book.DoesNotExist: self.fail(u'"Pro Django" should exist on default database') self.assertRaises(Book.DoesNotExist, Book.objects.using(u'other').get, titl...
'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(u'loaddata', u'pets', stdout=new_io, stderr=new_io) command_output = new_io.getvalue().strip() self.assertEqual(command_output, u'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=u'Pro Django', published=datetime.date(2008, 12, 16)) p = Person.objects.create(name=u'Marty Alchin') Book.objects.using(u'other').create(pk=b.pk, title=b.title, published=b.published) ...
'Check that the AttributeError from AttributeErrorRouter bubbles up'
def test_attribute_error_read(self):
router.routers = [] b = Book.objects.create(title=u'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 = u'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=u'Pro Django', published=datetime.date(2008, 12, 16)) p = Person.objects.create(name=u'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=u'Pro Django', published=datetime.date(2008, 12, 16)) p = Person.objects.create(name=u'Marty Alchin') router.routers = [AttributeErrorRouter()] self.assertRaises(AttributeError, setattr, b, u'authors', [p])
'Regression test for #16039: syncdb with --database option.'
def test_syncdb_to_other_database(self):
cts = ContentType.objects.using(u'other').filter(app_label=u'multiple_database') count = cts.count() self.assertGreater(count, 0) cts.delete() management.call_command(u'syncdb', verbosity=0, interactive=False, load_initial_data=False, database=u'other') self.assertEqual(cts.count(), count)
'Regression test for #16039: syncdb with --database option.'
def test_syncdb_to_other_database_with_router(self):
cts = ContentType.objects.using(u'other').filter(app_label=u'multiple_database') cts.delete() try: old_routers = router.routers router.routers = [SyncOnlyDefaultDatabaseRouter()] management.call_command(u'syncdb', verbosity=0, interactive=False, load_initial_data=False, database=u'ot...
'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 for #13839 and #17439. DoesNotExist on a reverse one-to-one relation is cached.'
def test_reverse_object_does_not_exist_cache(self):
p = Place(name='Zombie Cats', address='Not sure') p.save() with self.assertNumQueries(1): with self.assertRaises(Restaurant.DoesNotExist): p.restaurant with self.assertNumQueries(0): with self.assertRaises(Restaurant.DoesNotExist): p.restaurant
'Regression for #13839 and #17439. The target of a one-to-one relation is cached when the origin is accessed through the reverse relation.'
def test_reverse_object_cached_when_related_is_accessed(self):
r = Restaurant.objects.get(pk=self.r1.pk) p = r.place with self.assertNumQueries(0): self.assertEqual(p.restaurant, r)
'Regression for #13839 and #17439. The origin of a one-to-one relation is cached when the target is accessed through the reverse relation.'
def test_related_object_cached_when_reverse_is_accessed(self):
p = Place.objects.get(pk=self.p1.pk) r = p.restaurant with self.assertNumQueries(0): self.assertEqual(r.place, p)
'Regression for #13839 and #17439. The target of a one-to-one relation is always cached.'
def test_reverse_object_cached_when_related_is_set(self):
p = Place(name='Zombie Cats', address='Not sure') p.save() self.r1.place = p self.r1.save() with self.assertNumQueries(0): self.assertEqual(p.restaurant, self.r1)
'Regression for #13839 and #17439. The target of a one-to-one relation is always cached.'
def test_reverse_object_cached_when_related_is_unset(self):
b = UndergroundBar(place=self.p1, serves_cocktails=True) b.save() with self.assertNumQueries(0): self.assertEqual(self.p1.undergroundbar, b) b.place = None b.save() with self.assertNumQueries(0): with self.assertRaises(UndergroundBar.DoesNotExist): self.p1.underground...
'Regression for #18153 and #19089. Accessing the reverse relation on an unsaved object always raises an exception.'
def test_get_reverse_on_unsaved_object(self):
p = Place() with self.assertNumQueries(0): with self.assertRaises(UndergroundBar.DoesNotExist): p.undergroundbar UndergroundBar.objects.create() with self.assertNumQueries(0): with self.assertRaises(UndergroundBar.DoesNotExist): p.undergroundbar UndergroundBar...
'Writing to the reverse relation on an unsaved object is impossible too.'
def test_set_reverse_on_unsaved_object(self):
p = Place() b = UndergroundBar.objects.create() with self.assertNumQueries(0): with self.assertRaises(ValueError): p.undergroundbar = b
'Check that the nested collector doesn\'t query for DO_NOTHING objects.'
def test_on_delete_do_nothing(self):
n = NestedObjects(using=DEFAULT_DB_ALIAS) objs = [Event.objects.create()] EventGuide.objects.create(event=objs[0]) with self.assertNumQueries(2): n.collect(objs)
'Regression test for #12654: lookup_field'
def test_values_from_lookup_field(self):
SITE_NAME = u'example.com' TITLE_TEXT = u'Some title' CREATED_DATE = datetime.min ADMIN_METHOD = u'admin method' SIMPLE_FUNCTION = u'function' INSTANCE_ATTRIBUTE = u'attr' class MockModelAdmin(object, ): def get_admin_value(self, obj): return ADMIN_METHOD simple...
'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, u'test_none'),))) self.assertEqual(display_value, u'test_none') display_value = display_for_field(None, models....
'Tests for label_for_field'
def test_label_for_field(self):
self.assertEqual(label_for_field(u'title', Article), u'title') self.assertEqual(label_for_field(u'title2', Article), u'another name') self.assertEqual(label_for_field(u'title2', Article, return_attr=True), (u'another name', None)) self.assertEqual(label_for_field(u'__unicode__', Article), u'articl...
'Regression test for #13963'
def test_related_name(self):
self.assertEqual(label_for_field(u'location', Event, return_attr=True), (u'location', None)) self.assertEqual(label_for_field(u'event', Location, return_attr=True), (u'awesome event', None)) self.assertEqual(label_for_field(u'guest', Event, return_attr=True), (u'awesome guest', None))
'Regression test for #15661'
def test_logentry_unicode(self):
log_entry = admin.models.LogEntry() log_entry.action_flag = admin.models.ADDITION self.assertTrue(six.text_type(log_entry).startswith(u'Added ')) log_entry.action_flag = admin.models.CHANGE self.assertTrue(six.text_type(log_entry).startswith(u'Changed ')) log_entry.action_flag = admin.mode...
'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=u'test') data = {u'poem_set-TOTAL_FORMS': u'1', u'poem_set-INITIAL_FORMS': u'0', u'poem_set-MAX_NUM_FORMS': u'0', u'poem_set-0-id': u'', u'poem_set-0-poem': u'1', u'poem_set-0-name': (u'x' * 1000)} formset =...
'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=u'test') poem = poet.poem_set.create(name=u'test poem') data = {u'poem_set-TOTAL_FORMS': u'1', u'poem_set-INITIAL_FORMS': u'1', u'poem_set-MAX_NUM_FORMS': u'0', u'poem_set-0-id': six.text_type(poem.id), u...