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 = 1.2 (<%s 'float'>)" % (u'class' if PY3 else u'type')))])
finally:
signals.pre_save.disconnect(self.animal_pre_save_check)
|
'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()
management.call_command(u'dumpdata', u'fixtures_regress.animal', format=u'json', stdout=stdout)
data = stdout.getvalue()
data = re.sub(u'0{6,}\\d', u'', data)
animals_data = sorted([{u'pk': 1, u'model': u'fixtures_regress.animal', u'fields': {u'count': 3, u'weight': 1.2, u'name': u'Lion', u'latin_name': u'Panthera leo'}}, {u'pk': 10, u'model': u'fixtures_regress.animal', u'fields': {u'count': 42, u'weight': 1.2, u'name': u'Emu', u'latin_name': u'Dromaius novaehollandiae'}}, {u'pk': animal.pk, u'model': u'fixtures_regress.animal', u'fields': {u'count': 2, u'weight': 2.2, u'name': u'Platypus', u'latin_name': u'Ornithorhynchus anatinus'}}], key=(lambda x: x[u'pk']))
data = sorted(json.loads(data), key=(lambda x: x[u'pk']))
self.maxDiff = 1024
self.assertEqual(data, animals_data)
|
'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", "fields": {"name": "grommet"}}]' % widget.pk))
|
'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'apple')
|
'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(pk=2).data, u'banana')
self.assertEqual(RefToNKChild.objects.get(pk=2).nk_fk.data, u'apple')
|
'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.assertJSONEqual(stdout.getvalue(), u'[{"pk": 2, "model": "fixtures_regress.store", "fields": {"main": null, "name": "Amazon"}}, {"pk": 3, "model": "fixtures_regress.store", "fields": {"main": null, "name": "Borders"}}, {"pk": 4, "model": "fixtures_regress.person", "fields": {"name": "Neal Stephenson"}}, {"pk": 1, "model": "fixtures_regress.book", "fields": {"stores": [["Amazon"], ["Borders"]], "name": "Cryptonomicon", "author": ["Neal Stephenson"]}}]')
|
'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.assertEqual(books.__repr__(), u"[<Book: Cryptonomicon by Neal Stephenson (available at Amazon, Borders)>, <Book: Ender's Game by Orson Scott Card (available at Collins Bookstore)>, <Book: Permutation City by Greg Egan (available at Angus and Robertson)>]")
|
'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(response, u'dismissAddAnotherPopup')
self.assertContains(response, u'Action added through a popup')
|
'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)
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'path/to/html/document.html'),))
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
self.assertContains(response, u'Change action')
self.assertContains(response, u'value="path/to/html/document.html"')
|
'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_urls_person_history', args=[persons[0].pk]))
|
'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, reverse(u'admin:admin_custom_urls_person_delete', args=[person.pk]))
|
'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_urls_car_history', args=[cars[0].pk]))
|
'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()
self.assertEqual(len(cars), 1)
self.assertRedirects(response, reverse(u'admin:admin_custom_urls_cardeprecated_history', args=[cars[0].pk]))
self.assertEqual(len(w), 1)
self.assertTrue(isinstance(w[0].message, DeprecationWarning))
|
'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')
response = self.client.post(url, {'is_secure': 'blah'})
self.assertContains(response, 'Not secure')
response = self.client.get(url)
self.assertContains(response, url)
response = self.client.get(url, {'path': '/blah/'})
self.assertContains(response, url)
response = self.client.post(url, {'path': '/blah/'})
self.assertContains(response, url)
|
'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'other')
|
'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'Pro Django')
except Book.DoesNotExist:
self.fail(u'"Dive Into Python" should exist on default database')
self.assertRaises(Book.DoesNotExist, Book.objects.using(u'other').get, title=u'Pro Django')
try:
Book.objects.get(title=u'Dive into Python')
Book.objects.using(u'default').get(title=u'Dive into Python')
except Book.DoesNotExist:
self.fail(u'"Dive into Python" should exist on default database')
self.assertRaises(Book.DoesNotExist, Book.objects.using(u'other').get, title=u'Dive into Python')
|
'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')
except Book.DoesNotExist:
self.fail(u'"Dive Into Python" should exist on other database')
self.assertRaises(Book.DoesNotExist, Book.objects.get, title=u'Pro Django')
self.assertRaises(Book.DoesNotExist, Book.objects.using(u'default').get, title=u'Pro Django')
try:
Book.objects.using(u'other').get(title=u'Dive into Python')
except Book.DoesNotExist:
self.fail(u'"Dive into Python" should exist on other database')
self.assertRaises(Book.DoesNotExist, Book.objects.get, title=u'Dive into Python')
self.assertRaises(Book.DoesNotExist, Book.objects.using(u'default').get, title=u'Dive into Python')
|
'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'default').get, published=datetime.date(2009, 5, 4))
dive = Book.objects.using(u'other').get(title__icontains=u'dive')
self.assertEqual(dive.title, u'Dive into Python')
self.assertRaises(Book.DoesNotExist, Book.objects.using(u'default').get, title__icontains=u'dive')
dive = Book.objects.using(u'other').get(title__iexact=u'dive INTO python')
self.assertEqual(dive.title, u'Dive into Python')
self.assertRaises(Book.DoesNotExist, Book.objects.using(u'default').get, title__iexact=u'dive INTO python')
dive = Book.objects.using(u'other').get(published__year=2009)
self.assertEqual(dive.title, u'Dive into Python')
self.assertEqual(dive.published, datetime.date(2009, 5, 4))
self.assertRaises(Book.DoesNotExist, Book.objects.using(u'default').get, published__year=2009)
years = Book.objects.using(u'other').dates(u'published', u'year')
self.assertEqual([o.year for o in years], [2009])
years = Book.objects.using(u'default').dates(u'published', u'year')
self.assertEqual([o.year for o in years], [])
months = Book.objects.using(u'other').dates(u'published', u'month')
self.assertEqual([o.month for o in months], [5])
months = Book.objects.using(u'default').dates(u'published', u'month')
self.assertEqual([o.month for o in months], [])
|
'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(name=u'Mark Pilgrim')
pro.authors = [marty]
dive.authors = [mark]
self.assertEqual(Book.authors.through.objects.using(u'default').count(), 1)
self.assertEqual(Book.authors.through.objects.using(u'other').count(), 1)
self.assertEqual(list(Book.objects.using(u'default').filter(authors__name=u'Marty Alchin').values_list(u'title', flat=True)), [u'Pro Django'])
self.assertEqual(list(Book.objects.using(u'other').filter(authors__name=u'Marty Alchin').values_list(u'title', flat=True)), [])
self.assertEqual(list(Book.objects.using(u'default').filter(authors__name=u'Mark Pilgrim').values_list(u'title', flat=True)), [])
self.assertEqual(list(Book.objects.using(u'other').filter(authors__name=u'Mark Pilgrim').values_list(u'title', flat=True)), [u'Dive into Python'])
dive = Book.objects.using(u'other').get(title=u'Dive into Python')
mark = Person.objects.using(u'other').get(name=u'Mark Pilgrim')
self.assertEqual(list(dive.authors.all().values_list(u'name', flat=True)), [u'Mark Pilgrim'])
self.assertEqual(list(mark.book_set.all().values_list(u'title', flat=True)), [u'Dive into Python'])
|
'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.objects.using(u'other').filter(authors__name=u'John Smith').values_list(u'title', flat=True)), [])
dive.authors.add(john)
self.assertEqual(list(Book.objects.using(u'other').filter(authors__name=u'Mark Pilgrim').values_list(u'title', flat=True)), [u'Dive into Python'])
self.assertEqual(list(Book.objects.using(u'other').filter(authors__name=u'John Smith').values_list(u'title', flat=True)), [u'Dive into Python'])
dive.authors.remove(john)
self.assertEqual(list(Book.objects.using(u'other').filter(authors__name=u'Mark Pilgrim').values_list(u'title', flat=True)), [u'Dive into Python'])
self.assertEqual(list(Book.objects.using(u'other').filter(authors__name=u'John Smith').values_list(u'title', flat=True)), [])
dive.authors.clear()
self.assertEqual(list(Book.objects.using(u'other').filter(authors__name=u'Mark Pilgrim').values_list(u'title', flat=True)), [])
self.assertEqual(list(Book.objects.using(u'other').filter(authors__name=u'John Smith').values_list(u'title', flat=True)), [])
dive.authors.create(name=u'Jane Brown')
self.assertEqual(list(Book.objects.using(u'other').filter(authors__name=u'Mark Pilgrim').values_list(u'title', flat=True)), [])
self.assertEqual(list(Book.objects.using(u'other').filter(authors__name=u'Jane Brown').values_list(u'title', flat=True)), [u'Dive into Python'])
|
'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.date(2005, 11, 1))
mark.book_set.add(grease)
self.assertEqual(list(Person.objects.using(u'other').filter(book__title=u'Dive into Python').values_list(u'name', flat=True)), [u'Mark Pilgrim'])
self.assertEqual(list(Person.objects.using(u'other').filter(book__title=u'Greasemonkey Hacks').values_list(u'name', flat=True)), [u'Mark Pilgrim'])
mark.book_set.remove(grease)
self.assertEqual(list(Person.objects.using(u'other').filter(book__title=u'Dive into Python').values_list(u'name', flat=True)), [u'Mark Pilgrim'])
self.assertEqual(list(Person.objects.using(u'other').filter(book__title=u'Greasemonkey Hacks').values_list(u'name', flat=True)), [])
mark.book_set.clear()
self.assertEqual(list(Person.objects.using(u'other').filter(book__title=u'Dive into Python').values_list(u'name', flat=True)), [])
self.assertEqual(list(Person.objects.using(u'other').filter(book__title=u'Greasemonkey Hacks').values_list(u'name', flat=True)), [])
mark.book_set.create(title=u'Dive into HTML5', published=datetime.date(2020, 1, 1))
self.assertEqual(list(Person.objects.using(u'other').filter(book__title=u'Dive into Python').values_list(u'name', flat=True)), [])
self.assertEqual(list(Person.objects.using(u'other').filter(book__title=u'Dive into HTML5').values_list(u'name', flat=True)), [u'Mark Pilgrim'])
|
'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(name=u'Mark Pilgrim')
try:
marty.book_set = [pro, dive]
self.fail(u"Shouldn't be able to assign across databases")
except ValueError:
pass
try:
marty.book_set.add(dive)
self.fail(u"Shouldn't be able to assign across databases")
except ValueError:
pass
try:
marty.book_set = [pro, dive]
self.fail(u"Shouldn't be able to assign across databases")
except ValueError:
pass
try:
dive.authors.add(marty)
self.fail(u"Shouldn't be able to assign across databases")
except ValueError:
pass
try:
dive.authors = [mark, marty]
self.fail(u"Shouldn't be able to assign across databases")
except ValueError:
pass
|
'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.using(u'default').count(), 0)
self.assertEqual(Book.authors.through.objects.using(u'default').count(), 0)
self.assertEqual(Person.objects.using(u'other').count(), 1)
self.assertEqual(Book.objects.using(u'other').count(), 1)
self.assertEqual(Book.authors.through.objects.using(u'other').count(), 1)
dive.delete(using=u'other')
self.assertEqual(Person.objects.using(u'default').count(), 0)
self.assertEqual(Book.objects.using(u'default').count(), 0)
self.assertEqual(Book.authors.through.objects.using(u'default').count(), 0)
self.assertEqual(Person.objects.using(u'other').count(), 1)
self.assertEqual(Book.objects.using(u'other').count(), 0)
self.assertEqual(Book.authors.through.objects.using(u'other').count(), 0)
dive = Book.objects.using(u'other').create(title=u'Dive into Python', published=datetime.date(2009, 5, 4))
dive.authors = [mark]
self.assertEqual(Person.objects.using(u'default').count(), 0)
self.assertEqual(Book.objects.using(u'default').count(), 0)
self.assertEqual(Book.authors.through.objects.using(u'default').count(), 0)
self.assertEqual(Person.objects.using(u'other').count(), 1)
self.assertEqual(Book.objects.using(u'other').count(), 1)
self.assertEqual(Book.authors.through.objects.using(u'other').count(), 1)
mark.delete(using=u'other')
self.assertEqual(Person.objects.using(u'default').count(), 0)
self.assertEqual(Book.objects.using(u'default').count(), 0)
self.assertEqual(Book.authors.through.objects.using(u'default').count(), 0)
self.assertEqual(Person.objects.using(u'other').count(), 0)
self.assertEqual(Book.objects.using(u'other').count(), 1)
self.assertEqual(Book.authors.through.objects.using(u'other').count(), 0)
|
'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(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')
pro.editor = george
pro.save()
dive.editor = chris
dive.save()
pro = Book.objects.using(u'default').get(title=u'Pro Django')
self.assertEqual(pro.editor.name, u'George Vilches')
dive = Book.objects.using(u'other').get(title=u'Dive into Python')
self.assertEqual(dive.editor.name, u'Chris Mills')
self.assertEqual(list(Person.objects.using(u'default').filter(edited__title=u'Pro Django').values_list(u'name', flat=True)), [u'George Vilches'])
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Pro Django').values_list(u'name', flat=True)), [])
self.assertEqual(list(Person.objects.using(u'default').filter(edited__title=u'Dive into Python').values_list(u'name', flat=True)), [])
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Dive into Python').values_list(u'name', flat=True)), [u'Chris Mills'])
chris = Person.objects.using(u'other').get(name=u'Chris Mills')
dive = Book.objects.using(u'other').get(title=u'Dive into Python')
self.assertEqual(list(chris.edited.values_list(u'title', flat=True)), [u'Dive into Python'])
|
'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 = Book.objects.using(u'other').create(title=u'Dive into HTML5', published=datetime.date(2010, 3, 15))
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Dive into HTML5').values_list(u'name', flat=True)), [])
chris.edited.add(html5)
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Dive into HTML5').values_list(u'name', flat=True)), [u'Chris Mills'])
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Dive into Python').values_list(u'name', flat=True)), [u'Chris Mills'])
chris.edited.remove(html5)
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Dive into HTML5').values_list(u'name', flat=True)), [])
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Dive into Python').values_list(u'name', flat=True)), [u'Chris Mills'])
chris.edited.clear()
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Dive into HTML5').values_list(u'name', flat=True)), [])
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Dive into Python').values_list(u'name', flat=True)), [])
chris.edited.create(title=u'Dive into Water', published=datetime.date(2010, 3, 15))
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Dive into HTML5').values_list(u'name', flat=True)), [])
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Dive into Water').values_list(u'name', flat=True)), [u'Chris Mills'])
self.assertEqual(list(Person.objects.using(u'other').filter(edited__title=u'Dive into Python').values_list(u'name', flat=True)), [])
|
'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(name=u'Mark Pilgrim')
try:
dive.editor = marty
self.fail(u"Shouldn't be able to assign across databases")
except ValueError:
pass
try:
marty.edited = [pro, dive]
self.fail(u"Shouldn't be able to assign across databases")
except ValueError:
pass
try:
marty.edited.add(dive)
self.fail(u"Shouldn't be able to assign across databases")
except ValueError:
pass
chris = Person(name=u'Chris Mills')
html5 = Book(title=u'Dive into HTML5', published=datetime.date(2010, 3, 15))
self.assertEqual(chris._state.db, None)
self.assertEqual(html5._state.db, None)
dive.editor = chris
html5.editor = mark
self.assertEqual(chris._state.db, u'other')
self.assertEqual(html5._state.db, u'other')
self.assertEqual(list(Person.objects.using(u'other').values_list(u'name', flat=True)), [u'Mark Pilgrim'])
self.assertEqual(list(Book.objects.using(u'other').values_list(u'title', flat=True)), [u'Dive into Python'])
chris.save()
html5.save()
self.assertEqual(list(Person.objects.using(u'default').values_list(u'name', flat=True)), [u'Marty Alchin'])
self.assertEqual(list(Person.objects.using(u'other').values_list(u'name', flat=True)), [u'Chris Mills', u'Mark Pilgrim'])
self.assertEqual(list(Book.objects.using(u'default').values_list(u'title', flat=True)), [u'Pro Django'])
self.assertEqual(list(Book.objects.using(u'other').values_list(u'title', flat=True)), [u'Dive into HTML5', u'Dive into Python'])
water = Book(title=u'Dive into Water', published=datetime.date(2001, 1, 1), editor=mark)
self.assertEqual(water._state.db, u'other')
self.assertEqual(list(Book.objects.using(u'default').values_list(u'title', flat=True)), [u'Pro Django'])
self.assertEqual(list(Book.objects.using(u'other').values_list(u'title', flat=True)), [u'Dive into HTML5', u'Dive into Python'])
water.save()
self.assertEqual(list(Book.objects.using(u'default').values_list(u'title', flat=True)), [u'Pro Django'])
self.assertEqual(list(Book.objects.using(u'other').values_list(u'title', flat=True)), [u'Dive into HTML5', u'Dive into Python', u'Dive into Water'])
|
'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'other').count(), 1)
self.assertEqual(Pet.objects.using(u'other').count(), 1)
mark.delete(using=u'other')
self.assertEqual(Person.objects.using(u'default').count(), 0)
self.assertEqual(Pet.objects.using(u'default').count(), 0)
self.assertEqual(Person.objects.using(u'other').count(), 0)
self.assertEqual(Pet.objects.using(u'other').count(), 0)
|
'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'[email protected]')
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'[email protected]')
bob_profile = UserProfile.objects.using(u'other').create(user=bob, flavor=u'crunchy frog')
alice = User.objects.using(u'default').get(username=u'alice')
self.assertEqual(alice.userprofile.flavor, u'chocolate')
bob = User.objects.using(u'other').get(username=u'bob')
self.assertEqual(bob.userprofile.flavor, u'crunchy frog')
self.assertEqual(list(User.objects.using(u'default').filter(userprofile__flavor=u'chocolate').values_list(u'username', flat=True)), [u'alice'])
self.assertEqual(list(User.objects.using(u'other').filter(userprofile__flavor=u'chocolate').values_list(u'username', flat=True)), [])
self.assertEqual(list(User.objects.using(u'default').filter(userprofile__flavor=u'crunchy frog').values_list(u'username', flat=True)), [])
self.assertEqual(list(User.objects.using(u'other').filter(userprofile__flavor=u'crunchy frog').values_list(u'username', flat=True)), [u'bob'])
alice_profile = UserProfile.objects.using(u'default').get(flavor=u'chocolate')
bob_profile = UserProfile.objects.using(u'other').get(flavor=u'crunchy frog')
self.assertEqual(alice_profile.user.username, u'alice')
self.assertEqual(bob_profile.user.username, u'bob')
|
'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'[email protected]')
bob = User.objects.db_manager(u'other').create_user(u'bob', u'[email protected]')
alice_profile = UserProfile.objects.using(u'default').create(user=alice, flavor=u'chocolate')
try:
bob.userprofile = alice_profile
self.fail(u"Shouldn't be able to assign across databases")
except ValueError:
pass
bob_profile = UserProfile.objects.using(u'other').create(user=bob, flavor=u'crunchy frog')
new_bob_profile = UserProfile(flavor=u'spring surprise')
charlie = User(pk=51, username=u'charlie', email=u'[email protected]')
charlie.set_unusable_password()
self.assertEqual(new_bob_profile._state.db, None)
self.assertEqual(charlie._state.db, None)
new_bob_profile.user = bob
charlie.userprofile = bob_profile
self.assertEqual(new_bob_profile._state.db, u'other')
self.assertEqual(charlie._state.db, u'other')
self.assertEqual(list(User.objects.using(u'other').values_list(u'username', flat=True)), [u'bob'])
self.assertEqual(list(UserProfile.objects.using(u'other').values_list(u'flavor', flat=True)), [u'crunchy frog'])
charlie.save()
bob_profile.save()
new_bob_profile.save()
self.assertEqual(list(User.objects.using(u'default').values_list(u'username', flat=True)), [u'alice'])
self.assertEqual(list(User.objects.using(u'other').values_list(u'username', flat=True)), [u'bob', u'charlie'])
self.assertEqual(list(UserProfile.objects.using(u'default').values_list(u'flavor', flat=True)), [u'chocolate'])
self.assertEqual(list(UserProfile.objects.using(u'other').values_list(u'flavor', flat=True)), [u'crunchy frog', u'spring surprise'])
denise = User.objects.db_manager(u'other').create_user(u'denise', u'[email protected]')
denise_profile = UserProfile(flavor=u'tofu', user=denise)
self.assertEqual(denise_profile._state.db, u'other')
self.assertEqual(list(UserProfile.objects.using(u'default').values_list(u'flavor', flat=True)), [u'chocolate'])
self.assertEqual(list(UserProfile.objects.using(u'other').values_list(u'flavor', flat=True)), [u'crunchy frog', u'spring surprise'])
denise_profile.save()
self.assertEqual(list(UserProfile.objects.using(u'default').values_list(u'flavor', flat=True)), [u'chocolate'])
self.assertEqual(list(UserProfile.objects.using(u'other').values_list(u'flavor', flat=True)), [u'crunchy frog', u'spring surprise', u'tofu'])
|
'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.objects.using(u'other').create(source=u'Python Weekly', content_object=dive)
review1 = Review.objects.using(u'default').get(source=u'Python Monthly')
self.assertEqual(review1.content_object.title, u'Pro Django')
review2 = Review.objects.using(u'other').get(source=u'Python Weekly')
self.assertEqual(review2.content_object.title, u'Dive into Python')
dive = Book.objects.using(u'other').get(title=u'Dive into Python')
self.assertEqual(list(dive.reviews.all().values_list(u'source', flat=True)), [u'Python Weekly'])
|
'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)
review2 = Review.objects.using(u'other').create(source=u'Python Monthly', content_object=temp)
self.assertEqual(list(Review.objects.using(u'default').filter(object_id=dive.pk).values_list(u'source', flat=True)), [])
self.assertEqual(list(Review.objects.using(u'other').filter(object_id=dive.pk).values_list(u'source', flat=True)), [u'Python Weekly'])
dive.reviews.add(review2)
self.assertEqual(list(Review.objects.using(u'default').filter(object_id=dive.pk).values_list(u'source', flat=True)), [])
self.assertEqual(list(Review.objects.using(u'other').filter(object_id=dive.pk).values_list(u'source', flat=True)), [u'Python Monthly', u'Python Weekly'])
dive.reviews.remove(review1)
self.assertEqual(list(Review.objects.using(u'default').filter(object_id=dive.pk).values_list(u'source', flat=True)), [])
self.assertEqual(list(Review.objects.using(u'other').filter(object_id=dive.pk).values_list(u'source', flat=True)), [u'Python Monthly'])
dive.reviews.clear()
self.assertEqual(list(Review.objects.using(u'default').filter(object_id=dive.pk).values_list(u'source', flat=True)), [])
self.assertEqual(list(Review.objects.using(u'other').filter(object_id=dive.pk).values_list(u'source', flat=True)), [])
dive.reviews.create(source=u'Python Daily')
self.assertEqual(list(Review.objects.using(u'default').filter(object_id=dive.pk).values_list(u'source', flat=True)), [])
self.assertEqual(list(Review.objects.using(u'other').filter(object_id=dive.pk).values_list(u'source', flat=True)), [u'Python Daily'])
|
'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.objects.using(u'other').create(source=u'Python Weekly', content_object=dive)
try:
review1.content_object = dive
self.fail(u"Shouldn't be able to assign across databases")
except ValueError:
pass
try:
dive.reviews.add(review1)
self.fail(u"Shouldn't be able to assign across databases")
except ValueError:
pass
review3 = Review(source=u'Python Daily')
self.assertEqual(review3._state.db, None)
review3.content_object = dive
self.assertEqual(review3._state.db, u'other')
self.assertEqual(list(Review.objects.using(u'default').filter(object_id=pro.pk).values_list(u'source', flat=True)), [u'Python Monthly'])
self.assertEqual(list(Review.objects.using(u'other').filter(object_id=dive.pk).values_list(u'source', flat=True)), [u'Python Weekly'])
review3.save()
self.assertEqual(list(Review.objects.using(u'default').filter(object_id=pro.pk).values_list(u'source', flat=True)), [u'Python Monthly'])
self.assertEqual(list(Review.objects.using(u'other').filter(object_id=dive.pk).values_list(u'source', flat=True)), [u'Python Daily', u'Python Weekly'])
|
'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.using(u'default').count(), 0)
self.assertEqual(Book.objects.using(u'other').count(), 1)
self.assertEqual(Review.objects.using(u'other').count(), 1)
dive.delete(using=u'other')
self.assertEqual(Book.objects.using(u'default').count(), 0)
self.assertEqual(Review.objects.using(u'default').count(), 0)
self.assertEqual(Book.objects.using(u'other').count(), 0)
self.assertEqual(Review.objects.using(u'other').count(), 0)
|
'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, 16))
self.assertEqual(learn.get_next_by_published().title, u'Dive into Python')
self.assertEqual(dive.get_previous_by_published().title, u'Learning Python')
|
'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 id FROM multiple_database_book').using(u'other')
self.assertQuerysetEqual(val, [dive.pk], attrgetter(u'pk'))
|
'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.assertEqual(book.editor._state.db, u'other')
|
'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:
pass
|
'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.create(title=u'Dive into Water', published=datetime.date(2009, 5, 4), extra_arg=True)
mark.edited.get_or_create(title=u'Dive into Water', published=datetime.date(2009, 5, 4), extra_arg=True)
|
'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_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 = [AuthRouter(), TestRouter()]
self.assertFalse(router.allow_syncdb(u'default', User))
self.assertTrue(router.allow_syncdb(u'default', Book))
self.assertTrue(router.allow_syncdb(u'other', User))
self.assertFalse(router.allow_syncdb(u'other', Book))
|
'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.db_for_write(Book), u'default')
self.assertTrue(router.allow_relation(dive, dive))
self.assertTrue(router.allow_syncdb(u'default', User))
self.assertTrue(router.allow_syncdb(u'default', Book))
router.routers = [WriteRouter(), AuthRouter(), TestRouter()]
self.assertEqual(router.db_for_read(User), u'default')
self.assertEqual(router.db_for_read(Book), u'other')
self.assertEqual(router.db_for_write(User), u'writer')
self.assertEqual(router.db_for_write(Book), u'writer')
self.assertTrue(router.allow_relation(dive, dive))
self.assertFalse(router.allow_syncdb(u'default', User))
self.assertTrue(router.allow_syncdb(u'default', Book))
|
'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 = Person.objects.using(u'other').create(name=u'Mark Pilgrim')
try:
dive.editor = marty
except ValueError:
self.fail(u'Assignment across master/slave databases with a common source should be ok')
self.assertEqual(marty._state.db, u'default')
self.assertEqual(pro._state.db, u'default')
self.assertEqual(dive._state.db, u'other')
self.assertEqual(mark._state.db, u'other')
dive.save()
self.assertEqual(dive._state.db, u'default')
try:
Book.objects.using(u'default').get(title=u'Dive into Python').delete()
except Book.DoesNotExist:
self.fail(u'Source database should have a copy of saved object')
dive = Book.objects.using(u'other').get(title=u'Dive into Python')
self.assertEqual(dive._state.db, u'other')
try:
marty.edited = [pro, dive]
except ValueError:
self.fail(u'Assignment across master/slave databases with a common source should be ok')
self.assertEqual(marty._state.db, u'default')
self.assertEqual(pro._state.db, u'default')
self.assertEqual(dive._state.db, u'default')
self.assertEqual(mark._state.db, u'other')
try:
Book.objects.using(u'default').get(title=u'Dive into Python').delete()
except Book.DoesNotExist:
self.fail(u'Source database should have a copy of saved object')
dive = Book.objects.using(u'other').get(title=u'Dive into Python')
self.assertEqual(dive._state.db, u'other')
try:
marty.edited.add(dive)
except ValueError:
self.fail(u'Assignment across master/slave databases with a common source should be ok')
self.assertEqual(marty._state.db, u'default')
self.assertEqual(pro._state.db, u'default')
self.assertEqual(dive._state.db, u'default')
self.assertEqual(mark._state.db, u'other')
try:
Book.objects.using(u'default').get(title=u'Dive into Python').delete()
except Book.DoesNotExist:
self.fail(u'Source database should have a copy of saved object')
dive = Book.objects.using(u'other').get(title=u'Dive into Python')
chris = Person(name=u'Chris Mills')
html5 = Book(title=u'Dive into HTML5', published=datetime.date(2010, 3, 15))
self.assertEqual(chris._state.db, None)
self.assertEqual(html5._state.db, None)
self.assertEqual(dive._state.db, u'other')
dive.editor = chris
html5.editor = mark
self.assertEqual(dive._state.db, u'other')
self.assertEqual(mark._state.db, u'other')
self.assertEqual(chris._state.db, u'default')
self.assertEqual(html5._state.db, u'default')
water = Book(title=u'Dive into Water', published=datetime.date(2001, 1, 1), editor=mark)
self.assertEqual(water._state.db, u'default')
mark.save(using=u'default')
mark.save(using=u'other')
self.assertEqual(mark._state.db, u'other')
cheesecake = mark.edited.create(title=u'Dive into Cheesecake', published=datetime.date(2010, 3, 15))
self.assertEqual(cheesecake._state.db, u'default')
(cheesecake, created) = mark.edited.get_or_create(title=u'Dive into Cheesecake', published=datetime.date(2010, 3, 15))
self.assertEqual(cheesecake._state.db, u'default')
(puddles, created) = mark.edited.get_or_create(title=u'Dive into Puddles', published=datetime.date(2010, 3, 15))
self.assertEqual(puddles._state.db, u'default')
|
'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))
mark = Person.objects.using(u'default').create(pk=2, name=u'Mark Pilgrim')
pro.save(using=u'default')
marty.save(using=u'default')
dive.save(using=u'other')
mark.save(using=u'other')
self.assertEqual(Book.objects.using(u'default').count(), 2)
self.assertEqual(Book.objects.using(u'other').count(), 2)
self.assertEqual(Person.objects.using(u'default').count(), 2)
self.assertEqual(Person.objects.using(u'other').count(), 2)
try:
marty.book_set = [pro, dive]
except ValueError:
self.fail(u'Assignment across master/slave databases with a common source should be ok')
self.assertEqual(marty._state.db, u'default')
self.assertEqual(pro._state.db, u'default')
self.assertEqual(dive._state.db, u'other')
self.assertEqual(mark._state.db, u'other')
self.assertEqual(Book.authors.through.objects.using(u'default').count(), 2)
self.assertEqual(Book.authors.through.objects.using(u'other').count(), 0)
Book.authors.through.objects.using(u'default').delete()
try:
marty.book_set.add(dive)
except ValueError:
self.fail(u'Assignment across master/slave databases with a common source should be ok')
self.assertEqual(marty._state.db, u'default')
self.assertEqual(pro._state.db, u'default')
self.assertEqual(dive._state.db, u'other')
self.assertEqual(mark._state.db, u'other')
self.assertEqual(Book.authors.through.objects.using(u'default').count(), 1)
self.assertEqual(Book.authors.through.objects.using(u'other').count(), 0)
Book.authors.through.objects.using(u'default').delete()
try:
dive.authors = [mark, marty]
except ValueError:
self.fail(u'Assignment across master/slave databases with a common source should be ok')
self.assertEqual(marty._state.db, u'default')
self.assertEqual(pro._state.db, u'default')
self.assertEqual(dive._state.db, u'other')
self.assertEqual(mark._state.db, u'other')
self.assertEqual(Book.authors.through.objects.using(u'default').count(), 2)
self.assertEqual(Book.authors.through.objects.using(u'other').count(), 0)
Book.authors.through.objects.using(u'default').delete()
self.assertEqual(Book.authors.through.objects.using(u'default').count(), 0)
self.assertEqual(Book.authors.through.objects.using(u'other').count(), 0)
try:
dive.authors.add(marty)
except ValueError:
self.fail(u'Assignment across master/slave databases with a common source should be ok')
self.assertEqual(marty._state.db, u'default')
self.assertEqual(pro._state.db, u'default')
self.assertEqual(dive._state.db, u'other')
self.assertEqual(mark._state.db, u'other')
self.assertEqual(Book.authors.through.objects.using(u'default').count(), 1)
self.assertEqual(Book.authors.through.objects.using(u'other').count(), 0)
alice = dive.authors.create(name=u'Alice')
self.assertEqual(alice._state.db, u'default')
(alice, created) = dive.authors.get_or_create(name=u'Alice')
self.assertEqual(alice._state.db, u'default')
(bob, created) = dive.authors.get_or_create(name=u'Bob')
self.assertEqual(bob._state.db, u'default')
|
'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'[email protected]')
bob = User.objects.db_manager(u'other').create_user(u'bob', u'[email protected]')
alice_profile = UserProfile.objects.create(user=alice, flavor=u'chocolate')
try:
bob.userprofile = alice_profile
except ValueError:
self.fail(u'Assignment across master/slave databases with a common source should be ok')
self.assertEqual(alice._state.db, u'default')
self.assertEqual(alice_profile._state.db, u'default')
self.assertEqual(bob._state.db, u'other')
bob.save()
self.assertEqual(bob._state.db, u'default')
|
'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(2009, 5, 4))
review2 = Review.objects.using(u'other').create(source=u'Python Weekly', content_object=dive)
try:
review1.content_object = dive
except ValueError:
self.fail(u'Assignment across master/slave databases with a common source should be ok')
self.assertEqual(pro._state.db, u'default')
self.assertEqual(review1._state.db, u'default')
self.assertEqual(dive._state.db, u'other')
self.assertEqual(review2._state.db, u'other')
dive.save()
self.assertEqual(review1._state.db, u'default')
self.assertEqual(dive._state.db, u'default')
try:
Book.objects.using(u'default').get(title=u'Dive into Python').delete()
except Book.DoesNotExist:
self.fail(u'Source database should have a copy of saved object')
dive = Book.objects.using(u'other').get(title=u'Dive into Python')
self.assertEqual(dive._state.db, u'other')
try:
dive.reviews.add(review1)
except ValueError:
self.fail(u'Assignment across master/slave databases with a common source should be ok')
self.assertEqual(pro._state.db, u'default')
self.assertEqual(review1._state.db, u'default')
self.assertEqual(dive._state.db, u'other')
self.assertEqual(review2._state.db, u'other')
dive.save()
self.assertEqual(dive._state.db, u'default')
try:
Book.objects.using(u'default').get(title=u'Dive into Python').delete()
except Book.DoesNotExist:
self.fail(u'Source database should have a copy of saved object')
review3 = Review(source=u'Python Daily')
self.assertEqual(review3._state.db, None)
review3.content_object = dive
self.assertEqual(review3._state.db, u'default')
dive = Book.objects.using(u'other').get(title=u'Dive into Python')
nyt = dive.reviews.create(source=u'New York Times', content_object=dive)
self.assertEqual(nyt._state.db, u'default')
|
'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.assertEqual(pro.authors.db_manager(u'default').db, u'default')
self.assertEqual(pro.authors.db_manager(u'default').all().db, u'default')
self.assertEqual(marty.book_set.db, u'other')
self.assertEqual(marty.book_set.db_manager(u'default').db, u'default')
self.assertEqual(marty.book_set.db_manager(u'default').all().db, u'default')
|
'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'default')
self.assertEqual(marty.edited.db_manager(u'default').all().db, u'default')
|
'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'default')
self.assertEqual(pro.reviews.db_manager(u'default').all().db, u'default')
|
'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.query)
self.assertEqual(list(qs.values_list(u'title', flat=True)), [u'Dive into Python'])
|
'The methods on the auth manager obey database hints'
| def test_auth_manager(self):
| User.objects.create_user(u'alice', u'[email protected]')
User.objects.db_manager(u'default').create_user(u'bob', u'[email protected]')
alice = User.objects.using(u'other').get(username=u'alice')
self.assertEqual(alice.username, u'alice')
self.assertEqual(alice._state.db, u'other')
self.assertRaises(User.DoesNotExist, User.objects.using(u'default').get, username=u'alice')
bob = User.objects.using(u'default').get(username=u'bob')
self.assertEqual(bob.username, u'bob')
self.assertEqual(bob._state.db, u'default')
self.assertRaises(User.DoesNotExist, User.objects.using(u'other').get, username=u'bob')
self.assertEqual(User.objects.using(u'default').count(), 1)
self.assertEqual(User.objects.using(u'other').count(), 1)
|
'Check that dumpdata honors allow_syncdb restrictions on the router'
| def test_dumpdata(self):
| User.objects.create_user(u'alice', u'[email protected]')
User.objects.db_manager(u'default').create_user(u'bob', u'[email protected]')
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()
self.assertEqual(command_output, u'[]')
new_io = StringIO()
management.call_command(u'dumpdata', u'auth', format=u'json', database=u'other', stdout=new_io)
command_output = new_io.getvalue().strip()
self.assertTrue((u'"email": "[email protected]"' in command_output))
|
'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, title=u'Pro Django')
try:
Book.objects.using(u'other').get(title=u'Dive into Python')
except Book.DoesNotExist:
self.fail(u'"Dive into Python" should exist on other database')
self.assertRaises(Book.DoesNotExist, Book.objects.get, title=u'Dive into Python')
self.assertRaises(Book.DoesNotExist, Book.objects.using(u'default').get, title=u'Dive into Python')
try:
Book.objects.get(title=u'The Definitive Guide to Django')
Book.objects.using(u'default').get(title=u'The Definitive Guide to Django')
Book.objects.using(u'other').get(title=u'The Definitive Guide to Django')
except Book.DoesNotExist:
self.fail(u'"The Definitive Guide to Django" should exist on both databases')
|
'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_receiver)
signals.pre_delete.connect(sender=Person, receiver=pre_delete_receiver)
signals.post_delete.connect(sender=Person, receiver=post_delete_receiver)
p = Person.objects.create(name=u'Darth Vader')
p.save()
self.assertEqual(pre_save_receiver._database, DEFAULT_DB_ALIAS)
self.assertEqual(post_save_receiver._database, DEFAULT_DB_ALIAS)
p.delete()
self.assertEqual(pre_delete_receiver._database, DEFAULT_DB_ALIAS)
self.assertEqual(post_delete_receiver._database, DEFAULT_DB_ALIAS)
p.save(using=u'other')
self.assertEqual(pre_save_receiver._database, u'other')
self.assertEqual(post_save_receiver._database, u'other')
p.delete(using=u'other')
self.assertEqual(pre_delete_receiver._database, u'other')
self.assertEqual(post_delete_receiver._database, u'other')
signals.pre_save.disconnect(sender=Person, receiver=pre_save_receiver)
signals.post_save.disconnect(sender=Person, receiver=post_save_receiver)
signals.pre_delete.disconnect(sender=Person, receiver=pre_delete_receiver)
signals.post_delete.disconnect(sender=Person, receiver=post_delete_receiver)
|
'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)
Person.objects.using(u'other').create(pk=p.pk, name=p.name)
b.authors.add(p)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
self._write_to_other()
b.authors.add(p)
self._write_to_default()
self.assertEqual(receiver._database, u'other')
b.authors.remove(p)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
self._write_to_other()
b.authors.remove(p)
self._write_to_default()
self.assertEqual(receiver._database, u'other')
p.book_set.add(b)
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
self._write_to_other()
p.book_set.add(b)
self._write_to_default()
self.assertEqual(receiver._database, u'other')
b.authors.clear()
self.assertEqual(receiver._database, DEFAULT_DB_ALIAS)
self._write_to_other()
b.authors.clear()
self._write_to_default()
self.assertEqual(receiver._database, u'other')
|
'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'other')
finally:
router.routers = old_routers
self.assertEqual(cts.count(), 0)
|
'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.create(place=p, serves_cocktails=False)
ug_bar.place = None
self.assertTrue((ug_bar.place is None))
self.assertRaises(ValueError, setattr, p, 'restaurant', None)
self.assertRaises(ValueError, setattr, p, 'restaurant', p)
p = Place.objects.get(name='Demon Dogs')
r = Restaurant(place=p)
self.assertTrue((r.place is p))
p = Place()
r = Restaurant(place=p)
self.assertTrue((r.place is p))
p = Place.objects.get(name='Demon Dogs')
r = Restaurant(place_id=p.id)
self.assertFalse((r.place is p))
self.assertEqual(r.place, p)
|
'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.assertQuerysetEqual(Target.objects.exclude(pointer2=None), [])
|
'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.undergroundbar
|
'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.objects.create()
with self.assertNumQueries(0):
with self.assertRaises(UndergroundBar.DoesNotExist):
p.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_function = (lambda obj: SIMPLE_FUNCTION)
article = Article(site=Site(domain=SITE_NAME), title=TITLE_TEXT, created=CREATED_DATE)
article.non_field = INSTANCE_ATTRIBUTE
verifications = ((u'site', SITE_NAME), (u'created', localize(CREATED_DATE)), (u'title', TITLE_TEXT), (u'get_admin_value', ADMIN_METHOD), (simple_function, SIMPLE_FUNCTION), (u'test_from_model', article.test_from_model()), (u'non_field', INSTANCE_ATTRIBUTE))
mock_admin = MockModelAdmin()
for (name, value) in verifications:
(field, attr, resolved_value) = lookup_field(name, article, mock_admin)
if (field is not None):
resolved_value = display_for_field(resolved_value, field)
self.assertEqual(value, resolved_value)
|
'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.DateField())
self.assertEqual(display_value, EMPTY_CHANGELIST_VALUE)
display_value = display_for_field(None, models.TimeField())
self.assertEqual(display_value, EMPTY_CHANGELIST_VALUE)
display_value = display_for_field(None, models.NullBooleanField())
expected = (u'<img src="%sadmin/img/icon-unknown.gif" alt="None" />' % settings.STATIC_URL)
self.assertEqual(display_value, expected)
display_value = display_for_field(None, models.DecimalField())
self.assertEqual(display_value, EMPTY_CHANGELIST_VALUE)
display_value = display_for_field(None, models.FloatField())
self.assertEqual(display_value, EMPTY_CHANGELIST_VALUE)
|
'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'article')
self.assertEqual(label_for_field(u'__str__', Article), str(u'article'))
self.assertRaises(AttributeError, (lambda : label_for_field(u'unknown', Article)))
def test_callable(obj):
return u'nothing'
self.assertEqual(label_for_field(test_callable, Article), u'Test callable')
self.assertEqual(label_for_field(test_callable, Article, return_attr=True), (u'Test callable', test_callable))
self.assertEqual(label_for_field(u'test_from_model', Article), u'Test from model')
self.assertEqual(label_for_field(u'test_from_model', Article, return_attr=True), (u'Test from model', Article.test_from_model))
self.assertEqual(label_for_field(u'test_from_model_with_override', Article), u'not What you Expect')
self.assertEqual(label_for_field((lambda x: u'nothing'), Article), u'--')
class MockModelAdmin(object, ):
def test_from_model(self, obj):
return u'nothing'
test_from_model.short_description = u'not Really the Model'
self.assertEqual(label_for_field(u'test_from_model', Article, model_admin=MockModelAdmin), u'not Really the Model')
self.assertEqual(label_for_field(u'test_from_model', Article, model_admin=MockModelAdmin, return_attr=True), (u'not Really the Model', MockModelAdmin.test_from_model))
|
'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.models.DELETION
self.assertTrue(six.text_type(log_entry).startswith(u'Deleted '))
log_entry.action_flag = 4
self.assertEqual(six.text_type(log_entry), u'LogEntry Object')
|
'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 = PoemFormSet(data, instance=poet)
self.assertEqual(formset.is_valid(), False)
self.assertEqual(Poem.objects.count(), 0)
data[u'poem_set-0-DELETE'] = u'on'
formset = PoemFormSet(data, instance=poet)
self.assertEqual(formset.is_valid(), True)
formset.save()
self.assertEqual(Poem.objects.count(), 0)
|
'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'poem_set-0-poem': six.text_type(poem.id), u'poem_set-0-name': (u'x' * 1000)}
formset = PoemFormSet(data, instance=poet)
self.assertEqual(formset.is_valid(), False)
self.assertEqual(Poem.objects.count(), 1)
data[u'poem_set-0-DELETE'] = u'on'
formset = PoemFormSet(data, instance=poet)
self.assertEqual(formset.is_valid(), True)
formset.save()
self.assertEqual(Poem.objects.count(), 0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.