desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Test that a POST HTTPS request with a good referer is accepted'
def test_https_good_referer(self):
req = self._get_POST_request_with_token() req._is_secure = True req.META['HTTP_HOST'] = 'www.example.com' req.META['HTTP_REFERER'] = 'https://www.example.com/somepage' req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {}) self.assertEqual(None, req2)
'Test that a POST HTTPS request with a good referer is accepted where the referer contains no trailing slash'
def test_https_good_referer_2(self):
req = self._get_POST_request_with_token() req._is_secure = True req.META['HTTP_HOST'] = 'www.example.com' req.META['HTTP_REFERER'] = 'https://www.example.com' req2 = CsrfViewMiddleware().process_view(req, post_form_view, (), {}) self.assertEqual(None, req2)
'Year boundary tests (ticket #3689)'
def test_year_boundaries(self):
d = Donut.objects.create(name='Date Test 2007', baked_date=datetime.datetime(year=2007, month=12, day=31), consumed_at=datetime.datetime(year=2007, month=12, day=31, hour=23, minute=59, second=59)) d1 = Donut.objects.create(name='Date Test 2006', baked_date=datetime.datetime(year=2006, month=1, day=...
'Regression test for #10238: TextField values returned from the database should be unicode.'
def test_textfields_unicode(self):
d = Donut.objects.create(name=u'Jelly Donut', review=u'Outstanding') newd = Donut.objects.get(id=d.id) self.assertTrue(isinstance(newd.review, unicode))
'Regression test for #8354: the MySQL and Oracle backends should raise an error if given a timezone-aware datetime object.'
@skipIfDBFeature('supports_timezones') def test_error_on_timezone(self):
dt = datetime.datetime(2008, 8, 31, 16, 20, tzinfo=tzinfo.FixedOffset(0)) d = Donut(name='Bear claw', consumed_at=dt) self.assertRaises(ValueError, d.save)
'Regression test for #10970, auto_now_add for DateField should store a Python datetime.date, not a datetime.datetime'
def test_datefield_auto_now_add(self):
b = RumBaba.objects.create() self.assertTrue(isinstance(b.baked_timestamp, datetime.datetime)) self.assertTrue((isinstance(b.baked_date, datetime.date) and (not isinstance(b.baked_date, datetime.datetime))))
'Regression test for #1661 and #1662 Check that string form referencing of models works, both as pre and post reference, on all RelatedField types.'
def test_string_form_referencing(self):
f1 = Foo(name='Foo1') f1.save() f2 = Foo(name='Foo2') f2.save() w1 = Whiz(name='Whiz1') w1.save() b1 = Bar(name='Bar1', normal=f1, fwd=w1, back=f2) b1.save() self.assertEqual(b1.normal, f1) self.assertEqual(b1.fwd, w1) self.assertEqual(b1.back, f2) base1 = Base(name='Base...
'Regression tests for #3937 make sure we can use unicode characters in queries. If these tests fail on MySQL, it\'s a problem with the test setup. A properly configured UTF-8 database can handle this.'
def test_unicode_chars_in_queries(self):
fx = Foo(name='Bjorn', friend=u'Fran\xe7ois') fx.save() self.assertEqual(Foo.objects.get(friend__contains=u'\xe7'), fx) self.assertEqual(Foo.objects.get(friend__contains='\xc3\xa7'), fx)
'Regression tests for #5087 make sure we can perform queries on TextFields.'
def test_queries_on_textfields(self):
a = Article(name='Test', text='The quick brown fox jumps over the lazy dog.') a.save() self.assertEqual(Article.objects.get(text__exact='The quick brown fox jumps over the lazy dog.'), a) self.assertEqual(Article.objects.get(text__contains='quick brown ...
'Regression test for #708 "like" queries on IP address fields require casting to text (on PostgreSQL).'
def test_ipaddress_on_postgresql(self):
a = Article(name='IP test', text='The body', submitted_from='192.0.2.100') a.save() self.assertEqual(repr(Article.objects.filter(submitted_from__contains='192.0.2')), repr([a]))
'Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause Tests that the subselect works and returns results equivalent to a query with the IDs listed. Before the corresponding fix for this bug, this test passed in 1.1 and failed in 1.2-beta (trunk).'
def test_aggregates_in_where_clause(self):
qs = Book.objects.values('contact').annotate(Max('id')) qs = qs.order_by('contact').values_list('id__max', flat=True) books = Book.objects.order_by('id') qs1 = books.filter(id__in=qs) qs2 = books.filter(id__in=list(qs)) self.assertEqual(list(qs1), list(qs2))
'Regression test for #12822: DatabaseError: aggregates not allowed in WHERE clause Same as the above test, but evaluates the queryset for the subquery before it\'s used as a subquery. Before the corresponding fix for this bug, this test failed in both 1.1 and 1.2-beta (trunk).'
def test_aggregates_in_where_clause_pre_eval(self):
qs = Book.objects.values('contact').annotate(Max('id')) qs = qs.order_by('contact').values_list('id__max', flat=True) list(qs) books = Book.objects.order_by('id') qs1 = books.filter(id__in=qs) qs2 = books.filter(id__in=list(qs)) self.assertEqual(list(qs1), list(qs2))
'Regression test for #11916: Extra params + aggregation creates incorrect SQL.'
@skipUnlessDBFeature('supports_subqueries_in_group_by') def test_annotate_with_extra(self):
shortest_book_sql = '\n SELECT name\n FROM aggregation_regress_book b\n WHERE b.publisher_id = aggregation_regress_publisher.id\n ORDER BY b.pages\n ...
'Model saves should throw some signals.'
def test_model_signals(self):
a1 = Author(name='Neal Stephenson') self.assertEqual(self.get_signal_output(a1.save), ['pre_save signal, Neal Stephenson', 'post_save signal, Neal Stephenson', 'Is created']) b1 = Book(name='Snow Crash') self.assertEqual(self.get_signal_output(b1.save), ['pre_save signal, ...
'Assigning and removing to/from m2m shouldn\'t generate an m2m signal'
def test_m2m_signals(self):
b1 = Book(name='Snow Crash') self.get_signal_output(b1.save) a1 = Author(name='Neal Stephenson') self.get_signal_output(a1.save) self.assertEqual(self.get_signal_output(setattr, b1, 'authors', [a1]), []) self.assertEqual(self.get_signal_output(setattr, b1, 'authors', []), [])
'Even though the default manager filters out some records, we must still be able to save (particularly, save by updating existing records) those filtered instances. This is a regression test for #8990, #9527'
def test_filtered_default_manager(self):
related = RelatedModel.objects.create(name='xyzzy') obj = RestrictedModel.objects.create(name='hidden', related=related) obj.name = 'still hidden' obj.save() self.assertEqual(RestrictedModel.plain_manager.count(), 1)
'Deleting related objects should also not be distracted by a restricted manager on the related object. This is a regression test for #2698.'
def test_delete_related_on_filtered_manager(self):
related = RelatedModel.objects.create(name='xyzzy') for (name, public) in (('one', True), ('two', False), ('three', False)): RestrictedModel.objects.create(name=name, is_public=public, related=related) obj = RelatedModel.objects.get(name='xyzzy') obj.delete() self.assertEqual(len(RestrictedM...
'A save method that modifies the data in the object'
def save(self):
self.data = 666 super(ModifyingSaveData, self).save(raw)
'Test that the get_*_display() methods are added to the model instances.'
def test_get_display_methods(self):
place = self.form.save() self.assertEqual(place.get_state_display(), 'Georgia') self.assertEqual(place.get_state_req_display(), 'North Carolina')
'Test that required USStateFields throw appropriate errors.'
def test_required(self):
form = USPlaceForm({'state': 'GA', 'name': 'Place in GA'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['state_req'], [u'This field is required.'])
'Test that the empty option is there.'
def test_field_blank_option(self):
state_select_html = '<select name="state" id="id_state">\n<option value="">---------</option>\n<option value="AL">Alabama</option>\n<option value="AK">Alaska</option>\n<option value="AS">American Samoa</option>\n<option value="AZ">Arizona</option>\n<option value="AR">Arkansas</option>\n<o...
'Test that the full USPS code field is really the full list.'
def test_full_postal_code_list(self):
usps_select_html = '<select name="postal_code" id="id_postal_code">\n<option value="">---------</option>\n<option value="AL">Alabama</option>\n<option value="AK">Alaska</option>\n<option value="AS">American Samoa</option>\n<option value="AZ">Arizona</option>\n<option value="AR">Arkansas</...
'Rendering a template response triggers the post-render callbacks'
def test_post_callbacks(self):
post = [] def post1(obj): post.append('post1') def post2(obj): post.append('post2') response = SimpleTemplateResponse('first/test.html', {}) response.add_post_render_callback(post1) response.add_post_render_callback(post2) response.render() self.assertEqual('First temp...
'Tests that the correct template is identified as not existing when {% include %} specifies a template that does not exist.'
def test_include_missing_template(self):
(old_td, settings.TEMPLATE_DEBUG) = (settings.TEMPLATE_DEBUG, True) old_loaders = loader.template_source_loaders try: loader.template_source_loaders = (app_directories.Loader(),) load_name = 'test_include_error.html' r = None try: tmpl = loader.select_template([lo...
'Tests that the correct template is identified as not existing when {% extends %} specifies a template that does exist, but that template has an {% include %} of something that does not exist. See #12787.'
def test_extends_include_missing_baseloader(self):
(old_td, settings.TEMPLATE_DEBUG) = (settings.TEMPLATE_DEBUG, True) old_loaders = loader.template_source_loaders try: loader.template_source_loaders = (app_directories.Loader(),) load_name = 'test_extends_error.html' tmpl = loader.get_template(load_name) r = None try:...
'Same as test_extends_include_missing_baseloader, only tests behavior of the cached loader instead of BaseLoader.'
def test_extends_include_missing_cachedloader(self):
(old_td, settings.TEMPLATE_DEBUG) = (settings.TEMPLATE_DEBUG, True) old_loaders = loader.template_source_loaders try: cache_loader = cached.Loader(('',)) cache_loader._cached_loaders = (app_directories.Loader(),) loader.template_source_loaders = (cache_loader,) load_name = 't...
'Regression test for #15721, ``{% include %}`` and ``RequestContext`` not playing together nicely.'
def test_include_only(self):
ctx = RequestContext(self.fake_request, {'var': 'parent'}) self.assertEqual(template.Template('{% include "child" %}').render(ctx), 'parent') self.assertEqual(template.Template('{% include "child" only %}').render(ctx), 'none')
'A template can be loaded from an egg'
def test_existing(self):
settings.INSTALLED_APPS = ['egg_1'] (contents, template_name) = lts_egg('y.html') self.assertEqual(contents, 'y') self.assertEqual(template_name, 'egg:egg_1:templates/y.html')
'Loading any template on an empty egg should fail'
def test_empty(self):
settings.INSTALLED_APPS = ['egg_empty'] egg_loader = EggLoader() self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, 'not-existing.html')
'Template loading fails if the template is not in the egg'
def test_non_existing(self):
settings.INSTALLED_APPS = ['egg_1'] egg_loader = EggLoader() self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, 'not-existing.html')
'A template can be loaded from an egg'
def test_existing(self):
settings.INSTALLED_APPS = ['egg_1'] egg_loader = EggLoader() (contents, template_name) = egg_loader.load_template_source('y.html') self.assertEqual(contents, 'y') self.assertEqual(template_name, 'egg:egg_1:templates/y.html')
'Loading an existent template from an egg not included in INSTALLED_APPS should fail'
def test_not_installed(self):
settings.INSTALLED_APPS = [] egg_loader = EggLoader() self.assertRaises(TemplateDoesNotExist, egg_loader.load_template_source, 'y.html')
'Check that the template directories form part of the template cache key. Refs #13573'
def test_templatedir_caching(self):
(t1, name) = loader.find_template('test.html', (os.path.join(os.path.dirname(__file__), 'templates', 'first'),)) (t2, name) = loader.find_template('test.html', (os.path.join(os.path.dirname(__file__), 'templates', 'second'),)) self.assertNotEqual(t1.render(Context({})), t2.render(Context({})))
'can_delete should be passed to inlineformset factory.'
def test_can_delete(self):
response = self.client.get(self.change_url) inner_formset = response.context[(-1)]['inline_admin_formsets'][0].formset expected = InnerInline.can_delete actual = inner_formset.can_delete self.assertEqual(expected, actual, 'can_delete must be equal')
'Bug #13174.'
def test_readonly_stacked_inline_label(self):
holder = Holder.objects.create(dummy=42) inner = Inner.objects.create(holder=holder, dummy=42, readonly='') response = self.client.get(('/test_admin/admin/admin_inlines/holder/%i/' % holder.id)) self.assertContains(response, '<label>Inner readonly label:</label>')
'Autogenerated many-to-many inlines are displayed correctly (#13407)'
def test_many_to_many_inlines(self):
response = self.client.get('/test_admin/admin/admin_inlines/author/add/') self.assertContains(response, '<h2>Author-book relationships</h2>') self.assertContains(response, 'Add another Author-Book Relationship') self.assertContains(response, 'id="id_Author_books-TOTAL_FORMS"')
'Ensure that non_field_errors are displayed correctly, including the right value for colspan. Refs #13510.'
def test_tabular_non_field_errors(self):
data = {'title_set-TOTAL_FORMS': 1, 'title_set-INITIAL_FORMS': 0, 'title_set-MAX_NUM_FORMS': 0, '_save': u'Save', 'title_set-0-title1': 'a title', 'title_set-0-title2': 'a different title'} response = self.client.post('/test_admin/admin/admin_inlines/titlecollection/add/', data) self.assertContains...
'Admin inline `readonly_field` shouldn\'t invoke parent ModelAdmin callable'
def test_no_parent_callable_lookup(self):
response = self.client.get('/test_admin/admin/admin_inlines/novel/add/') self.assertEqual(response.status_code, 200) self.assertContains(response, '<div class="inline-group" id="chapter_set-group">')
'Admin inline should invoke local callable when its name is listed in readonly_fields'
def test_callable_lookup(self):
response = self.client.get('/test_admin/admin/admin_inlines/poll/add/') self.assertEqual(response.status_code, 200) self.assertContains(response, '<div class="inline-group" id="question_set-group">') self.assertContains(response, '<p>Callable in QuestionInline</p>')
'Regression for #9362 The problem depends only on InlineAdminForm and its "original" argument, so we can safely set the other arguments to None/{}. We just need to check that the content_type argument of Child isn\'t altered by the internals of the inline form.'
def test_immutable_content_type(self):
sally = Teacher.objects.create(name='Sally') john = Parent.objects.create(name='John') joe = Child.objects.create(name='Joe', teacher=sally, parent=john) iaf = InlineAdminForm(None, None, {}, {}, joe) parent_ct = ContentType.objects.get_for_model(Parent) self.assertEqual(iaf.original.content_typ...
'Regression tests for #7314 and #7372'
def test_regression_7314_7372(self):
rm = RevisionableModel.objects.create(title='First Revision', when=datetime.datetime(2008, 9, 28, 10, 30, 0)) self.assertEqual(rm.pk, rm.base.pk) rm2 = rm.new_revision() rm2.title = 'Second Revision' rm.when = datetime.datetime(2008, 9, 28, 14, 25, 0) rm2.save() self.assertEqual(rm2.ti...
'Regression test for #7957: Combining extra() calls should leave the corresponding parameters associated with the right extra() bit. I.e. internal dictionary must remain sorted.'
def test_regression_7957(self):
self.assertEqual(User.objects.extra(select={'alpha': '%s'}, select_params=(1,)).extra(select={'beta': '%s'}, select_params=(2,))[0].alpha, 1) self.assertEqual(User.objects.extra(select={'beta': '%s'}, select_params=(1,)).extra(select={'alpha': '%s'}, select_params=(2,))[0].alpha, 2)
'Regression test for #7961: When not using a portion of an extra(...) in a query, remove any corresponding parameters from the query as well.'
def test_regression_7961(self):
self.assertEqual(list(User.objects.extra(select={'alpha': '%s'}, select_params=((-6),)).filter(id=self.u.id).values_list('id', flat=True)), [self.u.id])
'Regression test for #8063: limiting a query shouldn\'t discard any extra() bits.'
def test_regression_8063(self):
qs = User.objects.all().extra(where=['id=%s'], params=[self.u.id]) self.assertQuerysetEqual(qs, ['<User: fred>']) self.assertQuerysetEqual(qs[:1], ['<User: fred>'])
'Regression test for #8039: Ordering sometimes removed relevant tables from extra(). This test is the critical case: ordering uses a table, but then removes the reference because of an optimisation. The table should still be present because of the extra() call.'
def test_regression_8039(self):
self.assertQuerysetEqual(Order.objects.extra(where=['username=%s'], params=['fred'], tables=['auth_user']).order_by('created_by'), [])
'Regression test for #8819: Fields in the extra(select=...) list should be available to extra(order_by=...).'
def test_regression_8819(self):
self.assertQuerysetEqual(User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}).distinct(), ['<User: fred>']) self.assertQuerysetEqual(User.objects.filter(pk=self.u.id).extra(select={'extra_field': 1}, order_by=['extra_field']), ['<User: fred>']) self.assertQuerysetEqual(User.objects.filte...
'When calling the dates() method on a queryset with extra selection columns, we can (and should) ignore those columns. They don\'t change the result and cause incorrect SQL to be produced otherwise.'
def test_dates_query(self):
rm = RevisionableModel.objects.create(title='First Revision', when=datetime.datetime(2008, 9, 28, 10, 30, 0)) self.assertQuerysetEqual(RevisionableModel.objects.extra(select={'the_answer': 'id'}).dates('when', 'month'), ['datetime.datetime(2008, 9, 1, 0, 0)'])
'Regression test for #10256... If there is a values() clause, Extra columns are only returned if they are explicitly mentioned.'
def test_values_with_extra(self):
obj = TestObject(first='first', second='second', third='third') obj.save() self.assertEqual(list(TestObject.objects.extra(select=SortedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values()), [{'bar': u'second', 'third': u'third', 'second': u'second', 'whiz': u'third', 'foo': u'first', 'id...
'Regression for #10847: the list of extra columns can always be accurately evaluated. Using an inner query ensures that as_sql() is producing correct output without requiring full evaluation and execution of the inner query.'
def test_regression_10847(self):
obj = TestObject(first='first', second='second', third='third') obj.save() self.assertEqual(list(TestObject.objects.extra(select={'extra': 1}).values('pk')), [{'pk': obj.pk}]) self.assertQuerysetEqual(TestObject.objects.filter(pk__in=TestObject.objects.extra(select={'extra': 1}).values('pk')), ['<TestOb...
'This is a regression test for ticket #3790.'
def test_duplicate_pk(self):
management.call_command('loaddata', 'sequence', verbosity=0, commit=False) animal = Animal(name='Platypus', latin_name='Ornithorhynchus anatinus', count=2, weight=2.2) animal.save() self.assertGreater(animal.id, 1)
'Regression test for ticket #4558 -- pretty printing of XML fixtures doesn\'t affect parsing of None values.'
@skipIfDBFeature('interprets_empty_strings_as_nulls') def test_pretty_print_xml(self):
management.call_command('loaddata', 'pretty.xml', verbosity=0, commit=False) self.assertEqual(Stuff.objects.all()[0].name, None) self.assertEqual(Stuff.objects.all()[0].owner, None)
'Regression test for ticket #4558 -- pretty printing of XML fixtures doesn\'t affect parsing of None values.'
@skipUnlessDBFeature('interprets_empty_strings_as_nulls') def test_pretty_print_xml_empty_strings(self):
management.call_command('loaddata', 'pretty.xml', verbosity=0, commit=False) self.assertEqual(Stuff.objects.all()[0].name, u'') self.assertEqual(Stuff.objects.all()[0].owner, None)
'Regression test for ticket #6436 -- os.path.join will throw away the initial parts of a path if it encounters an absolute path. This means that if a fixture is specified as an absolute path, we need to make sure we don\'t discover the absolute path in every fixture directory.'
def test_absolute_path(self):
load_absolute_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'absolute.json') management.call_command('loaddata', load_absolute_path, verbosity=0, commit=False) self.assertEqual(Absolute.load_count, 1)
'Test for ticket #4371 -- Loading data of an unknown format should fail Validate that error conditions are caught correctly'
def test_unknown_format(self):
stderr = StringIO() management.call_command('loaddata', 'bad_fixture1.unkn', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "Problem installing fixture 'bad_fixture1': unkn is not a known serialization format.\n")
'Test for ticket #4371 -- Loading a fixture file with invalid data using explicit filename. Validate that error conditions are caught correctly'
def test_invalid_data(self):
stderr = StringIO() management.call_command('loaddata', 'bad_fixture2.xml', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n")
'Test for ticket #4371 -- Loading a fixture file with invalid data without file extension. Validate that error conditions are caught correctly'
def test_invalid_data_no_ext(self):
stderr = StringIO() management.call_command('loaddata', 'bad_fixture2', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n")
'Test for ticket #4371 -- Loading a fixture file with no data returns an error. Validate that error conditions are caught correctly'
def test_empty(self):
stderr = StringIO() management.call_command('loaddata', 'empty', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "No fixture data found for 'empty'. (File format may be invalid.)\n")
'Test for ticket #4371 -- If any of the fixtures contain an error, loading is aborted. Validate that error conditions are caught correctly'
def test_abort_loaddata_on_error(self):
stderr = StringIO() management.call_command('loaddata', 'empty', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "No fixture data found for 'empty'. (File format may be invalid.)\n")
'(Regression for #9011 - error message is correct)'
def test_error_message(self):
stderr = StringIO() management.call_command('loaddata', 'bad_fixture2', 'animal', verbosity=0, commit=False, stderr=stderr) self.assertEqual(stderr.getvalue(), "No fixture data found for 'bad_fixture2'. (File format may be invalid.)\n")
'Test for ticket #7565 -- PostgreSQL sequence resetting checks shouldn\'t ascend to parent models when inheritance is used (since they are treated individually).'
def test_pg_sequence_resetting_checks(self):
management.call_command('loaddata', 'model-inheritance.json', verbosity=0, commit=False) self.assertEqual(Parent.objects.all()[0].id, 1) self.assertEqual(Child.objects.all()[0].id, 1)
'Test for ticket #7572 -- MySQL has a problem if the same connection is used to create tables, load data, and then query over that data. To compensate, we close the connection after running loaddata. This ensures that a new connection is opened when test queries are issued.'
def test_close_connection_after_loaddata(self):
management.call_command('loaddata', 'big-fixture.json', verbosity=0, commit=False) articles = Article.objects.exclude(id=9) self.assertEqual(list(articles.values_list('id', flat=True)), [1, 2, 3, 4, 5, 6, 7, 8]) self.assertEqual(list(articles.values_list('id', flat=True)), [1, 2, 3, 4, 5, 6, 7, 8])
'Test for tickets #8298, #9942 - Field values should be coerced into the correct type by the deserializer, not as part of the database write.'
def test_field_value_coerce(self):
global pre_save_checks pre_save_checks = [] signals.pre_save.connect(animal_pre_save_check) management.call_command('loaddata', 'animal.xml', verbosity=0, commit=False) self.assertEqual(pre_save_checks, [("Count = 42 (<type 'int'>)", "Weight = 1.2 (<type 'float'>)")]) sig...
'Regression for #11286 Ensure that dumpdata honors the default manager Dump the current contents of the database as a JSON fixture'
def test_dumpdata_uses_default_manager(self):
management.call_command('loaddata', 'animal.xml', verbosity=0, commit=False) management.call_command('loaddata', 'sequence.json', verbosity=0, commit=False) animal = Animal(name='Platypus', latin_name='Ornithorhynchus anatinus', count=2, weight=2.2) animal.save() stdout = StringIO() managemen...
'Regression for #11428 - Proxy models aren\'t included when you dumpdata'
def test_proxy_model_included(self):
stdout = StringIO() widget = Widget.objects.create(name='grommet') management.call_command('dumpdata', 'fixtures_regress.widget', 'fixtures_regress.widgetproxy', format='json', stdout=stdout) self.assertEqual(stdout.getvalue(), ('[{"pk": %d, "model": "fixtures_regress.widget", "fields": {...
'Test for ticket #13030 - Python based parser version natural keys deserialize with fk to inheriting model'
def test_nk_deserialize(self):
management.call_command('loaddata', 'model-inheritance.json', verbosity=0, commit=False) management.call_command('loaddata', 'nk-inheritance.json', verbosity=0, commit=False) self.assertEqual(NKChild.objects.get(pk=1).data, 'apple') self.assertEqual(RefToNKChild.objects.get(pk=1).nk_fk.data, 'apple')
'Test for ticket #13030 - XML version natural keys deserialize with fk to inheriting model'
def test_nk_deserialize_xml(self):
management.call_command('loaddata', 'model-inheritance.json', verbosity=0, commit=False) management.call_command('loaddata', 'nk-inheritance.json', verbosity=0, commit=False) management.call_command('loaddata', 'nk-inheritance2.xml', verbosity=0, commit=False) self.assertEqual(NKChild.objects.get(pk=2)....
'Check that natural key requirements are taken into account when serializing models'
def test_nk_on_serialize(self):
management.call_command('loaddata', 'forward_ref_lookup.json', verbosity=0, commit=False) stdout = StringIO() management.call_command('dumpdata', 'fixtures_regress.book', 'fixtures_regress.person', 'fixtures_regress.store', verbosity=0, format='json', use_natural_keys=True, stdout=stdout) self.assertEqu...
'Now lets check the dependency sorting explicitly It doesn\'t matter what order you mention the models Store *must* be serialized before then Person, and both must be serialized before Book.'
def test_dependency_sorting(self):
sorted_deps = sort_dependencies([('fixtures_regress', [Book, Person, Store])]) self.assertEqual(sorted_deps, [Store, Person, Book])
'Check that normal primary keys still work on a model with natural key capabilities'
def test_normal_pk(self):
management.call_command('loaddata', 'non_natural_1.json', verbosity=0, commit=False) management.call_command('loaddata', 'forward_ref_lookup.json', verbosity=0, commit=False) management.call_command('loaddata', 'non_natural_2.xml', verbosity=0, commit=False) books = Book.objects.all() self.assertEqu...
'Test that fixtures can be rolled back (ticket #11101).'
@skipUnlessDBFeature('supports_transactions') def test_ticket_11101(self):
ticket_11101 = transaction.commit_manually(self.ticket_11101) ticket_11101()
'Test that the request object is available in the template and that its attributes can\'t be overridden by GET and POST parameters (#3828).'
def test_request_attributes(self):
url = '/request_attrs/' response = self.client.get(url) self.assertContains(response, 'Have request') response = self.client.get(url) self.assertContains(response, 'Not secure') response = self.client.get(url, {'is_secure': 'blah'}) self.assertContains(response, 'Not secure') re...
'Tests that the session is not accessed simply by including the auth context processor'
def test_session_not_accessed(self):
response = self.client.get('/auth_processor_no_attr_access/') self.assertContains(response, 'Session not accessed')
'Tests that the session is accessed if the auth context processor is used and relevant attributes accessed.'
def test_session_is_accessed(self):
response = self.client.get('/auth_processor_attr_access/') self.assertContains(response, 'Session accessed')
'Test that the lazy objects returned behave just like the wrapped objects.'
def test_user_attrs(self):
self.client.login(username='super', password='secret') user = authenticate(username='super', password='secret') response = self.client.get('/auth_processor_user/') self.assertContains(response, 'unicode: super') self.assertContains(response, 'id: 100') self.assertContains(response, 'userna...
'Check that querysets will use the default 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('other').db, 'other') self.assertEqual(Book.objects.db_manager('other').db, 'other') self.assertEqual(Book.objects.db_manager('other').all().db, 'other')
'Objects created on the default database don\'t leak onto other databases'
def test_default_creation(self):
Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) dive = Book() dive.title = 'Dive into Python' dive.published = datetime.date(2009, 5, 4) dive.save() try: Book.objects.get(title='Pro Django') Book.objects.using('default').get(title='Pro ...
'Objects created on another database don\'t leak onto the default database'
def test_other_creation(self):
Book.objects.using('other').create(title='Pro Django', published=datetime.date(2008, 12, 16)) dive = Book() dive.title = 'Dive into Python' dive.published = datetime.date(2009, 5, 4) dive.save(using='other') try: Book.objects.using('other').get(title='Pro Django') except ...
'Queries are constrained to a single database'
def test_basic_queries(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) dive = Book.objects.using('other').get(published=datetime.date(2009, 5, 4)) self.assertEqual(dive.title, 'Dive into Python') self.assertRaises(Book.DoesNotExist, Book.objects.using('defau...
'M2M fields are constrained to a single database'
def test_m2m_separation(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name='Marty Alchin') dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='M...
'M2M forward manipulations are all constrained to a single DB'
def test_m2m_forward_operations(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='Mark Pilgrim') dive.authors = [mark] john = Person.objects.using('other').create(name='John Smith') self.assertEqual(list(Book.object...
'M2M reverse manipulations are all constrained to a single DB'
def test_m2m_reverse_operations(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='Mark Pilgrim') dive.authors = [mark] grease = Book.objects.using('other').create(title='Greasemonkey Hacks', published=datetime.date(2005...
'Operations that involve sharing M2M objects across databases raise an error'
def test_m2m_cross_database_protection(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name='Marty Alchin') dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='M...
'Cascaded deletions of m2m relations issue queries on the right database'
def test_m2m_deletion(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='Mark Pilgrim') dive.authors = [mark] self.assertEqual(Person.objects.using('default').count(), 0) self.assertEqual(Book.objects.using('d...
'FK fields are constrained to a single database'
def test_foreign_key_separation(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name='Marty Alchin') george = Person.objects.create(name='George Vilches') dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5...
'FK reverse manipulations are all constrained to a single DB'
def test_foreign_key_reverse_operations(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='Mark Pilgrim') chris = Person.objects.using('other').create(name='Chris Mills') dive.editor = chris dive.save() html5 = Book.obje...
'Operations that involve sharing FK objects across databases raise an error'
def test_foreign_key_cross_database_protection(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name='Marty Alchin') dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name='M...
'Cascaded deletions of Foreign Key relations issue queries on the right database'
def test_foreign_key_deletion(self):
mark = Person.objects.using('other').create(name='Mark Pilgrim') fido = Pet.objects.using('other').create(name='Fido', owner=mark) self.assertEqual(Person.objects.using('default').count(), 0) self.assertEqual(Pet.objects.using('default').count(), 0) self.assertEqual(Person.objects.using('other')....
'ForeignKey.validate() uses the correct database'
def test_foreign_key_validation(self):
mickey = Person.objects.using('other').create(name='Mickey') pluto = Pet.objects.using('other').create(name='Pluto', owner=mickey) self.assertEqual(None, pluto.full_clean())
'OneToOne fields are constrained to a single database'
def test_o2o_separation(self):
alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com') alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate') bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com') bob_profile = UserProfile.objects.using('other').c...
'Operations that involve sharing FK objects across databases raise an error'
def test_o2o_cross_database_protection(self):
alice = User.objects.db_manager('default').create_user('alice', 'alice@example.com') bob = User.objects.db_manager('other').create_user('bob', 'bob@example.com') alice_profile = UserProfile.objects.using('default').create(user=alice, flavor='chocolate') try: bob.userprofile = alice_profile ...
'Generic fields are constrained to a single database'
def test_generic_key_separation(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) review1 = Review.objects.create(source='Python Monthly', content_object=pro) dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) review2 = Review.objects....
'Generic reverse manipulations are all constrained to a single DB'
def test_generic_key_reverse_operations(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) temp = Book.objects.using('other').create(title='Temp', published=datetime.date(2009, 5, 4)) review1 = Review.objects.using('other').create(source='Python Weekly', content_object=dive) revie...
'Operations that involve sharing generic key objects across databases raise an error'
def test_generic_key_cross_database_protection(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) review1 = Review.objects.create(source='Python Monthly', content_object=pro) dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) review2 = Review.objects....
'Cascaded deletions of Generic Key relations issue queries on the right database'
def test_generic_key_deletion(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) review = Review.objects.using('other').create(source='Python Weekly', content_object=dive) self.assertEqual(Book.objects.using('default').count(), 0) self.assertEqual(Review.objects.using('d...
'get_next_by_XXX commands stick to a single database'
def test_ordering(self):
pro = Book.objects.create(title='Pro Django', published=datetime.date(2008, 12, 16)) dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) learn = Book.objects.using('other').create(title='Learning Python', published=datetime.date(2008, 7, 16)) ...
'test the raw() method across databases'
def test_raw(self):
dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4)) val = Book.objects.db_manager('other').raw('SELECT id FROM multiple_database_book') self.assertEqual(map((lambda o: o.pk), val), [dive.pk]) val = Book.objects.raw('SELECT id FROM...
'Database assignment is retained if an object is retrieved with select_related()'
def test_select_related(self):
mark = Person.objects.using('other').create(name='Mark Pilgrim') dive = Book.objects.using('other').create(title='Dive into Python', published=datetime.date(2009, 5, 4), editor=mark) book = Book.objects.using('other').select_related('editor').get(title='Dive into Python') self.assertEqual...
'Make sure as_sql works with subqueries and master/slave.'
def test_subquery(self):
sub = Person.objects.using('other').filter(name='fff') qs = Book.objects.filter(editor__in=sub) self.assertRaises(ValueError, str, qs.query) try: for obj in qs: pass self.fail('Iterating over query should raise ValueError') except ValueError: pass
'Related managers return managers, not querysets'
def test_related_manager(self):
mark = Person.objects.using('other').create(name='Mark Pilgrim') mark.book_set.create(title='Dive into Python', published=datetime.date(2009, 5, 4), extra_arg=True) mark.book_set.get_or_create(title='Dive into Python', published=datetime.date(2009, 5, 4), extra_arg=True) mark.edited.creat...
'Point all read operations on auth models to \'default\''
def db_for_read(self, model, **hints):
if (model._meta.app_label == 'auth'): return 'default' return None