hash
stringlengths
64
64
content
stringlengths
0
1.51M
6cfd3faf688f8267f81baa8a39932051f21cd9024d22b6cbae881de2a19a05a0
from django.db import models class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) friends = models.ManyToManyField('self') # A set of models that use a non-abstract inherited 'through' model. class ThroughBase(models.Model): person = models.ForeignKey(Person, models.CASCADE) b = models.ForeignKey('B', models.CASCADE) class Through(ThroughBase): extra = models.CharField(max_length=20) class B(models.Model): people = models.ManyToManyField(Person, through=Through)
f492faaccab2b33eee838f278c8d5beed793554c0e508f4985a59484298196cf
from django.test.runner import DiscoverRunner class CustomOptionsTestRunner(DiscoverRunner): def __init__(self, verbosity=1, interactive=True, failfast=True, option_a=None, option_b=None, option_c=None, **kwargs): super().__init__(verbosity=verbosity, interactive=interactive, failfast=failfast) self.option_a = option_a self.option_b = option_b self.option_c = option_c @classmethod def add_arguments(cls, parser): parser.add_argument('--option_a', '-a', default='1'), parser.add_argument('--option_b', '-b', default='2'), parser.add_argument('--option_c', '-c', default='3'), def run_tests(self, test_labels, extra_tests=None, **kwargs): print("%s:%s:%s" % (self.option_a, self.option_b, self.option_c))
401502fa2a3d7d8a0c270e3a6b823df0d9d83afdba00081f3128da358aaca362
import os from argparse import ArgumentParser from contextlib import contextmanager from unittest import TestSuite, TextTestRunner, defaultTestLoader, skipUnless from django.db import connections from django.test import SimpleTestCase from django.test.runner import DiscoverRunner from django.test.utils import captured_stdout from django.utils.version import PY37 @contextmanager def change_cwd(directory): current_dir = os.path.abspath(os.path.dirname(__file__)) new_dir = os.path.join(current_dir, directory) old_cwd = os.getcwd() os.chdir(new_dir) try: yield finally: os.chdir(old_cwd) class DiscoverRunnerTests(SimpleTestCase): @staticmethod def get_test_methods_names(suite): return [ t.__class__.__name__ + '.' + t._testMethodName for t in suite._tests ] def test_init_debug_mode(self): runner = DiscoverRunner() self.assertFalse(runner.debug_mode) def test_add_arguments_debug_mode(self): parser = ArgumentParser() DiscoverRunner.add_arguments(parser) ns = parser.parse_args([]) self.assertFalse(ns.debug_mode) ns = parser.parse_args(["--debug-mode"]) self.assertTrue(ns.debug_mode) def test_dotted_test_module(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests_sample'], ).countTestCases() self.assertEqual(count, 4) def test_dotted_test_class_vanilla_unittest(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests_sample.TestVanillaUnittest'], ).countTestCases() self.assertEqual(count, 1) def test_dotted_test_class_django_testcase(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests_sample.TestDjangoTestCase'], ).countTestCases() self.assertEqual(count, 1) def test_dotted_test_method_django_testcase(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests_sample.TestDjangoTestCase.test_sample'], ).countTestCases() self.assertEqual(count, 1) def test_pattern(self): count = DiscoverRunner( pattern="*_tests.py", ).build_suite(['test_runner_apps.sample']).countTestCases() self.assertEqual(count, 1) @skipUnless(PY37, 'unittest -k option requires Python 3.7 and later') def test_name_patterns(self): all_test_1 = [ 'DjangoCase1.test_1', 'DjangoCase2.test_1', 'SimpleCase1.test_1', 'SimpleCase2.test_1', 'UnittestCase1.test_1', 'UnittestCase2.test_1', ] all_test_2 = [ 'DjangoCase1.test_2', 'DjangoCase2.test_2', 'SimpleCase1.test_2', 'SimpleCase2.test_2', 'UnittestCase1.test_2', 'UnittestCase2.test_2', ] all_tests = sorted([*all_test_1, *all_test_2, 'UnittestCase2.test_3_test']) for pattern, expected in [ [['test_1'], all_test_1], [['UnittestCase1'], ['UnittestCase1.test_1', 'UnittestCase1.test_2']], [['*test'], ['UnittestCase2.test_3_test']], [['test*'], all_tests], [['test'], all_tests], [['test_1', 'test_2'], sorted([*all_test_1, *all_test_2])], [['test*1'], all_test_1], ]: with self.subTest(pattern): suite = DiscoverRunner( test_name_patterns=pattern ).build_suite(['test_runner_apps.simple']) self.assertEqual(expected, self.get_test_methods_names(suite)) def test_file_path(self): with change_cwd(".."): count = DiscoverRunner().build_suite( ['test_runner_apps/sample/'], ).countTestCases() self.assertEqual(count, 5) def test_empty_label(self): """ If the test label is empty, discovery should happen on the current working directory. """ with change_cwd("."): suite = DiscoverRunner().build_suite([]) self.assertEqual( suite._tests[0].id().split(".")[0], os.path.basename(os.getcwd()), ) def test_empty_test_case(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests_sample.EmptyTestCase'], ).countTestCases() self.assertEqual(count, 0) def test_discovery_on_package(self): count = DiscoverRunner().build_suite( ['test_runner_apps.sample.tests'], ).countTestCases() self.assertEqual(count, 1) def test_ignore_adjacent(self): """ When given a dotted path to a module, unittest discovery searches not just the module, but also the directory containing the module. This results in tests from adjacent modules being run when they should not. The discover runner avoids this behavior. """ count = DiscoverRunner().build_suite( ['test_runner_apps.sample.empty'], ).countTestCases() self.assertEqual(count, 0) def test_testcase_ordering(self): with change_cwd(".."): suite = DiscoverRunner().build_suite(['test_runner_apps/sample/']) self.assertEqual( suite._tests[0].__class__.__name__, 'TestDjangoTestCase', msg="TestDjangoTestCase should be the first test case") self.assertEqual( suite._tests[1].__class__.__name__, 'TestZimpleTestCase', msg="TestZimpleTestCase should be the second test case") # All others can follow in unspecified order, including doctests self.assertIn('DocTestCase', [t.__class__.__name__ for t in suite._tests[2:]]) def test_duplicates_ignored(self): """ Tests shouldn't be discovered twice when discovering on overlapping paths. """ base_app = 'forms_tests' sub_app = 'forms_tests.field_tests' with self.modify_settings(INSTALLED_APPS={'append': sub_app}): single = DiscoverRunner().build_suite([base_app]).countTestCases() dups = DiscoverRunner().build_suite([base_app, sub_app]).countTestCases() self.assertEqual(single, dups) def test_reverse(self): """ Reverse should reorder tests while maintaining the grouping specified by ``DiscoverRunner.reorder_by``. """ runner = DiscoverRunner(reverse=True) suite = runner.build_suite( test_labels=('test_runner_apps.sample', 'test_runner_apps.simple')) self.assertIn('test_runner_apps.simple', next(iter(suite)).id(), msg="Test labels should be reversed.") suite = runner.build_suite(test_labels=('test_runner_apps.simple',)) suite = tuple(suite) self.assertIn('DjangoCase', suite[0].id(), msg="Test groups should not be reversed.") self.assertIn('SimpleCase', suite[4].id(), msg="Test groups order should be preserved.") self.assertIn('DjangoCase2', suite[0].id(), msg="Django test cases should be reversed.") self.assertIn('SimpleCase2', suite[4].id(), msg="Simple test cases should be reversed.") self.assertIn('UnittestCase2', suite[8].id(), msg="Unittest test cases should be reversed.") self.assertIn('test_2', suite[0].id(), msg="Methods of Django cases should be reversed.") self.assertIn('test_2', suite[4].id(), msg="Methods of simple cases should be reversed.") self.assertIn('test_2', suite[9].id(), msg="Methods of unittest cases should be reversed.") def test_overridable_get_test_runner_kwargs(self): self.assertIsInstance(DiscoverRunner().get_test_runner_kwargs(), dict) def test_overridable_test_suite(self): self.assertEqual(DiscoverRunner().test_suite, TestSuite) def test_overridable_test_runner(self): self.assertEqual(DiscoverRunner().test_runner, TextTestRunner) def test_overridable_test_loader(self): self.assertEqual(DiscoverRunner().test_loader, defaultTestLoader) def test_tags(self): runner = DiscoverRunner(tags=['core']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 1) runner = DiscoverRunner(tags=['fast']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 2) runner = DiscoverRunner(tags=['slow']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 2) def test_exclude_tags(self): runner = DiscoverRunner(tags=['fast'], exclude_tags=['core']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 1) runner = DiscoverRunner(tags=['fast'], exclude_tags=['slow']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 0) runner = DiscoverRunner(exclude_tags=['slow']) self.assertEqual(runner.build_suite(['test_runner_apps.tagged.tests']).countTestCases(), 0) def test_tag_inheritance(self): def count_tests(**kwargs): suite = DiscoverRunner(**kwargs).build_suite(['test_runner_apps.tagged.tests_inheritance']) return suite.countTestCases() self.assertEqual(count_tests(tags=['foo']), 4) self.assertEqual(count_tests(tags=['bar']), 2) self.assertEqual(count_tests(tags=['baz']), 2) self.assertEqual(count_tests(tags=['foo'], exclude_tags=['bar']), 2) self.assertEqual(count_tests(tags=['foo'], exclude_tags=['bar', 'baz']), 1) self.assertEqual(count_tests(exclude_tags=['foo']), 0) def test_included_tags_displayed(self): runner = DiscoverRunner(tags=['foo', 'bar'], verbosity=2) with captured_stdout() as stdout: runner.build_suite(['test_runner_apps.tagged.tests']) self.assertIn('Including test tag(s): bar, foo.\n', stdout.getvalue()) def test_excluded_tags_displayed(self): runner = DiscoverRunner(exclude_tags=['foo', 'bar'], verbosity=3) with captured_stdout() as stdout: runner.build_suite(['test_runner_apps.tagged.tests']) self.assertIn('Excluding test tag(s): bar, foo.\n', stdout.getvalue()) class DiscoverRunnerGetDatabasesTests(SimpleTestCase): runner = DiscoverRunner(verbosity=2) skip_msg = 'Skipping setup of unused database(s): ' def get_databases(self, test_labels): suite = self.runner.build_suite(test_labels) with captured_stdout() as stdout: databases = self.runner.get_databases(suite) return databases, stdout.getvalue() def test_mixed(self): databases, output = self.get_databases(['test_runner_apps.databases.tests']) self.assertEqual(databases, set(connections)) self.assertNotIn(self.skip_msg, output) def test_all(self): databases, output = self.get_databases(['test_runner_apps.databases.tests.AllDatabasesTests']) self.assertEqual(databases, set(connections)) self.assertNotIn(self.skip_msg, output) def test_default_and_other(self): databases, output = self.get_databases([ 'test_runner_apps.databases.tests.DefaultDatabaseTests', 'test_runner_apps.databases.tests.OtherDatabaseTests', ]) self.assertEqual(databases, set(connections)) self.assertNotIn(self.skip_msg, output) def test_default_only(self): databases, output = self.get_databases(['test_runner_apps.databases.tests.DefaultDatabaseTests']) self.assertEqual(databases, {'default'}) self.assertIn(self.skip_msg + 'other', output) def test_other_only(self): databases, output = self.get_databases(['test_runner_apps.databases.tests.OtherDatabaseTests']) self.assertEqual(databases, {'other'}) self.assertIn(self.skip_msg + 'default', output) def test_no_databases_required(self): databases, output = self.get_databases(['test_runner_apps.databases.tests.NoDatabaseTests']) self.assertEqual(databases, set()) self.assertIn(self.skip_msg + 'default, other', output)
e5a27c447edc06f82e7fad260b7c2004b22dc5e37a90349339cf50cde4cfcb3d
from datetime import datetime from decimal import Decimal from django import forms from django.conf import settings from django.contrib.admin import helpers from django.contrib.admin.utils import ( NestedObjects, display_for_field, display_for_value, flatten, flatten_fieldsets, label_for_field, lookup_field, quote, ) from django.db import DEFAULT_DB_ALIAS, models from django.test import SimpleTestCase, TestCase, override_settings from django.utils.formats import localize from django.utils.safestring import mark_safe from .models import ( Article, Car, Count, Event, EventGuide, Location, Site, Vehicle, ) class NestedObjectsTests(TestCase): """ Tests for ``NestedObject`` utility collection. """ def setUp(self): self.n = NestedObjects(using=DEFAULT_DB_ALIAS) self.objs = [Count.objects.create(num=i) for i in range(5)] def _check(self, target): self.assertEqual(self.n.nested(lambda obj: obj.num), target) def _connect(self, i, j): self.objs[i].parent = self.objs[j] self.objs[i].save() def _collect(self, *indices): self.n.collect([self.objs[i] for i in indices]) def test_unrelated_roots(self): self._connect(2, 1) self._collect(0) self._collect(1) self._check([0, 1, [2]]) def test_siblings(self): self._connect(1, 0) self._connect(2, 0) self._collect(0) self._check([0, [1, 2]]) def test_non_added_parent(self): self._connect(0, 1) self._collect(0) self._check([0]) def test_cyclic(self): self._connect(0, 2) self._connect(1, 0) self._connect(2, 1) self._collect(0) self._check([0, [1, [2]]]) def test_queries(self): self._connect(1, 0) self._connect(2, 0) # 1 query to fetch all children of 0 (1 and 2) # 1 query to fetch all children of 1 and 2 (none) # Should not require additional queries to populate the nested graph. self.assertNumQueries(2, self._collect, 0) def test_on_delete_do_nothing(self): """ The nested collector doesn't query for DO_NOTHING objects. """ n = NestedObjects(using=DEFAULT_DB_ALIAS) objs = [Event.objects.create()] EventGuide.objects.create(event=objs[0]) with self.assertNumQueries(2): # One for Location, one for Guest, and no query for EventGuide n.collect(objs) def test_relation_on_abstract(self): """ NestedObjects.collect() doesn't trip (AttributeError) on the special notation for relations on abstract models (related_name that contains %(app_label)s and/or %(class)s) (#21846). """ n = NestedObjects(using=DEFAULT_DB_ALIAS) Car.objects.create() n.collect([Vehicle.objects.first()]) class UtilsTests(SimpleTestCase): empty_value = '-empty-' def test_values_from_lookup_field(self): """ Regression test for #12654: lookup_field """ SITE_NAME = 'example.com' TITLE_TEXT = 'Some title' CREATED_DATE = datetime.min ADMIN_METHOD = 'admin method' SIMPLE_FUNCTION = 'function' INSTANCE_ATTRIBUTE = 'attr' class MockModelAdmin: def get_admin_value(self, obj): return ADMIN_METHOD def simple_function(obj): return SIMPLE_FUNCTION site_obj = Site(domain=SITE_NAME) article = Article( site=site_obj, title=TITLE_TEXT, created=CREATED_DATE, ) article.non_field = INSTANCE_ATTRIBUTE verifications = ( ('site', SITE_NAME), ('created', localize(CREATED_DATE)), ('title', TITLE_TEXT), ('get_admin_value', ADMIN_METHOD), (simple_function, SIMPLE_FUNCTION), ('test_from_model', article.test_from_model()), ('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.empty_value) self.assertEqual(value, resolved_value) def test_null_display_for_field(self): """ Regression test for #12550: display_for_field should handle None value. """ display_value = display_for_field(None, models.CharField(), self.empty_value) self.assertEqual(display_value, self.empty_value) display_value = display_for_field(None, models.CharField( choices=( (None, "test_none"), ) ), self.empty_value) self.assertEqual(display_value, "test_none") display_value = display_for_field(None, models.DateField(), self.empty_value) self.assertEqual(display_value, self.empty_value) display_value = display_for_field(None, models.TimeField(), self.empty_value) self.assertEqual(display_value, self.empty_value) # Regression test for #13071: NullBooleanField has special # handling. display_value = display_for_field(None, models.NullBooleanField(), self.empty_value) expected = '<img src="%sadmin/img/icon-unknown.svg" alt="None">' % settings.STATIC_URL self.assertHTMLEqual(display_value, expected) display_value = display_for_field(None, models.BooleanField(null=True), self.empty_value) expected = '<img src="%sadmin/img/icon-unknown.svg" alt="None" />' % settings.STATIC_URL self.assertHTMLEqual(display_value, expected) display_value = display_for_field(None, models.DecimalField(), self.empty_value) self.assertEqual(display_value, self.empty_value) display_value = display_for_field(None, models.FloatField(), self.empty_value) self.assertEqual(display_value, self.empty_value) def test_number_formats_display_for_field(self): display_value = display_for_field(12345.6789, models.FloatField(), self.empty_value) self.assertEqual(display_value, '12345.6789') display_value = display_for_field(Decimal('12345.6789'), models.DecimalField(), self.empty_value) self.assertEqual(display_value, '12345.6789') display_value = display_for_field(12345, models.IntegerField(), self.empty_value) self.assertEqual(display_value, '12345') @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_number_formats_with_thousand_separator_display_for_field(self): display_value = display_for_field(12345.6789, models.FloatField(), self.empty_value) self.assertEqual(display_value, '12,345.6789') display_value = display_for_field(Decimal('12345.6789'), models.DecimalField(), self.empty_value) self.assertEqual(display_value, '12,345.6789') display_value = display_for_field(12345, models.IntegerField(), self.empty_value) self.assertEqual(display_value, '12,345') def test_list_display_for_value(self): display_value = display_for_value([1, 2, 3], self.empty_value) self.assertEqual(display_value, '1, 2, 3') display_value = display_for_value([1, 2, 'buckle', 'my', 'shoe'], self.empty_value) self.assertEqual(display_value, '1, 2, buckle, my, shoe') @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_list_display_for_value_boolean(self): self.assertEqual( display_for_value(True, '', boolean=True), '<img src="/static/admin/img/icon-yes.svg" alt="True">' ) self.assertEqual( display_for_value(False, '', boolean=True), '<img src="/static/admin/img/icon-no.svg" alt="False">' ) self.assertEqual(display_for_value(True, ''), 'True') self.assertEqual(display_for_value(False, ''), 'False') def test_label_for_field(self): """ Tests for label_for_field """ self.assertEqual( label_for_field("title", Article), "title" ) self.assertEqual( label_for_field("hist", Article), "History" ) self.assertEqual( label_for_field("hist", Article, return_attr=True), ("History", None) ) self.assertEqual( label_for_field("__str__", Article), "article" ) with self.assertRaisesMessage(AttributeError, "Unable to lookup 'unknown' on Article"): label_for_field("unknown", Article) def test_callable(obj): return "nothing" self.assertEqual( label_for_field(test_callable, Article), "Test callable" ) self.assertEqual( label_for_field(test_callable, Article, return_attr=True), ("Test callable", test_callable) ) self.assertEqual( label_for_field("test_from_model", Article), "Test from model" ) self.assertEqual( label_for_field("test_from_model", Article, return_attr=True), ("Test from model", Article.test_from_model) ) self.assertEqual( label_for_field("test_from_model_with_override", Article), "not What you Expect" ) self.assertEqual( label_for_field(lambda x: "nothing", Article), "--" ) self.assertEqual(label_for_field('site_id', Article), 'Site id') class MockModelAdmin: def test_from_model(self, obj): return "nothing" test_from_model.short_description = "not Really the Model" self.assertEqual( label_for_field("test_from_model", Article, model_admin=MockModelAdmin), "not Really the Model" ) self.assertEqual( label_for_field("test_from_model", Article, model_admin=MockModelAdmin, return_attr=True), ("not Really the Model", MockModelAdmin.test_from_model) ) def test_label_for_field_form_argument(self): class ArticleForm(forms.ModelForm): extra_form_field = forms.BooleanField() class Meta: fields = '__all__' model = Article self.assertEqual( label_for_field('extra_form_field', Article, form=ArticleForm()), 'Extra form field' ) msg = "Unable to lookup 'nonexistent' on Article or ArticleForm" with self.assertRaisesMessage(AttributeError, msg): label_for_field('nonexistent', Article, form=ArticleForm()), def test_label_for_property(self): # NOTE: cannot use @property decorator, because of # AttributeError: 'property' object has no attribute 'short_description' class MockModelAdmin: def my_property(self): return "this if from property" my_property.short_description = 'property short description' test_from_property = property(my_property) self.assertEqual( label_for_field("test_from_property", Article, model_admin=MockModelAdmin), 'property short description' ) def test_related_name(self): """ Regression test for #13963 """ self.assertEqual( label_for_field('location', Event, return_attr=True), ('location', None), ) self.assertEqual( label_for_field('event', Location, return_attr=True), ('awesome event', None), ) self.assertEqual( label_for_field('guest', Event, return_attr=True), ('awesome guest', None), ) def test_safestring_in_field_label(self): # safestring should not be escaped class MyForm(forms.Form): text = forms.CharField(label=mark_safe('<i>text</i>')) cb = forms.BooleanField(label=mark_safe('<i>cb</i>')) form = MyForm() self.assertHTMLEqual(helpers.AdminField(form, 'text', is_first=False).label_tag(), '<label for="id_text" class="required inline"><i>text</i>:</label>') self.assertHTMLEqual(helpers.AdminField(form, 'cb', is_first=False).label_tag(), '<label for="id_cb" class="vCheckboxLabel required inline"><i>cb</i></label>') # normal strings needs to be escaped class MyForm(forms.Form): text = forms.CharField(label='&text') cb = forms.BooleanField(label='&cb') form = MyForm() self.assertHTMLEqual(helpers.AdminField(form, 'text', is_first=False).label_tag(), '<label for="id_text" class="required inline">&amp;text:</label>') self.assertHTMLEqual(helpers.AdminField(form, 'cb', is_first=False).label_tag(), '<label for="id_cb" class="vCheckboxLabel required inline">&amp;cb</label>') def test_flatten(self): flat_all = ['url', 'title', 'content', 'sites'] inputs = ( ((), []), (('url', 'title', ('content', 'sites')), flat_all), (('url', 'title', 'content', 'sites'), flat_all), ((('url', 'title'), ('content', 'sites')), flat_all) ) for orig, expected in inputs: self.assertEqual(flatten(orig), expected) def test_flatten_fieldsets(self): """ Regression test for #18051 """ fieldsets = ( (None, { 'fields': ('url', 'title', ('content', 'sites')) }), ) self.assertEqual(flatten_fieldsets(fieldsets), ['url', 'title', 'content', 'sites']) fieldsets = ( (None, { 'fields': ('url', 'title', ['content', 'sites']) }), ) self.assertEqual(flatten_fieldsets(fieldsets), ['url', 'title', 'content', 'sites']) def test_quote(self): self.assertEqual(quote('something\nor\nother'), 'something_0Aor_0Aother')
33261b022af44aa18973a659a51b3588e208b423900beb8354f8496825e11291
from django import forms from django.contrib import admin from .models import Article, ArticleProxy, Site class ArticleAdminForm(forms.ModelForm): nolabel_form_field = forms.BooleanField(required=False) class Meta: model = Article fields = ['title'] @property def changed_data(self): data = super().changed_data if data: # Add arbitrary name to changed_data to test # change message construction. return data + ['not_a_form_field'] return data class ArticleInline(admin.TabularInline): model = Article fields = ['title'] form = ArticleAdminForm class SiteAdmin(admin.ModelAdmin): inlines = [ArticleInline] site = admin.AdminSite(name='admin') site.register(Article) site.register(ArticleProxy) site.register(Site, SiteAdmin)
6ef19febb5307f8f7b285da58ecf2d675cdee1821e1f0dfa534211c97c86f2d7
import json from datetime import datetime from django.contrib.admin.models import ADDITION, CHANGE, DELETION, LogEntry from django.contrib.admin.utils import quote from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.test import TestCase, override_settings from django.urls import reverse from django.utils import translation from django.utils.html import escape from .models import Article, ArticleProxy, Site @override_settings(ROOT_URLCONF='admin_utils.urls') class LogEntryTests(TestCase): def setUp(self): self.user = User.objects.create_superuser(username='super', password='secret', email='[email protected]') self.site = Site.objects.create(domain='example.org') self.a1 = Article.objects.create( site=self.site, title="Title", created=datetime(2008, 3, 12, 11, 54), ) content_type_pk = ContentType.objects.get_for_model(Article).pk LogEntry.objects.log_action( self.user.pk, content_type_pk, self.a1.pk, repr(self.a1), CHANGE, change_message='Changed something' ) self.client.force_login(self.user) def test_logentry_save(self): """ LogEntry.action_time is a timestamp of the date when the entry was created. It shouldn't be updated on a subsequent save(). """ logentry = LogEntry.objects.get(content_type__model__iexact="article") action_time = logentry.action_time logentry.save() self.assertEqual(logentry.action_time, action_time) def test_logentry_change_message(self): """ LogEntry.change_message is stored as a dumped JSON structure to be able to get the message dynamically translated at display time. """ post_data = { 'site': self.site.pk, 'title': 'Changed', 'hist': 'Some content', 'created_0': '2008-03-12', 'created_1': '11:54', } change_url = reverse('admin:admin_utils_article_change', args=[quote(self.a1.pk)]) response = self.client.post(change_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_article_changelist')) logentry = LogEntry.objects.filter(content_type__model__iexact='article').latest('id') self.assertEqual(logentry.get_change_message(), 'Changed Title and History.') with translation.override('fr'): self.assertEqual(logentry.get_change_message(), 'Modification de Title et Historique.') add_url = reverse('admin:admin_utils_article_add') post_data['title'] = 'New' response = self.client.post(add_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_article_changelist')) logentry = LogEntry.objects.filter(content_type__model__iexact='article').latest('id') self.assertEqual(logentry.get_change_message(), 'Added.') with translation.override('fr'): self.assertEqual(logentry.get_change_message(), 'Ajout.') def test_logentry_change_message_not_json(self): """LogEntry.change_message was a string before Django 1.10.""" logentry = LogEntry(change_message='non-JSON string') self.assertEqual(logentry.get_change_message(), logentry.change_message) @override_settings(USE_L10N=True) def test_logentry_change_message_localized_datetime_input(self): """ Localized date/time inputs shouldn't affect changed form data detection. """ post_data = { 'site': self.site.pk, 'title': 'Changed', 'hist': 'Some content', 'created_0': '12/03/2008', 'created_1': '11:54', } with translation.override('fr'): change_url = reverse('admin:admin_utils_article_change', args=[quote(self.a1.pk)]) response = self.client.post(change_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_article_changelist')) logentry = LogEntry.objects.filter(content_type__model__iexact='article').latest('id') self.assertEqual(logentry.get_change_message(), 'Changed Title and History.') def test_logentry_change_message_formsets(self): """ All messages for changed formsets are logged in a change message. """ a2 = Article.objects.create( site=self.site, title="Title second article", created=datetime(2012, 3, 18, 11, 54), ) post_data = { 'domain': 'example.com', # domain changed 'admin_articles-TOTAL_FORMS': '5', 'admin_articles-INITIAL_FORMS': '2', 'admin_articles-MIN_NUM_FORMS': '0', 'admin_articles-MAX_NUM_FORMS': '1000', # Changed title for 1st article 'admin_articles-0-id': str(self.a1.pk), 'admin_articles-0-site': str(self.site.pk), 'admin_articles-0-title': 'Changed Title', # Second article is deleted 'admin_articles-1-id': str(a2.pk), 'admin_articles-1-site': str(self.site.pk), 'admin_articles-1-title': 'Title second article', 'admin_articles-1-DELETE': 'on', # A new article is added 'admin_articles-2-site': str(self.site.pk), 'admin_articles-2-title': 'Added article', } change_url = reverse('admin:admin_utils_site_change', args=[quote(self.site.pk)]) response = self.client.post(change_url, post_data) self.assertRedirects(response, reverse('admin:admin_utils_site_changelist')) self.assertQuerysetEqual(Article.objects.filter(pk=a2.pk), []) logentry = LogEntry.objects.filter(content_type__model__iexact='site').latest('action_time') self.assertEqual( json.loads(logentry.change_message), [ {"changed": {"fields": ["Domain"]}}, {"added": {"object": "Added article", "name": "article"}}, {"changed": {"fields": ["Title", "not_a_form_field"], "object": "Changed Title", "name": "article"}}, {"deleted": {"object": "Title second article", "name": "article"}}, ] ) self.assertEqual( logentry.get_change_message(), 'Changed Domain. Added article "Added article". ' 'Changed Title and not_a_form_field for article "Changed Title". ' 'Deleted article "Title second article".' ) with translation.override('fr'): self.assertEqual( logentry.get_change_message(), "Modification de Domain. Ajout de article « Added article ». " "Modification de Title et not_a_form_field pour l'objet " "article « Changed Title ». " "Suppression de article « Title second article »." ) def test_logentry_get_edited_object(self): """ LogEntry.get_edited_object() returns the edited object of a LogEntry object. """ logentry = LogEntry.objects.get(content_type__model__iexact="article") edited_obj = logentry.get_edited_object() self.assertEqual(logentry.object_id, str(edited_obj.pk)) def test_logentry_get_admin_url(self): """ LogEntry.get_admin_url returns a URL to edit the entry's object or None for nonexistent (possibly deleted) models. """ logentry = LogEntry.objects.get(content_type__model__iexact='article') expected_url = reverse('admin:admin_utils_article_change', args=(quote(self.a1.pk),)) self.assertEqual(logentry.get_admin_url(), expected_url) self.assertIn('article/%d/change/' % self.a1.pk, logentry.get_admin_url()) logentry.content_type.model = "nonexistent" self.assertIsNone(logentry.get_admin_url()) def test_logentry_unicode(self): log_entry = LogEntry() log_entry.action_flag = ADDITION self.assertTrue(str(log_entry).startswith('Added ')) log_entry.action_flag = CHANGE self.assertTrue(str(log_entry).startswith('Changed ')) log_entry.action_flag = DELETION self.assertTrue(str(log_entry).startswith('Deleted ')) # Make sure custom action_flags works log_entry.action_flag = 4 self.assertEqual(str(log_entry), 'LogEntry Object') def test_logentry_repr(self): logentry = LogEntry.objects.first() self.assertEqual(repr(logentry), str(logentry.action_time)) def test_log_action(self): content_type_pk = ContentType.objects.get_for_model(Article).pk log_entry = LogEntry.objects.log_action( self.user.pk, content_type_pk, self.a1.pk, repr(self.a1), CHANGE, change_message='Changed something else', ) self.assertEqual(log_entry, LogEntry.objects.latest('id')) def test_recentactions_without_content_type(self): """ If a LogEntry is missing content_type it will not display it in span tag under the hyperlink. """ response = self.client.get(reverse('admin:index')) link = reverse('admin:admin_utils_article_change', args=(quote(self.a1.pk),)) should_contain = """<a href="%s">%s</a>""" % (escape(link), escape(repr(self.a1))) self.assertContains(response, should_contain) should_contain = "Article" self.assertContains(response, should_contain) logentry = LogEntry.objects.get(content_type__model__iexact='article') # If the log entry doesn't have a content type it should still be # possible to view the Recent Actions part (#10275). logentry.content_type = None logentry.save() should_contain = should_contain.encode() counted_presence_before = response.content.count(should_contain) response = self.client.get(reverse('admin:index')) counted_presence_after = response.content.count(should_contain) self.assertEqual(counted_presence_before - 1, counted_presence_after) def test_proxy_model_content_type_is_used_for_log_entries(self): """ Log entries for proxy models should have the proxy model's contenttype (#21084). """ proxy_content_type = ContentType.objects.get_for_model(ArticleProxy, for_concrete_model=False) post_data = { 'site': self.site.pk, 'title': "Foo", 'hist': "Bar", 'created_0': '2015-12-25', 'created_1': '00:00', } changelist_url = reverse('admin:admin_utils_articleproxy_changelist') # add proxy_add_url = reverse('admin:admin_utils_articleproxy_add') response = self.client.post(proxy_add_url, post_data) self.assertRedirects(response, changelist_url) proxy_addition_log = LogEntry.objects.latest('id') self.assertEqual(proxy_addition_log.action_flag, ADDITION) self.assertEqual(proxy_addition_log.content_type, proxy_content_type) # change article_id = proxy_addition_log.object_id proxy_change_url = reverse('admin:admin_utils_articleproxy_change', args=(article_id,)) post_data['title'] = 'New' response = self.client.post(proxy_change_url, post_data) self.assertRedirects(response, changelist_url) proxy_change_log = LogEntry.objects.latest('id') self.assertEqual(proxy_change_log.action_flag, CHANGE) self.assertEqual(proxy_change_log.content_type, proxy_content_type) # delete proxy_delete_url = reverse('admin:admin_utils_articleproxy_delete', args=(article_id,)) response = self.client.post(proxy_delete_url, {'post': 'yes'}) self.assertRedirects(response, changelist_url) proxy_delete_log = LogEntry.objects.latest('id') self.assertEqual(proxy_delete_log.action_flag, DELETION) self.assertEqual(proxy_delete_log.content_type, proxy_content_type) def test_action_flag_choices(self): tests = ((1, 'Addition'), (2, 'Change'), (3, 'Deletion')) for action_flag, display_name in tests: with self.subTest(action_flag=action_flag): log = LogEntry(action_flag=action_flag) self.assertEqual(log.get_action_flag_display(), display_name)
de7437ae798513a5a0c73bfee4fff342488efda3817b4abd07ed854c365feed5
from django.urls import path from .admin import site urlpatterns = [ path('test_admin/admin/', site.urls), ]
795351c23eb535384a6f8f7fc1be49f27f20e2a25e94ff7c9ab54398e406a31d
from unittest import mock from django.db import transaction from django.test import TestCase, skipUnlessDBFeature from .models import ( Article, InheritedArticleA, InheritedArticleB, Publication, User, ) class ManyToManyTests(TestCase): def setUp(self): # Create a couple of Publications. self.p1 = Publication.objects.create(title='The Python Journal') self.p2 = Publication.objects.create(title='Science News') self.p3 = Publication.objects.create(title='Science Weekly') self.p4 = Publication.objects.create(title='Highlights for Children') self.a1 = Article.objects.create(headline='Django lets you build Web apps easily') self.a1.publications.add(self.p1) self.a2 = Article.objects.create(headline='NASA uses Python') self.a2.publications.add(self.p1, self.p2, self.p3, self.p4) self.a3 = Article.objects.create(headline='NASA finds intelligent life on Earth') self.a3.publications.add(self.p2) self.a4 = Article.objects.create(headline='Oxygen-free diet works wonders') self.a4.publications.add(self.p2) def test_add(self): # Create an Article. a5 = Article(headline='Django lets you create Web apps easily') # You can't associate it with a Publication until it's been saved. msg = ( '"<Article: Django lets you create Web apps easily>" needs to have ' 'a value for field "id" before this many-to-many relationship can be used.' ) with self.assertRaisesMessage(ValueError, msg): getattr(a5, 'publications') # Save it! a5.save() # Associate the Article with a Publication. a5.publications.add(self.p1) self.assertQuerysetEqual(a5.publications.all(), ['<Publication: The Python Journal>']) # Create another Article, and set it to appear in both Publications. a6 = Article(headline='ESA uses Python') a6.save() a6.publications.add(self.p1, self.p2) a6.publications.add(self.p3) # Adding a second time is OK a6.publications.add(self.p3) self.assertQuerysetEqual( a6.publications.all(), [ '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ] ) # Adding an object of the wrong type raises TypeError msg = "'Publication' instance expected, got <Article: Django lets you create Web apps easily>" with self.assertRaisesMessage(TypeError, msg): with transaction.atomic(): a6.publications.add(a5) # Add a Publication directly via publications.add by using keyword arguments. a6.publications.create(title='Highlights for Adults') self.assertQuerysetEqual( a6.publications.all(), [ '<Publication: Highlights for Adults>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ] ) def test_add_remove_set_by_pk(self): a5 = Article.objects.create(headline='Django lets you create Web apps easily') a5.publications.add(self.p1.pk) self.assertQuerysetEqual( a5.publications.all(), ['<Publication: The Python Journal>'], ) a5.publications.set([self.p2.pk]) self.assertQuerysetEqual( a5.publications.all(), ['<Publication: Science News>'], ) a5.publications.remove(self.p2.pk) self.assertQuerysetEqual(a5.publications.all(), []) def test_add_remove_set_by_to_field(self): user_1 = User.objects.create(username='Jean') user_2 = User.objects.create(username='Joe') a5 = Article.objects.create(headline='Django lets you create Web apps easily') a5.authors.add(user_1.username) self.assertQuerysetEqual(a5.authors.all(), ['<User: Jean>']) a5.authors.set([user_2.username]) self.assertQuerysetEqual(a5.authors.all(), ['<User: Joe>']) a5.authors.remove(user_2.username) self.assertQuerysetEqual(a5.authors.all(), []) def test_reverse_add(self): # Adding via the 'other' end of an m2m a5 = Article(headline='NASA finds intelligent life on Mars') a5.save() self.p2.article_set.add(a5) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA finds intelligent life on Mars>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(a5.publications.all(), ['<Publication: Science News>']) # Adding via the other end using keywords self.p2.article_set.create(headline='Carbon-free diet works wonders') self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: Carbon-free diet works wonders>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA finds intelligent life on Mars>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) a6 = self.p2.article_set.all()[3] self.assertQuerysetEqual( a6.publications.all(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ] ) @skipUnlessDBFeature('supports_ignore_conflicts') def test_fast_add_ignore_conflicts(self): """ A single query is necessary to add auto-created through instances if the database backend supports bulk_create(ignore_conflicts) and no m2m_changed signals receivers are connected. """ with self.assertNumQueries(1): self.a1.publications.add(self.p1, self.p2) @skipUnlessDBFeature('supports_ignore_conflicts') def test_slow_add_ignore_conflicts(self): manager_cls = self.a1.publications.__class__ # Simulate a race condition between the missing ids retrieval and # the bulk insertion attempt. missing_target_ids = {self.p1.id} # Disable fast-add to test the case where the slow add path is taken. add_plan = (True, False, False) with mock.patch.object(manager_cls, '_get_missing_target_ids', return_value=missing_target_ids) as mocked: with mock.patch.object(manager_cls, '_get_add_plan', return_value=add_plan): self.a1.publications.add(self.p1) mocked.assert_called_once() def test_related_sets(self): # Article objects have access to their related Publication objects. self.assertQuerysetEqual(self.a1.publications.all(), ['<Publication: The Python Journal>']) self.assertQuerysetEqual( self.a2.publications.all(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ] ) # Publication objects have access to their related Article objects. self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual( self.p1.article_set.all(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ] ) self.assertQuerysetEqual( Publication.objects.get(id=self.p4.id).article_set.all(), ['<Article: NASA uses Python>'] ) def test_selects(self): # We can perform kwarg queries across m2m relationships self.assertQuerysetEqual( Article.objects.filter(publications__id__exact=self.p1.id), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ]) self.assertQuerysetEqual( Article.objects.filter(publications__pk=self.p1.id), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ] ) self.assertQuerysetEqual( Article.objects.filter(publications=self.p1.id), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ] ) self.assertQuerysetEqual( Article.objects.filter(publications=self.p1), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA uses Python>', ] ) self.assertQuerysetEqual( Article.objects.filter(publications__title__startswith="Science"), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual( Article.objects.filter(publications__title__startswith="Science").distinct(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) # The count() function respects distinct() as well. self.assertEqual(Article.objects.filter(publications__title__startswith="Science").count(), 4) self.assertEqual(Article.objects.filter(publications__title__startswith="Science").distinct().count(), 3) self.assertQuerysetEqual( Article.objects.filter(publications__in=[self.p1.id, self.p2.id]).distinct(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ]) self.assertQuerysetEqual( Article.objects.filter(publications__in=[self.p1.id, self.p2]).distinct(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual( Article.objects.filter(publications__in=[self.p1, self.p2]).distinct(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) # Excluding a related item works as you would expect, too (although the SQL # involved is a little complex). self.assertQuerysetEqual( Article.objects.exclude(publications=self.p2), ['<Article: Django lets you build Web apps easily>'] ) def test_reverse_selects(self): # Reverse m2m queries are supported (i.e., starting at the table that # doesn't have a ManyToManyField). python_journal = ['<Publication: The Python Journal>'] self.assertQuerysetEqual(Publication.objects.filter(id__exact=self.p1.id), python_journal) self.assertQuerysetEqual(Publication.objects.filter(pk=self.p1.id), python_journal) self.assertQuerysetEqual( Publication.objects.filter(article__headline__startswith="NASA"), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual(Publication.objects.filter(article__id__exact=self.a1.id), python_journal) self.assertQuerysetEqual(Publication.objects.filter(article__pk=self.a1.id), python_journal) self.assertQuerysetEqual(Publication.objects.filter(article=self.a1.id), python_journal) self.assertQuerysetEqual(Publication.objects.filter(article=self.a1), python_journal) self.assertQuerysetEqual( Publication.objects.filter(article__in=[self.a1.id, self.a2.id]).distinct(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual( Publication.objects.filter(article__in=[self.a1.id, self.a2]).distinct(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual( Publication.objects.filter(article__in=[self.a1, self.a2]).distinct(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', '<Publication: The Python Journal>', ]) def test_delete(self): # If we delete a Publication, its Articles won't be able to access it. self.p1.delete() self.assertQuerysetEqual( Publication.objects.all(), [ '<Publication: Highlights for Children>', '<Publication: Science News>', '<Publication: Science Weekly>', ] ) self.assertQuerysetEqual(self.a1.publications.all(), []) # If we delete an Article, its Publications won't be able to access it. self.a2.delete() self.assertQuerysetEqual( Article.objects.all(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) def test_bulk_delete(self): # Bulk delete some Publications - references to deleted publications should go Publication.objects.filter(title__startswith='Science').delete() self.assertQuerysetEqual( Publication.objects.all(), [ '<Publication: Highlights for Children>', '<Publication: The Python Journal>', ] ) self.assertQuerysetEqual( Article.objects.all(), [ '<Article: Django lets you build Web apps easily>', '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual( self.a2.publications.all(), [ '<Publication: Highlights for Children>', '<Publication: The Python Journal>', ] ) # Bulk delete some articles - references to deleted objects should go q = Article.objects.filter(headline__startswith='Django') self.assertQuerysetEqual(q, ['<Article: Django lets you build Web apps easily>']) q.delete() # After the delete, the QuerySet cache needs to be cleared, # and the referenced objects should be gone self.assertQuerysetEqual(q, []) self.assertQuerysetEqual(self.p1.article_set.all(), ['<Article: NASA uses Python>']) def test_remove(self): # Removing publication from an article: self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', '<Article: Oxygen-free diet works wonders>', ] ) self.a4.publications.remove(self.p2) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: NASA uses Python>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), []) # And from the other end self.p2.article_set.remove(self.a3) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA uses Python>']) self.assertQuerysetEqual(self.a3.publications.all(), []) def test_set(self): self.p2.article_set.set([self.a4, self.a3]) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications.set([self.p3.id]) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science Weekly>']) self.p2.article_set.set([]) self.assertQuerysetEqual(self.p2.article_set.all(), []) self.a4.publications.set([]) self.assertQuerysetEqual(self.a4.publications.all(), []) self.p2.article_set.set([self.a4, self.a3], clear=True) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications.set([self.p3.id], clear=True) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science Weekly>']) self.p2.article_set.set([], clear=True) self.assertQuerysetEqual(self.p2.article_set.all(), []) self.a4.publications.set([], clear=True) self.assertQuerysetEqual(self.a4.publications.all(), []) def test_assign_forward(self): msg = ( "Direct assignment to the reverse side of a many-to-many set is " "prohibited. Use article_set.set() instead." ) with self.assertRaisesMessage(TypeError, msg): self.p2.article_set = [self.a4, self.a3] def test_assign_reverse(self): msg = ( "Direct assignment to the forward side of a many-to-many " "set is prohibited. Use publications.set() instead." ) with self.assertRaisesMessage(TypeError, msg): self.a1.publications = [self.p1, self.p2] def test_assign(self): # Relation sets can be assigned using set(). self.p2.article_set.set([self.a4, self.a3]) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications.set([self.p3.id]) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science Weekly>']) # An alternate to calling clear() is to set an empty set. self.p2.article_set.set([]) self.assertQuerysetEqual(self.p2.article_set.all(), []) self.a4.publications.set([]) self.assertQuerysetEqual(self.a4.publications.all(), []) def test_assign_ids(self): # Relation sets can also be set using primary key values self.p2.article_set.set([self.a4.id, self.a3.id]) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications.set([self.p3.id]) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science Weekly>']) def test_forward_assign_with_queryset(self): # Querysets used in m2m assignments are pre-evaluated so their value # isn't affected by the clearing operation in ManyRelatedManager.set() # (#19816). self.a1.publications.set([self.p1, self.p2]) qs = self.a1.publications.filter(title='The Python Journal') self.a1.publications.set(qs) self.assertEqual(1, self.a1.publications.count()) self.assertEqual(1, qs.count()) def test_reverse_assign_with_queryset(self): # Querysets used in M2M assignments are pre-evaluated so their value # isn't affected by the clearing operation in ManyRelatedManager.set() # (#19816). self.p1.article_set.set([self.a1, self.a2]) qs = self.p1.article_set.filter(headline='Django lets you build Web apps easily') self.p1.article_set.set(qs) self.assertEqual(1, self.p1.article_set.count()) self.assertEqual(1, qs.count()) def test_clear(self): # Relation sets can be cleared: self.p2.article_set.clear() self.assertQuerysetEqual(self.p2.article_set.all(), []) self.assertQuerysetEqual(self.a4.publications.all(), []) # And you can clear from the other end self.p2.article_set.add(self.a3, self.a4) self.assertQuerysetEqual( self.p2.article_set.all(), [ '<Article: NASA finds intelligent life on Earth>', '<Article: Oxygen-free diet works wonders>', ] ) self.assertQuerysetEqual(self.a4.publications.all(), ['<Publication: Science News>']) self.a4.publications.clear() self.assertQuerysetEqual(self.a4.publications.all(), []) self.assertQuerysetEqual(self.p2.article_set.all(), ['<Article: NASA finds intelligent life on Earth>']) def test_clear_after_prefetch(self): a4 = Article.objects.prefetch_related('publications').get(id=self.a4.id) self.assertQuerysetEqual(a4.publications.all(), ['<Publication: Science News>']) a4.publications.clear() self.assertQuerysetEqual(a4.publications.all(), []) def test_remove_after_prefetch(self): a4 = Article.objects.prefetch_related('publications').get(id=self.a4.id) self.assertQuerysetEqual(a4.publications.all(), ['<Publication: Science News>']) a4.publications.remove(self.p2) self.assertQuerysetEqual(a4.publications.all(), []) def test_add_after_prefetch(self): a4 = Article.objects.prefetch_related('publications').get(id=self.a4.id) self.assertEqual(a4.publications.count(), 1) a4.publications.add(self.p1) self.assertEqual(a4.publications.count(), 2) def test_set_after_prefetch(self): a4 = Article.objects.prefetch_related('publications').get(id=self.a4.id) self.assertEqual(a4.publications.count(), 1) a4.publications.set([self.p2, self.p1]) self.assertEqual(a4.publications.count(), 2) a4.publications.set([self.p1]) self.assertEqual(a4.publications.count(), 1) def test_add_then_remove_after_prefetch(self): a4 = Article.objects.prefetch_related('publications').get(id=self.a4.id) self.assertEqual(a4.publications.count(), 1) a4.publications.add(self.p1) self.assertEqual(a4.publications.count(), 2) a4.publications.remove(self.p1) self.assertQuerysetEqual(a4.publications.all(), ['<Publication: Science News>']) def test_inherited_models_selects(self): """ #24156 - Objects from child models where the parent's m2m field uses related_name='+' should be retrieved correctly. """ a = InheritedArticleA.objects.create() b = InheritedArticleB.objects.create() a.publications.add(self.p1, self.p2) self.assertQuerysetEqual( a.publications.all(), [ '<Publication: Science News>', '<Publication: The Python Journal>', ]) self.assertQuerysetEqual(b.publications.all(), []) b.publications.add(self.p3) self.assertQuerysetEqual( a.publications.all(), [ '<Publication: Science News>', '<Publication: The Python Journal>', ] ) self.assertQuerysetEqual(b.publications.all(), ['<Publication: Science Weekly>']) def test_custom_default_manager_exists_count(self): a5 = Article.objects.create(headline='deleted') a5.publications.add(self.p2) self.assertEqual(self.p2.article_set.count(), self.p2.article_set.all().count()) self.assertEqual(self.p3.article_set.exists(), self.p3.article_set.all().exists())
a50b6f678dc4fb87df0c96d8ad5998d8797fb396df32535399a4bd8e9cedbebd
""" Many-to-many relationships To define a many-to-many relationship, use ``ManyToManyField()``. In this example, an ``Article`` can be published in multiple ``Publication`` objects, and a ``Publication`` has multiple ``Article`` objects. """ from django.db import models class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ('title',) def __str__(self): return self.title class Tag(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50) def __str__(self): return self.name class NoDeletedArticleManager(models.Manager): def get_queryset(self): return super().get_queryset().exclude(headline='deleted') class Article(models.Model): headline = models.CharField(max_length=100) # Assign a string as name to make sure the intermediary model is # correctly created. Refs #20207 publications = models.ManyToManyField(Publication, name='publications') tags = models.ManyToManyField(Tag, related_name='tags') authors = models.ManyToManyField('User', through='UserArticle') objects = NoDeletedArticleManager() class Meta: ordering = ('headline',) def __str__(self): return self.headline class User(models.Model): username = models.CharField(max_length=20, unique=True) def __str__(self): return self.username class UserArticle(models.Model): user = models.ForeignKey(User, models.CASCADE, to_field='username') article = models.ForeignKey(Article, models.CASCADE) # Models to test correct related_name inheritance class AbstractArticle(models.Model): class Meta: abstract = True publications = models.ManyToManyField(Publication, name='publications', related_name='+') class InheritedArticleA(AbstractArticle): pass class InheritedArticleB(AbstractArticle): pass
a3e8cd7e322a39b94e7375c5931f1199b78cf63e7a69a94d702f534a17e3a404
from io import BytesIO from itertools import chain from urllib.parse import urlencode from django.core.exceptions import DisallowedHost from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.http import HttpRequest, RawPostDataException, UnreadablePostError from django.http.multipartparser import MultiPartParserError from django.http.request import HttpHeaders, split_domain_port from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.client import FakePayload class RequestsTests(SimpleTestCase): def test_httprequest(self): request = HttpRequest() self.assertEqual(list(request.GET), []) self.assertEqual(list(request.POST), []) self.assertEqual(list(request.COOKIES), []) self.assertEqual(list(request.META), []) # .GET and .POST should be QueryDicts self.assertEqual(request.GET.urlencode(), '') self.assertEqual(request.POST.urlencode(), '') # and FILES should be MultiValueDict self.assertEqual(request.FILES.getlist('foo'), []) self.assertIsNone(request.content_type) self.assertIsNone(request.content_params) def test_httprequest_full_path(self): request = HttpRequest() request.path = '/;some/?awful/=path/foo:bar/' request.path_info = '/prefix' + request.path request.META['QUERY_STRING'] = ';some=query&+query=string' expected = '/%3Bsome/%3Fawful/%3Dpath/foo:bar/?;some=query&+query=string' self.assertEqual(request.get_full_path(), expected) self.assertEqual(request.get_full_path_info(), '/prefix' + expected) def test_httprequest_full_path_with_query_string_and_fragment(self): request = HttpRequest() request.path = '/foo#bar' request.path_info = '/prefix' + request.path request.META['QUERY_STRING'] = 'baz#quux' self.assertEqual(request.get_full_path(), '/foo%23bar?baz#quux') self.assertEqual(request.get_full_path_info(), '/prefix/foo%23bar?baz#quux') def test_httprequest_repr(self): request = HttpRequest() request.path = '/somepath/' request.method = 'GET' request.GET = {'get-key': 'get-value'} request.POST = {'post-key': 'post-value'} request.COOKIES = {'post-key': 'post-value'} request.META = {'post-key': 'post-value'} self.assertEqual(repr(request), "<HttpRequest: GET '/somepath/'>") def test_httprequest_repr_invalid_method_and_path(self): request = HttpRequest() self.assertEqual(repr(request), "<HttpRequest>") request = HttpRequest() request.method = "GET" self.assertEqual(repr(request), "<HttpRequest>") request = HttpRequest() request.path = "" self.assertEqual(repr(request), "<HttpRequest>") def test_wsgirequest(self): request = WSGIRequest({ 'PATH_INFO': 'bogus', 'REQUEST_METHOD': 'bogus', 'CONTENT_TYPE': 'text/html; charset=utf8', 'wsgi.input': BytesIO(b''), }) self.assertEqual(list(request.GET), []) self.assertEqual(list(request.POST), []) self.assertEqual(list(request.COOKIES), []) self.assertEqual( set(request.META), {'PATH_INFO', 'REQUEST_METHOD', 'SCRIPT_NAME', 'CONTENT_TYPE', 'wsgi.input'} ) self.assertEqual(request.META['PATH_INFO'], 'bogus') self.assertEqual(request.META['REQUEST_METHOD'], 'bogus') self.assertEqual(request.META['SCRIPT_NAME'], '') self.assertEqual(request.content_type, 'text/html') self.assertEqual(request.content_params, {'charset': 'utf8'}) def test_wsgirequest_with_script_name(self): """ The request's path is correctly assembled, regardless of whether or not the SCRIPT_NAME has a trailing slash (#20169). """ # With trailing slash request = WSGIRequest({ 'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/PREFIX/somepath/') # Without trailing slash request = WSGIRequest({ 'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/PREFIX/somepath/') def test_wsgirequest_script_url_double_slashes(self): """ WSGI squashes multiple successive slashes in PATH_INFO, WSGIRequest should take that into account when populating request.path and request.META['SCRIPT_NAME'] (#17133). """ request = WSGIRequest({ 'SCRIPT_URL': '/mst/milestones//accounts/login//help', 'PATH_INFO': '/milestones/accounts/login/help', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/mst/milestones/accounts/login/help') self.assertEqual(request.META['SCRIPT_NAME'], '/mst') def test_wsgirequest_with_force_script_name(self): """ The FORCE_SCRIPT_NAME setting takes precedence over the request's SCRIPT_NAME environment parameter (#20169). """ with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'): request = WSGIRequest({ 'PATH_INFO': '/somepath/', 'SCRIPT_NAME': '/PREFIX/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) self.assertEqual(request.path, '/FORCED_PREFIX/somepath/') def test_wsgirequest_path_with_force_script_name_trailing_slash(self): """ The request's path is correctly assembled, regardless of whether or not the FORCE_SCRIPT_NAME setting has a trailing slash (#20169). """ # With trailing slash with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX/'): request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, '/FORCED_PREFIX/somepath/') # Without trailing slash with override_settings(FORCE_SCRIPT_NAME='/FORCED_PREFIX'): request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, '/FORCED_PREFIX/somepath/') def test_wsgirequest_repr(self): request = WSGIRequest({'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(repr(request), "<WSGIRequest: GET '/'>") request = WSGIRequest({'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) request.GET = {'get-key': 'get-value'} request.POST = {'post-key': 'post-value'} request.COOKIES = {'post-key': 'post-value'} request.META = {'post-key': 'post-value'} self.assertEqual(repr(request), "<WSGIRequest: GET '/somepath/'>") def test_wsgirequest_path_info(self): def wsgi_str(path_info, encoding='utf-8'): path_info = path_info.encode(encoding) # Actual URL sent by the browser (bytestring) path_info = path_info.decode('iso-8859-1') # Value in the WSGI environ dict (native string) return path_info # Regression for #19468 request = WSGIRequest({'PATH_INFO': wsgi_str("/سلام/"), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b'')}) self.assertEqual(request.path, "/سلام/") # The URL may be incorrectly encoded in a non-UTF-8 encoding (#26971) request = WSGIRequest({ 'PATH_INFO': wsgi_str("/café/", encoding='iso-8859-1'), 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), }) # Since it's impossible to decide the (wrong) encoding of the URL, it's # left percent-encoded in the path. self.assertEqual(request.path, "/caf%E9/") def test_limited_stream(self): # Read all of a limited stream stream = LimitedStream(BytesIO(b'test'), 2) self.assertEqual(stream.read(), b'te') # Reading again returns nothing. self.assertEqual(stream.read(), b'') # Read a number of characters greater than the stream has to offer stream = LimitedStream(BytesIO(b'test'), 2) self.assertEqual(stream.read(5), b'te') # Reading again returns nothing. self.assertEqual(stream.readline(5), b'') # Read sequentially from a stream stream = LimitedStream(BytesIO(b'12345678'), 8) self.assertEqual(stream.read(5), b'12345') self.assertEqual(stream.read(5), b'678') # Reading again returns nothing. self.assertEqual(stream.readline(5), b'') # Read lines from a stream stream = LimitedStream(BytesIO(b'1234\n5678\nabcd\nefgh\nijkl'), 24) # Read a full line, unconditionally self.assertEqual(stream.readline(), b'1234\n') # Read a number of characters less than a line self.assertEqual(stream.readline(2), b'56') # Read the rest of the partial line self.assertEqual(stream.readline(), b'78\n') # Read a full line, with a character limit greater than the line length self.assertEqual(stream.readline(6), b'abcd\n') # Read the next line, deliberately terminated at the line end self.assertEqual(stream.readline(4), b'efgh') # Read the next line... just the line end self.assertEqual(stream.readline(), b'\n') # Read everything else. self.assertEqual(stream.readline(), b'ijkl') # Regression for #15018 # If a stream contains a newline, but the provided length # is less than the number of provided characters, the newline # doesn't reset the available character count stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9) self.assertEqual(stream.readline(10), b'1234\n') self.assertEqual(stream.readline(3), b'abc') # Now expire the available characters self.assertEqual(stream.readline(3), b'd') # Reading again returns nothing. self.assertEqual(stream.readline(2), b'') # Same test, but with read, not readline. stream = LimitedStream(BytesIO(b'1234\nabcdef'), 9) self.assertEqual(stream.read(6), b'1234\na') self.assertEqual(stream.read(2), b'bc') self.assertEqual(stream.read(2), b'd') self.assertEqual(stream.read(2), b'') self.assertEqual(stream.read(), b'') def test_stream(self): payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload}, ) self.assertEqual(request.read(), b'name=value') def test_read_after_value(self): """ Reading from request is allowed after accessing request contents as POST or body. """ payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(request.POST, {'name': ['value']}) self.assertEqual(request.body, b'name=value') self.assertEqual(request.read(), b'name=value') def test_value_after_read(self): """ Construction of POST or body is not allowed after reading from request. """ payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(request.read(2), b'na') with self.assertRaises(RawPostDataException): request.body self.assertEqual(request.POST, {}) def test_non_ascii_POST(self): payload = FakePayload(urlencode({'key': 'España'})) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'wsgi.input': payload, }) self.assertEqual(request.POST, {'key': ['España']}) def test_alternate_charset_POST(self): """ Test a POST with non-utf-8 payload encoding. """ payload = FakePayload(urlencode({'key': 'España'.encode('latin-1')})) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': 'application/x-www-form-urlencoded; charset=iso-8859-1', 'wsgi.input': payload, }) self.assertEqual(request.POST, {'key': ['España']}) def test_body_after_POST_multipart_form_data(self): """ Reading body after parsing multipart/form-data is not allowed """ # Because multipart is used for large amounts of data i.e. file uploads, # we don't want the data held in memory twice, and we don't want to # silence the error by setting body = '' either. payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--' ''])) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(request.POST, {'name': ['value']}) with self.assertRaises(RawPostDataException): request.body def test_body_after_POST_multipart_related(self): """ Reading body after parsing multipart that isn't form-data is allowed """ # Ticket #9054 # There are cases in which the multipart data is related instead of # being a binary upload, in which case it should still be accessible # via body. payload_data = b"\r\n".join([ b'--boundary', b'Content-ID: id; name="name"', b'', b'value', b'--boundary--' b'']) payload = FakePayload(payload_data) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/related; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(request.POST, {}) self.assertEqual(request.body, payload_data) def test_POST_multipart_with_content_length_zero(self): """ Multipart POST requests with Content-Length >= 0 are valid and need to be handled. """ # According to: # https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.13 # Every request.POST with Content-Length >= 0 is a valid request, # this test ensures that we handle Content-Length == 0. payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--' ''])) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': 0, 'wsgi.input': payload, }) self.assertEqual(request.POST, {}) def test_POST_binary_only(self): payload = b'\r\n\x01\x00\x00\x00ab\x00\x00\xcd\xcc,@' environ = { 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/octet-stream', 'CONTENT_LENGTH': len(payload), 'wsgi.input': BytesIO(payload), } request = WSGIRequest(environ) self.assertEqual(request.POST, {}) self.assertEqual(request.FILES, {}) self.assertEqual(request.body, payload) # Same test without specifying content-type environ.update({'CONTENT_TYPE': '', 'wsgi.input': BytesIO(payload)}) request = WSGIRequest(environ) self.assertEqual(request.POST, {}) self.assertEqual(request.FILES, {}) self.assertEqual(request.body, payload) def test_read_by_lines(self): payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(list(request), [b'name=value']) def test_POST_after_body_read(self): """ POST should be populated even if body is read first """ payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) request.body # evaluate self.assertEqual(request.POST, {'name': ['value']}) def test_POST_after_body_read_and_stream_read(self): """ POST should be populated even if body is read first, and then the stream is read second. """ payload = FakePayload('name=value') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) request.body # evaluate self.assertEqual(request.read(1), b'n') self.assertEqual(request.POST, {'name': ['value']}) def test_POST_after_body_read_and_stream_read_multipart(self): """ POST should be populated even if body is read first, and then the stream is read second. Using multipart/form-data instead of urlencoded. """ payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--' ''])) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) request.body # evaluate # Consume enough data to mess up the parsing: self.assertEqual(request.read(13), b'--boundary\r\nC') self.assertEqual(request.POST, {'name': ['value']}) def test_POST_immutable_for_mutipart(self): """ MultiPartParser.parse() leaves request.POST immutable. """ payload = FakePayload("\r\n".join([ '--boundary', 'Content-Disposition: form-data; name="name"', '', 'value', '--boundary--', ])) request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertFalse(request.POST._mutable) def test_multipart_without_boundary(self): request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data;', 'CONTENT_LENGTH': 0, 'wsgi.input': FakePayload(), }) with self.assertRaisesMessage(MultiPartParserError, 'Invalid boundary in multipart: None'): request.POST def test_multipart_non_ascii_content_type(self): request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary = \xe0', 'CONTENT_LENGTH': 0, 'wsgi.input': FakePayload(), }) msg = 'Invalid non-ASCII Content-Type in multipart: multipart/form-data; boundary = à' with self.assertRaisesMessage(MultiPartParserError, msg): request.POST def test_POST_connection_error(self): """ If wsgi.input.read() raises an exception while trying to read() the POST, the exception is identifiable (not a generic OSError). """ class ExplodingBytesIO(BytesIO): def read(self, len=0): raise OSError('kaboom!') payload = b'name=value' request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': ExplodingBytesIO(payload), }) with self.assertRaises(UnreadablePostError): request.body def test_set_encoding_clears_POST(self): payload = FakePayload('name=Hello Günter') request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_LENGTH': len(payload), 'wsgi.input': payload, }) self.assertEqual(request.POST, {'name': ['Hello Günter']}) request.encoding = 'iso-8859-16' self.assertEqual(request.POST, {'name': ['Hello GĂŒnter']}) def test_set_encoding_clears_GET(self): request = WSGIRequest({ 'REQUEST_METHOD': 'GET', 'wsgi.input': '', 'QUERY_STRING': 'name=Hello%20G%C3%BCnter', }) self.assertEqual(request.GET, {'name': ['Hello Günter']}) request.encoding = 'iso-8859-16' self.assertEqual(request.GET, {'name': ['Hello G\u0102\u0152nter']}) def test_FILES_connection_error(self): """ If wsgi.input.read() raises an exception while trying to read() the FILES, the exception is identifiable (not a generic OSError). """ class ExplodingBytesIO(BytesIO): def read(self, len=0): raise OSError('kaboom!') payload = b'x' request = WSGIRequest({ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': 'multipart/form-data; boundary=foo_', 'CONTENT_LENGTH': len(payload), 'wsgi.input': ExplodingBytesIO(payload), }) with self.assertRaises(UnreadablePostError): request.FILES @override_settings(ALLOWED_HOSTS=['example.com']) def test_get_raw_uri(self): factory = RequestFactory(HTTP_HOST='evil.com') request = factory.get('////absolute-uri') self.assertEqual(request.get_raw_uri(), 'http://evil.com//absolute-uri') request = factory.get('/?foo=bar') self.assertEqual(request.get_raw_uri(), 'http://evil.com/?foo=bar') request = factory.get('/path/with:colons') self.assertEqual(request.get_raw_uri(), 'http://evil.com/path/with:colons') class HostValidationTests(SimpleTestCase): poisoned_hosts = [ '[email protected]', 'example.com:[email protected]', 'example.com:[email protected]:80', 'example.com:80/badpath', 'example.com: recovermypassword.com', ] @override_settings( USE_X_FORWARDED_HOST=False, ALLOWED_HOSTS=[ 'forward.com', 'example.com', 'internal.com', '12.34.56.78', '[2001:19f0:feee::dead:beef:cafe]', 'xn--4ca9at.com', '.multitenant.com', 'INSENSITIVE.com', '[::ffff:169.254.169.254]', ]) def test_http_get_host(self): # Check if X_FORWARDED_HOST is provided. request = HttpRequest() request.META = { 'HTTP_X_FORWARDED_HOST': 'forward.com', 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } # X_FORWARDED_HOST is ignored. self.assertEqual(request.get_host(), 'example.com') # Check if X_FORWARDED_HOST isn't provided. request = HttpRequest() request.META = { 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'example.com') # Check if HTTP_HOST isn't provided. request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'internal.com') # Check if HTTP_HOST isn't provided, and we're on a nonstandard port request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 8042, } self.assertEqual(request.get_host(), 'internal.com:8042') legit_hosts = [ 'example.com', 'example.com:80', '12.34.56.78', '12.34.56.78:443', '[2001:19f0:feee::dead:beef:cafe]', '[2001:19f0:feee::dead:beef:cafe]:8080', 'xn--4ca9at.com', # Punycode for öäü.com 'anything.multitenant.com', 'multitenant.com', 'insensitive.com', 'example.com.', 'example.com.:80', '[::ffff:169.254.169.254]', ] for host in legit_hosts: request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() # Poisoned host headers are rejected as suspicious for host in chain(self.poisoned_hosts, ['other.com', 'example.com..']): with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() @override_settings(USE_X_FORWARDED_HOST=True, ALLOWED_HOSTS=['*']) def test_http_get_host_with_x_forwarded_host(self): # Check if X_FORWARDED_HOST is provided. request = HttpRequest() request.META = { 'HTTP_X_FORWARDED_HOST': 'forward.com', 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } # X_FORWARDED_HOST is obeyed. self.assertEqual(request.get_host(), 'forward.com') # Check if X_FORWARDED_HOST isn't provided. request = HttpRequest() request.META = { 'HTTP_HOST': 'example.com', 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'example.com') # Check if HTTP_HOST isn't provided. request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, } self.assertEqual(request.get_host(), 'internal.com') # Check if HTTP_HOST isn't provided, and we're on a nonstandard port request = HttpRequest() request.META = { 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 8042, } self.assertEqual(request.get_host(), 'internal.com:8042') # Poisoned host headers are rejected as suspicious legit_hosts = [ 'example.com', 'example.com:80', '12.34.56.78', '12.34.56.78:443', '[2001:19f0:feee::dead:beef:cafe]', '[2001:19f0:feee::dead:beef:cafe]:8080', 'xn--4ca9at.com', # Punycode for öäü.com ] for host in legit_hosts: request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() for host in self.poisoned_hosts: with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = { 'HTTP_HOST': host, } request.get_host() @override_settings(USE_X_FORWARDED_PORT=False) def test_get_port(self): request = HttpRequest() request.META = { 'SERVER_PORT': '8080', 'HTTP_X_FORWARDED_PORT': '80', } # Shouldn't use the X-Forwarded-Port header self.assertEqual(request.get_port(), '8080') request = HttpRequest() request.META = { 'SERVER_PORT': '8080', } self.assertEqual(request.get_port(), '8080') @override_settings(USE_X_FORWARDED_PORT=True) def test_get_port_with_x_forwarded_port(self): request = HttpRequest() request.META = { 'SERVER_PORT': '8080', 'HTTP_X_FORWARDED_PORT': '80', } # Should use the X-Forwarded-Port header self.assertEqual(request.get_port(), '80') request = HttpRequest() request.META = { 'SERVER_PORT': '8080', } self.assertEqual(request.get_port(), '8080') @override_settings(DEBUG=True, ALLOWED_HOSTS=[]) def test_host_validation_in_debug_mode(self): """ If ALLOWED_HOSTS is empty and DEBUG is True, variants of localhost are allowed. """ valid_hosts = ['localhost', '127.0.0.1', '[::1]'] for host in valid_hosts: request = HttpRequest() request.META = {'HTTP_HOST': host} self.assertEqual(request.get_host(), host) # Other hostnames raise a DisallowedHost. with self.assertRaises(DisallowedHost): request = HttpRequest() request.META = {'HTTP_HOST': 'example.com'} request.get_host() @override_settings(ALLOWED_HOSTS=[]) def test_get_host_suggestion_of_allowed_host(self): """get_host() makes helpful suggestions if a valid-looking host is not in ALLOWED_HOSTS.""" msg_invalid_host = "Invalid HTTP_HOST header: %r." msg_suggestion = msg_invalid_host + " You may need to add %r to ALLOWED_HOSTS." msg_suggestion2 = msg_invalid_host + " The domain name provided is not valid according to RFC 1034/1035" for host in [ # Valid-looking hosts 'example.com', '12.34.56.78', '[2001:19f0:feee::dead:beef:cafe]', 'xn--4ca9at.com', # Punycode for öäü.com ]: request = HttpRequest() request.META = {'HTTP_HOST': host} with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, host)): request.get_host() for domain, port in [ # Valid-looking hosts with a port number ('example.com', 80), ('12.34.56.78', 443), ('[2001:19f0:feee::dead:beef:cafe]', 8080), ]: host = '%s:%s' % (domain, port) request = HttpRequest() request.META = {'HTTP_HOST': host} with self.assertRaisesMessage(DisallowedHost, msg_suggestion % (host, domain)): request.get_host() for host in self.poisoned_hosts: request = HttpRequest() request.META = {'HTTP_HOST': host} with self.assertRaisesMessage(DisallowedHost, msg_invalid_host % host): request.get_host() request = HttpRequest() request.META = {'HTTP_HOST': "invalid_hostname.com"} with self.assertRaisesMessage(DisallowedHost, msg_suggestion2 % "invalid_hostname.com"): request.get_host() def test_split_domain_port_removes_trailing_dot(self): domain, port = split_domain_port('example.com.:8080') self.assertEqual(domain, 'example.com') self.assertEqual(port, '8080') class BuildAbsoluteURITests(SimpleTestCase): factory = RequestFactory() def test_absolute_url(self): request = HttpRequest() url = 'https://www.example.com/asdf' self.assertEqual(request.build_absolute_uri(location=url), url) def test_host_retrieval(self): request = HttpRequest() request.get_host = lambda: 'www.example.com' request.path = '' self.assertEqual( request.build_absolute_uri(location='/path/with:colons'), 'http://www.example.com/path/with:colons' ) def test_request_path_begins_with_two_slashes(self): # //// creates a request with a path beginning with // request = self.factory.get('////absolute-uri') tests = ( # location isn't provided (None, 'http://testserver//absolute-uri'), # An absolute URL ('http://example.com/?foo=bar', 'http://example.com/?foo=bar'), # A schema-relative URL ('//example.com/?foo=bar', 'http://example.com/?foo=bar'), # Relative URLs ('/foo/bar/', 'http://testserver/foo/bar/'), ('/foo/./bar/', 'http://testserver/foo/bar/'), ('/foo/../bar/', 'http://testserver/bar/'), ('///foo/bar/', 'http://testserver/foo/bar/'), ) for location, expected_url in tests: with self.subTest(location=location): self.assertEqual(request.build_absolute_uri(location=location), expected_url) class RequestHeadersTests(SimpleTestCase): ENVIRON = { # Non-headers are ignored. 'PATH_INFO': '/somepath/', 'REQUEST_METHOD': 'get', 'wsgi.input': BytesIO(b''), 'SERVER_NAME': 'internal.com', 'SERVER_PORT': 80, # These non-HTTP prefixed headers are included. 'CONTENT_TYPE': 'text/html', 'CONTENT_LENGTH': '100', # All HTTP-prefixed headers are included. 'HTTP_ACCEPT': '*', 'HTTP_HOST': 'example.com', 'HTTP_USER_AGENT': 'python-requests/1.2.0', } def test_base_request_headers(self): request = HttpRequest() request.META = self.ENVIRON self.assertEqual(dict(request.headers), { 'Content-Type': 'text/html', 'Content-Length': '100', 'Accept': '*', 'Host': 'example.com', 'User-Agent': 'python-requests/1.2.0', }) def test_wsgi_request_headers(self): request = WSGIRequest(self.ENVIRON) self.assertEqual(dict(request.headers), { 'Content-Type': 'text/html', 'Content-Length': '100', 'Accept': '*', 'Host': 'example.com', 'User-Agent': 'python-requests/1.2.0', }) def test_wsgi_request_headers_getitem(self): request = WSGIRequest(self.ENVIRON) self.assertEqual(request.headers['User-Agent'], 'python-requests/1.2.0') self.assertEqual(request.headers['user-agent'], 'python-requests/1.2.0') self.assertEqual(request.headers['user_agent'], 'python-requests/1.2.0') self.assertEqual(request.headers['Content-Type'], 'text/html') self.assertEqual(request.headers['Content-Length'], '100') def test_wsgi_request_headers_get(self): request = WSGIRequest(self.ENVIRON) self.assertEqual(request.headers.get('User-Agent'), 'python-requests/1.2.0') self.assertEqual(request.headers.get('user-agent'), 'python-requests/1.2.0') self.assertEqual(request.headers.get('Content-Type'), 'text/html') self.assertEqual(request.headers.get('Content-Length'), '100') class HttpHeadersTests(SimpleTestCase): def test_basic(self): environ = { 'CONTENT_TYPE': 'text/html', 'CONTENT_LENGTH': '100', 'HTTP_HOST': 'example.com', } headers = HttpHeaders(environ) self.assertEqual(sorted(headers), ['Content-Length', 'Content-Type', 'Host']) self.assertEqual(headers, { 'Content-Type': 'text/html', 'Content-Length': '100', 'Host': 'example.com', }) def test_parse_header_name(self): tests = ( ('PATH_INFO', None), ('HTTP_ACCEPT', 'Accept'), ('HTTP_USER_AGENT', 'User-Agent'), ('HTTP_X_FORWARDED_PROTO', 'X-Forwarded-Proto'), ('CONTENT_TYPE', 'Content-Type'), ('CONTENT_LENGTH', 'Content-Length'), ) for header, expected in tests: with self.subTest(header=header): self.assertEqual(HttpHeaders.parse_header_name(header), expected)
e4438dcea6410f4c0b1b86a0c19d3417af74971785ca2111424cda4a9fe9606c
import datetime from unittest import mock from django.db import connections from django.db.models.sql.compiler import cursor_iter from django.test import TestCase from .models import Article class QuerySetIteratorTests(TestCase): itersize_index_in_mock_args = 3 @classmethod def setUpTestData(cls): Article.objects.create(name='Article 1', created=datetime.datetime.now()) Article.objects.create(name='Article 2', created=datetime.datetime.now()) def test_iterator_invalid_chunk_size(self): for size in (0, -1): with self.subTest(size=size): with self.assertRaisesMessage(ValueError, 'Chunk size must be strictly positive.'): Article.objects.iterator(chunk_size=size) def test_default_iterator_chunk_size(self): qs = Article.objects.iterator() with mock.patch('django.db.models.sql.compiler.cursor_iter', side_effect=cursor_iter) as cursor_iter_mock: next(qs) self.assertEqual(cursor_iter_mock.call_count, 1) mock_args, _mock_kwargs = cursor_iter_mock.call_args self.assertEqual(mock_args[self.itersize_index_in_mock_args], 2000) def test_iterator_chunk_size(self): batch_size = 3 qs = Article.objects.iterator(chunk_size=batch_size) with mock.patch('django.db.models.sql.compiler.cursor_iter', side_effect=cursor_iter) as cursor_iter_mock: next(qs) self.assertEqual(cursor_iter_mock.call_count, 1) mock_args, _mock_kwargs = cursor_iter_mock.call_args self.assertEqual(mock_args[self.itersize_index_in_mock_args], batch_size) def test_no_chunked_reads(self): """ If the database backend doesn't support chunked reads, then the result of SQLCompiler.execute_sql() is a list. """ qs = Article.objects.all() compiler = qs.query.get_compiler(using=qs.db) features = connections[qs.db].features with mock.patch.object(features, 'can_use_chunked_reads', False): result = compiler.execute_sql(chunked_fetch=True) self.assertIsInstance(result, list)
b3f2f69b4ee3e5e0a1a4935be85b7d22bec86af66baec76ce1654b5d66a8f7fd
import datetime import pickle import sys import unittest from operator import attrgetter from django.core.exceptions import EmptyResultSet, FieldError from django.db import DEFAULT_DB_ALIAS, connection from django.db.models import Count, F, Q from django.db.models.sql.constants import LOUTER from django.db.models.sql.where import NothingNode, WhereNode from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import ( FK1, Annotation, Article, Author, BaseA, Book, CategoryItem, CategoryRelationship, Celebrity, Channel, Chapter, Child, ChildObjectA, Classroom, CommonMixedCaseForeignKeys, Company, Cover, CustomPk, CustomPkTag, Detail, DumbCategory, Eaten, Employment, ExtraInfo, Fan, Food, Identifier, Individual, Item, Job, JobResponsibilities, Join, LeafA, LeafB, LoopX, LoopZ, ManagedModel, Member, MixedCaseDbColumnCategoryItem, MixedCaseFieldCategoryItem, ModelA, ModelB, ModelC, ModelD, MyObject, NamedCategory, Node, Note, NullableName, Number, ObjectA, ObjectB, ObjectC, OneToOneCategory, Order, OrderItem, Page, Paragraph, Person, Plaything, PointerA, Program, ProxyCategory, ProxyObjectA, ProxyObjectB, Ranking, Related, RelatedIndividual, RelatedObject, Report, ReportComment, ReservedName, Responsibility, School, SharedConnection, SimpleCategory, SingleObject, SpecialCategory, Staff, StaffUser, Student, Tag, Task, Teacher, Ticket21203Child, Ticket21203Parent, Ticket23605A, Ticket23605B, Ticket23605C, TvChef, Valid, X, ) class Queries1Tests(TestCase): @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") cls.t1 = Tag.objects.create(name='t1', category=generic) cls.t2 = Tag.objects.create(name='t2', parent=cls.t1, category=generic) cls.t3 = Tag.objects.create(name='t3', parent=cls.t1) t4 = Tag.objects.create(name='t4', parent=cls.t3) cls.t5 = Tag.objects.create(name='t5', parent=cls.t3) cls.n1 = Note.objects.create(note='n1', misc='foo', id=1) cls.n2 = Note.objects.create(note='n2', misc='bar', id=2) cls.n3 = Note.objects.create(note='n3', misc='foo', id=3) ann1 = Annotation.objects.create(name='a1', tag=cls.t1) ann1.notes.add(cls.n1) ann2 = Annotation.objects.create(name='a2', tag=t4) ann2.notes.add(cls.n2, cls.n3) # Create these out of order so that sorting by 'id' will be different to sorting # by 'info'. Helps detect some problems later. cls.e2 = ExtraInfo.objects.create(info='e2', note=cls.n2, value=41) e1 = ExtraInfo.objects.create(info='e1', note=cls.n1, value=42) cls.a1 = Author.objects.create(name='a1', num=1001, extra=e1) cls.a2 = Author.objects.create(name='a2', num=2002, extra=e1) a3 = Author.objects.create(name='a3', num=3003, extra=cls.e2) cls.a4 = Author.objects.create(name='a4', num=4004, extra=cls.e2) cls.time1 = datetime.datetime(2007, 12, 19, 22, 25, 0) cls.time2 = datetime.datetime(2007, 12, 19, 21, 0, 0) time3 = datetime.datetime(2007, 12, 20, 22, 25, 0) time4 = datetime.datetime(2007, 12, 20, 21, 0, 0) cls.i1 = Item.objects.create(name='one', created=cls.time1, modified=cls.time1, creator=cls.a1, note=cls.n3) cls.i1.tags.set([cls.t1, cls.t2]) cls.i2 = Item.objects.create(name='two', created=cls.time2, creator=cls.a2, note=cls.n2) cls.i2.tags.set([cls.t1, cls.t3]) cls.i3 = Item.objects.create(name='three', created=time3, creator=cls.a2, note=cls.n3) i4 = Item.objects.create(name='four', created=time4, creator=cls.a4, note=cls.n3) i4.tags.set([t4]) cls.r1 = Report.objects.create(name='r1', creator=cls.a1) Report.objects.create(name='r2', creator=a3) Report.objects.create(name='r3') # Ordering by 'rank' gives us rank2, rank1, rank3. Ordering by the Meta.ordering # will be rank3, rank2, rank1. cls.rank1 = Ranking.objects.create(rank=2, author=cls.a2) Cover.objects.create(title="first", item=i4) Cover.objects.create(title="second", item=cls.i2) def test_subquery_condition(self): qs1 = Tag.objects.filter(pk__lte=0) qs2 = Tag.objects.filter(parent__in=qs1) qs3 = Tag.objects.filter(parent__in=qs2) self.assertEqual(qs3.query.subq_aliases, {'T', 'U', 'V'}) self.assertIn('v0', str(qs3.query).lower()) qs4 = qs3.filter(parent__in=qs1) self.assertEqual(qs4.query.subq_aliases, {'T', 'U', 'V'}) # It is possible to reuse U for the second subquery, no need to use W. self.assertNotIn('w0', str(qs4.query).lower()) # So, 'U0."id"' is referenced in SELECT and WHERE twice. self.assertEqual(str(qs4.query).lower().count('u0.'), 4) def test_ticket1050(self): self.assertQuerysetEqual( Item.objects.filter(tags__isnull=True), ['<Item: three>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__id__isnull=True), ['<Item: three>'] ) def test_ticket1801(self): self.assertQuerysetEqual( Author.objects.filter(item=self.i2), ['<Author: a2>'] ) self.assertQuerysetEqual( Author.objects.filter(item=self.i3), ['<Author: a2>'] ) self.assertQuerysetEqual( Author.objects.filter(item=self.i2) & Author.objects.filter(item=self.i3), ['<Author: a2>'] ) def test_ticket2306(self): # Checking that no join types are "left outer" joins. query = Item.objects.filter(tags=self.t2).query self.assertNotIn(LOUTER, [x.join_type for x in query.alias_map.values()]) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1)).order_by('name'), ['<Item: one>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1)).filter(Q(tags=self.t2)), ['<Item: one>'] ) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1)).filter(Q(creator__name='fred') | Q(tags=self.t2)), ['<Item: one>'] ) # Each filter call is processed "at once" against a single table, so this is # different from the previous example as it tries to find tags that are two # things at once (rather than two tags). self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1) & Q(tags=self.t2)), [] ) self.assertQuerysetEqual( Item.objects.filter(Q(tags=self.t1), Q(creator__name='fred') | Q(tags=self.t2)), [] ) qs = Author.objects.filter(ranking__rank=2, ranking__id=self.rank1.id) self.assertQuerysetEqual(list(qs), ['<Author: a2>']) self.assertEqual(2, qs.query.count_active_tables(), 2) qs = Author.objects.filter(ranking__rank=2).filter(ranking__id=self.rank1.id) self.assertEqual(qs.query.count_active_tables(), 3) def test_ticket4464(self): self.assertQuerysetEqual( Item.objects.filter(tags=self.t1).filter(tags=self.t2), ['<Item: one>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).distinct().order_by('name'), ['<Item: one>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).filter(tags=self.t3), ['<Item: two>'] ) # Make sure .distinct() works with slicing (this was broken in Oracle). self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).order_by('name')[:3], ['<Item: one>', '<Item: one>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(tags__in=[self.t1, self.t2]).distinct().order_by('name')[:3], ['<Item: one>', '<Item: two>'] ) def test_tickets_2080_3592(self): self.assertQuerysetEqual( Author.objects.filter(item__name='one') | Author.objects.filter(name='a3'), ['<Author: a1>', '<Author: a3>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(item__name='one') | Q(name='a3')), ['<Author: a1>', '<Author: a3>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(name='a3') | Q(item__name='one')), ['<Author: a1>', '<Author: a3>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(item__name='three') | Q(report__name='r3')), ['<Author: a2>'] ) def test_ticket6074(self): # Merging two empty result sets shouldn't leave a queryset with no constraints # (which would match everything). self.assertQuerysetEqual(Author.objects.filter(Q(id__in=[])), []) self.assertQuerysetEqual( Author.objects.filter(Q(id__in=[]) | Q(id__in=[])), [] ) def test_tickets_1878_2939(self): self.assertEqual(Item.objects.values('creator').distinct().count(), 3) # Create something with a duplicate 'name' so that we can test multi-column # cases (which require some tricky SQL transformations under the covers). xx = Item(name='four', created=self.time1, creator=self.a2, note=self.n1) xx.save() self.assertEqual( Item.objects.exclude(name='two').values('creator', 'name').distinct().count(), 4 ) self.assertEqual( ( Item.objects .exclude(name='two') .extra(select={'foo': '%s'}, select_params=(1,)) .values('creator', 'name', 'foo') .distinct() .count() ), 4 ) self.assertEqual( ( Item.objects .exclude(name='two') .extra(select={'foo': '%s'}, select_params=(1,)) .values('creator', 'name') .distinct() .count() ), 4 ) xx.delete() def test_ticket7323(self): self.assertEqual(Item.objects.values('creator', 'name').count(), 4) def test_ticket2253(self): q1 = Item.objects.order_by('name') q2 = Item.objects.filter(id=self.i1.id) self.assertQuerysetEqual( q1, ['<Item: four>', '<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual(q2, ['<Item: one>']) self.assertQuerysetEqual( (q1 | q2).order_by('name'), ['<Item: four>', '<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual((q1 & q2).order_by('name'), ['<Item: one>']) q1 = Item.objects.filter(tags=self.t1) q2 = Item.objects.filter(note=self.n3, tags=self.t2) q3 = Item.objects.filter(creator=self.a4) self.assertQuerysetEqual( ((q1 & q2) | q3).order_by('name'), ['<Item: four>', '<Item: one>'] ) def test_order_by_tables(self): q1 = Item.objects.order_by('name') q2 = Item.objects.filter(id=self.i1.id) list(q2) combined_query = (q1 & q2).order_by('name').query self.assertEqual(len([ t for t in combined_query.alias_map if combined_query.alias_refcount[t] ]), 1) def test_order_by_join_unref(self): """ This test is related to the above one, testing that there aren't old JOINs in the query. """ qs = Celebrity.objects.order_by('greatest_fan__fan_of') self.assertIn('OUTER JOIN', str(qs.query)) qs = qs.order_by('id') self.assertNotIn('OUTER JOIN', str(qs.query)) def test_get_clears_ordering(self): """ get() should clear ordering for optimization purposes. """ with CaptureQueriesContext(connection) as captured_queries: Author.objects.order_by('name').get(pk=self.a1.pk) self.assertNotIn('order by', captured_queries[0]['sql'].lower()) def test_tickets_4088_4306(self): self.assertQuerysetEqual( Report.objects.filter(creator=1001), ['<Report: r1>'] ) self.assertQuerysetEqual( Report.objects.filter(creator__num=1001), ['<Report: r1>'] ) self.assertQuerysetEqual(Report.objects.filter(creator__id=1001), []) self.assertQuerysetEqual( Report.objects.filter(creator__id=self.a1.id), ['<Report: r1>'] ) self.assertQuerysetEqual( Report.objects.filter(creator__name='a1'), ['<Report: r1>'] ) def test_ticket4510(self): self.assertQuerysetEqual( Author.objects.filter(report__name='r1'), ['<Author: a1>'] ) def test_ticket7378(self): self.assertQuerysetEqual(self.a1.report_set.all(), ['<Report: r1>']) def test_tickets_5324_6704(self): self.assertQuerysetEqual( Item.objects.filter(tags__name='t4'), ['<Item: four>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t4').order_by('name').distinct(), ['<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t4').order_by('name').distinct().reverse(), ['<Item: two>', '<Item: three>', '<Item: one>'] ) self.assertQuerysetEqual( Author.objects.exclude(item__name='one').distinct().order_by('name'), ['<Author: a2>', '<Author: a3>', '<Author: a4>'] ) # Excluding across a m2m relation when there is more than one related # object associated was problematic. self.assertQuerysetEqual( Item.objects.exclude(tags__name='t1').order_by('name'), ['<Item: four>', '<Item: three>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t1').exclude(tags__name='t4'), ['<Item: three>'] ) # Excluding from a relation that cannot be NULL should not use outer joins. query = Item.objects.exclude(creator__in=[self.a1, self.a2]).query self.assertNotIn(LOUTER, [x.join_type for x in query.alias_map.values()]) # Similarly, when one of the joins cannot possibly, ever, involve NULL # values (Author -> ExtraInfo, in the following), it should never be # promoted to a left outer join. So the following query should only # involve one "left outer" join (Author -> Item is 0-to-many). qs = Author.objects.filter(id=self.a1.id).filter(Q(extra__note=self.n1) | Q(item__note=self.n3)) self.assertEqual( len([ x for x in qs.query.alias_map.values() if x.join_type == LOUTER and qs.query.alias_refcount[x.table_alias] ]), 1 ) # The previous changes shouldn't affect nullable foreign key joins. self.assertQuerysetEqual( Tag.objects.filter(parent__isnull=True).order_by('name'), ['<Tag: t1>'] ) self.assertQuerysetEqual( Tag.objects.exclude(parent__isnull=True).order_by('name'), ['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.exclude(Q(parent__name='t1') | Q(parent__isnull=True)).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.exclude(Q(parent__isnull=True) | Q(parent__name='t1')).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.exclude(Q(parent__parent__isnull=True)).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.filter(~Q(parent__parent__isnull=True)).order_by('name'), ['<Tag: t4>', '<Tag: t5>'] ) def test_ticket2091(self): t = Tag.objects.get(name='t4') self.assertQuerysetEqual( Item.objects.filter(tags__in=[t]), ['<Item: four>'] ) def test_avoid_infinite_loop_on_too_many_subqueries(self): x = Tag.objects.filter(pk=1) local_recursion_limit = sys.getrecursionlimit() // 16 msg = 'Maximum recursion depth exceeded: too many subqueries.' with self.assertRaisesMessage(RecursionError, msg): for i in range(local_recursion_limit + 2): x = Tag.objects.filter(pk__in=x) def test_reasonable_number_of_subq_aliases(self): x = Tag.objects.filter(pk=1) for _ in range(20): x = Tag.objects.filter(pk__in=x) self.assertEqual( x.query.subq_aliases, { 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', } ) def test_heterogeneous_qs_combination(self): # Combining querysets built on different models should behave in a well-defined # fashion. We raise an error. with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'): Author.objects.all() & Tag.objects.all() with self.assertRaisesMessage(AssertionError, 'Cannot combine queries on two different base models.'): Author.objects.all() | Tag.objects.all() def test_ticket3141(self): self.assertEqual(Author.objects.extra(select={'foo': '1'}).count(), 4) self.assertEqual( Author.objects.extra(select={'foo': '%s'}, select_params=(1,)).count(), 4 ) def test_ticket2400(self): self.assertQuerysetEqual( Author.objects.filter(item__isnull=True), ['<Author: a3>'] ) self.assertQuerysetEqual( Tag.objects.filter(item__isnull=True), ['<Tag: t5>'] ) def test_ticket2496(self): self.assertQuerysetEqual( Item.objects.extra(tables=['queries_author']).select_related().order_by('name')[:1], ['<Item: four>'] ) def test_error_raised_on_filter_with_dictionary(self): with self.assertRaisesMessage(FieldError, 'Cannot parse keyword query as dict'): Note.objects.filter({'note': 'n1', 'misc': 'foo'}) def test_tickets_2076_7256(self): # Ordering on related tables should be possible, even if the table is # not otherwise involved. self.assertQuerysetEqual( Item.objects.order_by('note__note', 'name'), ['<Item: two>', '<Item: four>', '<Item: one>', '<Item: three>'] ) # Ordering on a related field should use the remote model's default # ordering as a final step. self.assertQuerysetEqual( Author.objects.order_by('extra', '-name'), ['<Author: a2>', '<Author: a1>', '<Author: a4>', '<Author: a3>'] ) # Using remote model default ordering can span multiple models (in this # case, Cover is ordered by Item's default, which uses Note's default). self.assertQuerysetEqual( Cover.objects.all(), ['<Cover: first>', '<Cover: second>'] ) # If the remote model does not have a default ordering, we order by its 'id' # field. self.assertQuerysetEqual( Item.objects.order_by('creator', 'name'), ['<Item: one>', '<Item: three>', '<Item: two>', '<Item: four>'] ) # Ordering by a many-valued attribute (e.g. a many-to-many or reverse # ForeignKey) is legal, but the results might not make sense. That # isn't Django's problem. Garbage in, garbage out. self.assertQuerysetEqual( Item.objects.filter(tags__isnull=False).order_by('tags', 'id'), ['<Item: one>', '<Item: two>', '<Item: one>', '<Item: two>', '<Item: four>'] ) # If we replace the default ordering, Django adjusts the required # tables automatically. Item normally requires a join with Note to do # the default ordering, but that isn't needed here. qs = Item.objects.order_by('name') self.assertQuerysetEqual( qs, ['<Item: four>', '<Item: one>', '<Item: three>', '<Item: two>'] ) self.assertEqual(len(qs.query.alias_map), 1) def test_tickets_2874_3002(self): qs = Item.objects.select_related().order_by('note__note', 'name') self.assertQuerysetEqual( qs, ['<Item: two>', '<Item: four>', '<Item: one>', '<Item: three>'] ) # This is also a good select_related() test because there are multiple # Note entries in the SQL. The two Note items should be different. self.assertEqual(repr(qs[0].note), '<Note: n2>') self.assertEqual(repr(qs[0].creator.extra.note), '<Note: n1>') def test_ticket3037(self): self.assertQuerysetEqual( Item.objects.filter(Q(creator__name='a3', name='two') | Q(creator__name='a4', name='four')), ['<Item: four>'] ) def test_tickets_5321_7070(self): # Ordering columns must be included in the output columns. Note that # this means results that might otherwise be distinct are not (if there # are multiple values in the ordering cols), as in this example. This # isn't a bug; it's a warning to be careful with the selection of # ordering columns. self.assertSequenceEqual( Note.objects.values('misc').distinct().order_by('note', '-misc'), [{'misc': 'foo'}, {'misc': 'bar'}, {'misc': 'foo'}] ) def test_ticket4358(self): # If you don't pass any fields to values(), relation fields are # returned as "foo_id" keys, not "foo". For consistency, you should be # able to pass "foo_id" in the fields list and have it work, too. We # actually allow both "foo" and "foo_id". # The *_id version is returned by default. self.assertIn('note_id', ExtraInfo.objects.values()[0]) # You can also pass it in explicitly. self.assertSequenceEqual(ExtraInfo.objects.values('note_id'), [{'note_id': 1}, {'note_id': 2}]) # ...or use the field name. self.assertSequenceEqual(ExtraInfo.objects.values('note'), [{'note': 1}, {'note': 2}]) def test_ticket6154(self): # Multiple filter statements are joined using "AND" all the time. self.assertQuerysetEqual( Author.objects.filter(id=self.a1.id).filter(Q(extra__note=self.n1) | Q(item__note=self.n3)), ['<Author: a1>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(extra__note=self.n1) | Q(item__note=self.n3)).filter(id=self.a1.id), ['<Author: a1>'] ) def test_ticket6981(self): self.assertQuerysetEqual( Tag.objects.select_related('parent').order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) def test_ticket9926(self): self.assertQuerysetEqual( Tag.objects.select_related("parent", "category").order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Tag.objects.select_related('parent', "parent__category").order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'] ) def test_tickets_6180_6203(self): # Dates with limits and/or counts self.assertEqual(Item.objects.count(), 4) self.assertEqual(Item.objects.datetimes('created', 'month').count(), 1) self.assertEqual(Item.objects.datetimes('created', 'day').count(), 2) self.assertEqual(len(Item.objects.datetimes('created', 'day')), 2) self.assertEqual(Item.objects.datetimes('created', 'day')[0], datetime.datetime(2007, 12, 19, 0, 0)) def test_tickets_7087_12242(self): # Dates with extra select columns self.assertQuerysetEqual( Item.objects.datetimes('created', 'day').extra(select={'a': 1}), ['datetime.datetime(2007, 12, 19, 0, 0)', 'datetime.datetime(2007, 12, 20, 0, 0)'] ) self.assertQuerysetEqual( Item.objects.extra(select={'a': 1}).datetimes('created', 'day'), ['datetime.datetime(2007, 12, 19, 0, 0)', 'datetime.datetime(2007, 12, 20, 0, 0)'] ) name = "one" self.assertQuerysetEqual( Item.objects.datetimes('created', 'day').extra(where=['name=%s'], params=[name]), ['datetime.datetime(2007, 12, 19, 0, 0)'] ) self.assertQuerysetEqual( Item.objects.extra(where=['name=%s'], params=[name]).datetimes('created', 'day'), ['datetime.datetime(2007, 12, 19, 0, 0)'] ) def test_ticket7155(self): # Nullable dates self.assertQuerysetEqual( Item.objects.datetimes('modified', 'day'), ['datetime.datetime(2007, 12, 19, 0, 0)'] ) def test_ticket7098(self): # Make sure semi-deprecated ordering by related models syntax still # works. self.assertSequenceEqual( Item.objects.values('note__note').order_by('queries_note.note', 'id'), [{'note__note': 'n2'}, {'note__note': 'n3'}, {'note__note': 'n3'}, {'note__note': 'n3'}] ) def test_ticket7096(self): # Make sure exclude() with multiple conditions continues to work. self.assertQuerysetEqual( Tag.objects.filter(parent=self.t1, name='t3').order_by('name'), ['<Tag: t3>'] ) self.assertQuerysetEqual( Tag.objects.exclude(parent=self.t1, name='t3').order_by('name'), ['<Tag: t1>', '<Tag: t2>', '<Tag: t4>', '<Tag: t5>'] ) self.assertQuerysetEqual( Item.objects.exclude(tags__name='t1', name='one').order_by('name').distinct(), ['<Item: four>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual( Item.objects.filter(name__in=['three', 'four']).exclude(tags__name='t1').order_by('name'), ['<Item: four>', '<Item: three>'] ) # More twisted cases, involving nested negations. self.assertQuerysetEqual( Item.objects.exclude(~Q(tags__name='t1', name='one')), ['<Item: one>'] ) self.assertQuerysetEqual( Item.objects.filter(~Q(tags__name='t1', name='one'), name='two'), ['<Item: two>'] ) self.assertQuerysetEqual( Item.objects.exclude(~Q(tags__name='t1', name='one'), name='two'), ['<Item: four>', '<Item: one>', '<Item: three>'] ) def test_tickets_7204_7506(self): # Make sure querysets with related fields can be pickled. If this # doesn't crash, it's a Good Thing. pickle.dumps(Item.objects.all()) def test_ticket7813(self): # We should also be able to pickle things that use select_related(). # The only tricky thing here is to ensure that we do the related # selections properly after unpickling. qs = Item.objects.select_related() query = qs.query.get_compiler(qs.db).as_sql()[0] query2 = pickle.loads(pickle.dumps(qs.query)) self.assertEqual( query2.get_compiler(qs.db).as_sql()[0], query ) def test_deferred_load_qs_pickling(self): # Check pickling of deferred-loading querysets qs = Item.objects.defer('name', 'creator') q2 = pickle.loads(pickle.dumps(qs)) self.assertEqual(list(qs), list(q2)) q3 = pickle.loads(pickle.dumps(qs, pickle.HIGHEST_PROTOCOL)) self.assertEqual(list(qs), list(q3)) def test_ticket7277(self): self.assertQuerysetEqual( self.n1.annotation_set.filter( Q(tag=self.t5) | Q(tag__children=self.t5) | Q(tag__children__children=self.t5) ), ['<Annotation: a1>'] ) def test_tickets_7448_7707(self): # Complex objects should be converted to strings before being used in # lookups. self.assertQuerysetEqual( Item.objects.filter(created__in=[self.time1, self.time2]), ['<Item: one>', '<Item: two>'] ) def test_ticket7235(self): # An EmptyQuerySet should not raise exceptions if it is filtered. Eaten.objects.create(meal='m') q = Eaten.objects.none() with self.assertNumQueries(0): self.assertQuerysetEqual(q.all(), []) self.assertQuerysetEqual(q.filter(meal='m'), []) self.assertQuerysetEqual(q.exclude(meal='m'), []) self.assertQuerysetEqual(q.complex_filter({'pk': 1}), []) self.assertQuerysetEqual(q.select_related('food'), []) self.assertQuerysetEqual(q.annotate(Count('food')), []) self.assertQuerysetEqual(q.order_by('meal', 'food'), []) self.assertQuerysetEqual(q.distinct(), []) self.assertQuerysetEqual( q.extra(select={'foo': "1"}), [] ) self.assertQuerysetEqual(q.reverse(), []) q.query.low_mark = 1 with self.assertRaisesMessage(AssertionError, 'Cannot change a query once a slice has been taken'): q.extra(select={'foo': "1"}) self.assertQuerysetEqual(q.defer('meal'), []) self.assertQuerysetEqual(q.only('meal'), []) def test_ticket7791(self): # There were "issues" when ordering and distinct-ing on fields related # via ForeignKeys. self.assertEqual( len(Note.objects.order_by('extrainfo__info').distinct()), 3 ) # Pickling of QuerySets using datetimes() should work. qs = Item.objects.datetimes('created', 'month') pickle.loads(pickle.dumps(qs)) def test_ticket9997(self): # If a ValuesList or Values queryset is passed as an inner query, we # make sure it's only requesting a single value and use that as the # thing to select. self.assertQuerysetEqual( Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values('name')), ['<Tag: t2>', '<Tag: t3>'] ) # Multi-valued values() and values_list() querysets should raise errors. with self.assertRaisesMessage(TypeError, 'Cannot use multi-field values as a filter value.'): Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values('name', 'id')) with self.assertRaisesMessage(TypeError, 'Cannot use multi-field values as a filter value.'): Tag.objects.filter(name__in=Tag.objects.filter(parent=self.t1).values_list('name', 'id')) def test_ticket9985(self): # qs.values_list(...).values(...) combinations should work. self.assertSequenceEqual( Note.objects.values_list("note", flat=True).values("id").order_by("id"), [{'id': 1}, {'id': 2}, {'id': 3}] ) self.assertQuerysetEqual( Annotation.objects.filter(notes__in=Note.objects.filter(note="n1").values_list('note').values('id')), ['<Annotation: a1>'] ) def test_ticket10205(self): # When bailing out early because of an empty "__in" filter, we need # to set things up correctly internally so that subqueries can continue properly. self.assertEqual(Tag.objects.filter(name__in=()).update(name="foo"), 0) def test_ticket10432(self): # Testing an empty "__in" filter with a generator as the value. def f(): return iter([]) n_obj = Note.objects.all()[0] def g(): yield n_obj.pk self.assertQuerysetEqual(Note.objects.filter(pk__in=f()), []) self.assertEqual(list(Note.objects.filter(pk__in=g())), [n_obj]) def test_ticket10742(self): # Queries used in an __in clause don't execute subqueries subq = Author.objects.filter(num__lt=3000) qs = Author.objects.filter(pk__in=subq) self.assertQuerysetEqual(qs, ['<Author: a1>', '<Author: a2>']) # The subquery result cache should not be populated self.assertIsNone(subq._result_cache) subq = Author.objects.filter(num__lt=3000) qs = Author.objects.exclude(pk__in=subq) self.assertQuerysetEqual(qs, ['<Author: a3>', '<Author: a4>']) # The subquery result cache should not be populated self.assertIsNone(subq._result_cache) subq = Author.objects.filter(num__lt=3000) self.assertQuerysetEqual( Author.objects.filter(Q(pk__in=subq) & Q(name='a1')), ['<Author: a1>'] ) # The subquery result cache should not be populated self.assertIsNone(subq._result_cache) def test_ticket7076(self): # Excluding shouldn't eliminate NULL entries. self.assertQuerysetEqual( Item.objects.exclude(modified=self.time1).order_by('name'), ['<Item: four>', '<Item: three>', '<Item: two>'] ) self.assertQuerysetEqual( Tag.objects.exclude(parent__name=self.t1.name), ['<Tag: t1>', '<Tag: t4>', '<Tag: t5>'] ) def test_ticket7181(self): # Ordering by related tables should accommodate nullable fields (this # test is a little tricky, since NULL ordering is database dependent. # Instead, we just count the number of results). self.assertEqual(len(Tag.objects.order_by('parent__name')), 5) # Empty querysets can be merged with others. self.assertQuerysetEqual( Note.objects.none() | Note.objects.all(), ['<Note: n1>', '<Note: n2>', '<Note: n3>'] ) self.assertQuerysetEqual( Note.objects.all() | Note.objects.none(), ['<Note: n1>', '<Note: n2>', '<Note: n3>'] ) self.assertQuerysetEqual(Note.objects.none() & Note.objects.all(), []) self.assertQuerysetEqual(Note.objects.all() & Note.objects.none(), []) def test_ticket9411(self): # Make sure bump_prefix() (an internal Query method) doesn't (re-)break. It's # sufficient that this query runs without error. qs = Tag.objects.values_list('id', flat=True).order_by('id') qs.query.bump_prefix(qs.query) first = qs[0] self.assertEqual(list(qs), list(range(first, first + 5))) def test_ticket8439(self): # Complex combinations of conjunctions, disjunctions and nullable # relations. self.assertQuerysetEqual( Author.objects.filter(Q(item__note__extrainfo=self.e2) | Q(report=self.r1, name='xyz')), ['<Author: a2>'] ) self.assertQuerysetEqual( Author.objects.filter(Q(report=self.r1, name='xyz') | Q(item__note__extrainfo=self.e2)), ['<Author: a2>'] ) self.assertQuerysetEqual( Annotation.objects.filter(Q(tag__parent=self.t1) | Q(notes__note='n1', name='a1')), ['<Annotation: a1>'] ) xx = ExtraInfo.objects.create(info='xx', note=self.n3) self.assertQuerysetEqual( Note.objects.filter(Q(extrainfo__author=self.a1) | Q(extrainfo=xx)), ['<Note: n1>', '<Note: n3>'] ) q = Note.objects.filter(Q(extrainfo__author=self.a1) | Q(extrainfo=xx)).query self.assertEqual( len([x for x in q.alias_map.values() if x.join_type == LOUTER and q.alias_refcount[x.table_alias]]), 1 ) def test_ticket17429(self): """ Meta.ordering=None works the same as Meta.ordering=[] """ original_ordering = Tag._meta.ordering Tag._meta.ordering = None try: self.assertQuerysetEqual( Tag.objects.all(), ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ordered=False ) finally: Tag._meta.ordering = original_ordering def test_exclude(self): self.assertQuerysetEqual( Item.objects.exclude(tags__name='t4'), [repr(i) for i in Item.objects.filter(~Q(tags__name='t4'))]) self.assertQuerysetEqual( Item.objects.exclude(Q(tags__name='t4') | Q(tags__name='t3')), [repr(i) for i in Item.objects.filter(~(Q(tags__name='t4') | Q(tags__name='t3')))]) self.assertQuerysetEqual( Item.objects.exclude(Q(tags__name='t4') | ~Q(tags__name='t3')), [repr(i) for i in Item.objects.filter(~(Q(tags__name='t4') | ~Q(tags__name='t3')))]) def test_nested_exclude(self): self.assertQuerysetEqual( Item.objects.exclude(~Q(tags__name='t4')), [repr(i) for i in Item.objects.filter(~~Q(tags__name='t4'))]) def test_double_exclude(self): self.assertQuerysetEqual( Item.objects.filter(Q(tags__name='t4')), [repr(i) for i in Item.objects.filter(~~Q(tags__name='t4'))]) self.assertQuerysetEqual( Item.objects.filter(Q(tags__name='t4')), [repr(i) for i in Item.objects.filter(~Q(~Q(tags__name='t4')))]) def test_exclude_in(self): self.assertQuerysetEqual( Item.objects.exclude(Q(tags__name__in=['t4', 't3'])), [repr(i) for i in Item.objects.filter(~Q(tags__name__in=['t4', 't3']))]) self.assertQuerysetEqual( Item.objects.filter(Q(tags__name__in=['t4', 't3'])), [repr(i) for i in Item.objects.filter(~~Q(tags__name__in=['t4', 't3']))]) def test_ticket_10790_1(self): # Querying direct fields with isnull should trim the left outer join. # It also should not create INNER JOIN. q = Tag.objects.filter(parent__isnull=True) self.assertQuerysetEqual(q, ['<Tag: t1>']) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.filter(parent__isnull=False) self.assertQuerysetEqual( q, ['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.exclude(parent__isnull=True) self.assertQuerysetEqual( q, ['<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.exclude(parent__isnull=False) self.assertQuerysetEqual(q, ['<Tag: t1>']) self.assertNotIn('JOIN', str(q.query)) q = Tag.objects.exclude(parent__parent__isnull=False) self.assertQuerysetEqual( q, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) self.assertNotIn('INNER JOIN', str(q.query)) def test_ticket_10790_2(self): # Querying across several tables should strip only the last outer join, # while preserving the preceding inner joins. q = Tag.objects.filter(parent__parent__isnull=False) self.assertQuerysetEqual( q, ['<Tag: t4>', '<Tag: t5>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 1) # Querying without isnull should not convert anything to left outer join. q = Tag.objects.filter(parent__parent=self.t1) self.assertQuerysetEqual( q, ['<Tag: t4>', '<Tag: t5>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 1) def test_ticket_10790_3(self): # Querying via indirect fields should populate the left outer join q = NamedCategory.objects.filter(tag__isnull=True) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) # join to dumbcategory ptr_id self.assertEqual(str(q.query).count('INNER JOIN'), 1) self.assertQuerysetEqual(q, []) # Querying across several tables should strip only the last join, while # preserving the preceding left outer joins. q = NamedCategory.objects.filter(tag__parent__isnull=True) self.assertEqual(str(q.query).count('INNER JOIN'), 1) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) self.assertQuerysetEqual(q, ['<NamedCategory: Generic>']) def test_ticket_10790_4(self): # Querying across m2m field should not strip the m2m table from join. q = Author.objects.filter(item__tags__isnull=True) self.assertQuerysetEqual( q, ['<Author: a2>', '<Author: a3>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 2) self.assertNotIn('INNER JOIN', str(q.query)) q = Author.objects.filter(item__tags__parent__isnull=True) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>'], ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3) self.assertNotIn('INNER JOIN', str(q.query)) def test_ticket_10790_5(self): # Querying with isnull=False across m2m field should not create outer joins q = Author.objects.filter(item__tags__isnull=False) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 2) q = Author.objects.filter(item__tags__parent__isnull=False) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 3) q = Author.objects.filter(item__tags__parent__parent__isnull=False) self.assertQuerysetEqual( q, ['<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 4) def test_ticket_10790_6(self): # Querying with isnull=True across m2m field should not create inner joins # and strip last outer join q = Author.objects.filter(item__tags__parent__parent__isnull=True) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a2>', '<Author: a3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 4) self.assertEqual(str(q.query).count('INNER JOIN'), 0) q = Author.objects.filter(item__tags__parent__isnull=True) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 3) self.assertEqual(str(q.query).count('INNER JOIN'), 0) def test_ticket_10790_7(self): # Reverse querying with isnull should not strip the join q = Author.objects.filter(item__isnull=True) self.assertQuerysetEqual( q, ['<Author: a3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(q.query).count('INNER JOIN'), 0) q = Author.objects.filter(item__isnull=False) self.assertQuerysetEqual( q, ['<Author: a1>', '<Author: a2>', '<Author: a2>', '<Author: a4>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 1) def test_ticket_10790_8(self): # Querying with combined q-objects should also strip the left outer join q = Tag.objects.filter(Q(parent__isnull=True) | Q(parent=self.t1)) self.assertQuerysetEqual( q, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q.query).count('INNER JOIN'), 0) def test_ticket_10790_combine(self): # Combining queries should not re-populate the left outer join q1 = Tag.objects.filter(parent__isnull=True) q2 = Tag.objects.filter(parent__isnull=False) q3 = q1 | q2 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>', '<Tag: t4>', '<Tag: t5>'], ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q3 = q1 & q2 self.assertQuerysetEqual(q3, []) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q2 = Tag.objects.filter(parent=self.t1) q3 = q1 | q2 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q3 = q2 | q1 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q1 = Tag.objects.filter(parent__isnull=True) q2 = Tag.objects.filter(parent__parent__isnull=True) q3 = q1 | q2 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) q3 = q2 | q1 self.assertQuerysetEqual( q3, ['<Tag: t1>', '<Tag: t2>', '<Tag: t3>'] ) self.assertEqual(str(q3.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(q3.query).count('INNER JOIN'), 0) def test_ticket19672(self): self.assertQuerysetEqual( Report.objects.filter(Q(creator__isnull=False) & ~Q(creator__extra__value=41)), ['<Report: r1>'] ) def test_ticket_20250(self): # A negated Q along with an annotated queryset failed in Django 1.4 qs = Author.objects.annotate(Count('item')) qs = qs.filter(~Q(extra__value=0)).order_by('name') self.assertIn('SELECT', str(qs.query)) self.assertQuerysetEqual( qs, ['<Author: a1>', '<Author: a2>', '<Author: a3>', '<Author: a4>'] ) def test_lookup_constraint_fielderror(self): msg = ( "Cannot resolve keyword 'unknown_field' into field. Choices are: " "annotation, category, category_id, children, id, item, " "managedmodel, name, note, parent, parent_id" ) with self.assertRaisesMessage(FieldError, msg): Tag.objects.filter(unknown_field__name='generic') def test_common_mixed_case_foreign_keys(self): """ Valid query should be generated when fields fetched from joined tables include FKs whose names only differ by case. """ c1 = SimpleCategory.objects.create(name='c1') c2 = SimpleCategory.objects.create(name='c2') c3 = SimpleCategory.objects.create(name='c3') category = CategoryItem.objects.create(category=c1) mixed_case_field_category = MixedCaseFieldCategoryItem.objects.create(CaTeGoRy=c2) mixed_case_db_column_category = MixedCaseDbColumnCategoryItem.objects.create(category=c3) CommonMixedCaseForeignKeys.objects.create( category=category, mixed_case_field_category=mixed_case_field_category, mixed_case_db_column_category=mixed_case_db_column_category, ) qs = CommonMixedCaseForeignKeys.objects.values( 'category', 'mixed_case_field_category', 'mixed_case_db_column_category', 'category__category', 'mixed_case_field_category__CaTeGoRy', 'mixed_case_db_column_category__category', ) self.assertTrue(qs.first()) def test_excluded_intermediary_m2m_table_joined(self): self.assertSequenceEqual( Note.objects.filter(~Q(tag__annotation__name=F('note'))), [self.n1, self.n2, self.n3], ) self.assertSequenceEqual( Note.objects.filter(tag__annotation__name='a1').filter(~Q(tag__annotation__name=F('note'))), [], ) class Queries2Tests(TestCase): @classmethod def setUpTestData(cls): Number.objects.create(num=4) Number.objects.create(num=8) Number.objects.create(num=12) def test_ticket4289(self): # A slight variation on the restricting the filtering choices by the # lookup constraints. self.assertQuerysetEqual(Number.objects.filter(num__lt=4), []) self.assertQuerysetEqual(Number.objects.filter(num__gt=8, num__lt=12), []) self.assertQuerysetEqual( Number.objects.filter(num__gt=8, num__lt=13), ['<Number: 12>'] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__lt=4) | Q(num__gt=8, num__lt=12)), [] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__gt=8, num__lt=12) | Q(num__lt=4)), [] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__gt=8) & Q(num__lt=12) | Q(num__lt=4)), [] ) self.assertQuerysetEqual( Number.objects.filter(Q(num__gt=7) & Q(num__lt=12) | Q(num__lt=4)), ['<Number: 8>'] ) def test_ticket12239(self): # Custom lookups are registered to round float values correctly on gte # and lt IntegerField queries. self.assertQuerysetEqual( Number.objects.filter(num__gt=11.9), ['<Number: 12>'] ) self.assertQuerysetEqual(Number.objects.filter(num__gt=12), []) self.assertQuerysetEqual(Number.objects.filter(num__gt=12.0), []) self.assertQuerysetEqual(Number.objects.filter(num__gt=12.1), []) self.assertQuerysetEqual( Number.objects.filter(num__lt=12), ['<Number: 4>', '<Number: 8>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lt=12.0), ['<Number: 4>', '<Number: 8>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lt=12.1), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__gte=11.9), ['<Number: 12>'] ) self.assertQuerysetEqual( Number.objects.filter(num__gte=12), ['<Number: 12>'] ) self.assertQuerysetEqual( Number.objects.filter(num__gte=12.0), ['<Number: 12>'] ) self.assertQuerysetEqual(Number.objects.filter(num__gte=12.1), []) self.assertQuerysetEqual(Number.objects.filter(num__gte=12.9), []) self.assertQuerysetEqual( Number.objects.filter(num__lte=11.9), ['<Number: 4>', '<Number: 8>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12.0), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12.1), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) self.assertQuerysetEqual( Number.objects.filter(num__lte=12.9), ['<Number: 4>', '<Number: 8>', '<Number: 12>'], ordered=False ) def test_ticket7759(self): # Count should work with a partially read result set. count = Number.objects.count() qs = Number.objects.all() def run(): for obj in qs: return qs.count() == count self.assertTrue(run()) class Queries3Tests(TestCase): def test_ticket7107(self): # This shouldn't create an infinite loop. self.assertQuerysetEqual(Valid.objects.all(), []) def test_ticket8683(self): # An error should be raised when QuerySet.datetimes() is passed the # wrong type of field. with self.assertRaisesMessage(AssertionError, "'name' isn't a DateField, TimeField, or DateTimeField."): Item.objects.datetimes('name', 'month') def test_ticket22023(self): with self.assertRaisesMessage(TypeError, "Cannot call only() after .values() or .values_list()"): Valid.objects.values().only() with self.assertRaisesMessage(TypeError, "Cannot call defer() after .values() or .values_list()"): Valid.objects.values().defer() class Queries4Tests(TestCase): @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") cls.t1 = Tag.objects.create(name='t1', category=generic) n1 = Note.objects.create(note='n1', misc='foo') n2 = Note.objects.create(note='n2', misc='bar') e1 = ExtraInfo.objects.create(info='e1', note=n1) e2 = ExtraInfo.objects.create(info='e2', note=n2) cls.a1 = Author.objects.create(name='a1', num=1001, extra=e1) cls.a3 = Author.objects.create(name='a3', num=3003, extra=e2) cls.r1 = Report.objects.create(name='r1', creator=cls.a1) cls.r2 = Report.objects.create(name='r2', creator=cls.a3) cls.r3 = Report.objects.create(name='r3') Item.objects.create(name='i1', created=datetime.datetime.now(), note=n1, creator=cls.a1) Item.objects.create(name='i2', created=datetime.datetime.now(), note=n1, creator=cls.a3) def test_ticket24525(self): tag = Tag.objects.create() anth100 = tag.note_set.create(note='ANTH', misc='100') math101 = tag.note_set.create(note='MATH', misc='101') s1 = tag.annotation_set.create(name='1') s2 = tag.annotation_set.create(name='2') s1.notes.set([math101, anth100]) s2.notes.set([math101]) result = math101.annotation_set.all() & tag.annotation_set.exclude(notes__in=[anth100]) self.assertEqual(list(result), [s2]) def test_ticket11811(self): unsaved_category = NamedCategory(name="Other") msg = 'Unsaved model instance <NamedCategory: Other> cannot be used in an ORM query.' with self.assertRaisesMessage(ValueError, msg): Tag.objects.filter(pk=self.t1.pk).update(category=unsaved_category) def test_ticket14876(self): # Note: when combining the query we need to have information available # about the join type of the trimmed "creator__isnull" join. If we # don't have that information, then the join is created as INNER JOIN # and results will be incorrect. q1 = Report.objects.filter(Q(creator__isnull=True) | Q(creator__extra__info='e1')) q2 = Report.objects.filter(Q(creator__isnull=True)) | Report.objects.filter(Q(creator__extra__info='e1')) self.assertQuerysetEqual(q1, ["<Report: r1>", "<Report: r3>"], ordered=False) self.assertEqual(str(q1.query), str(q2.query)) q1 = Report.objects.filter(Q(creator__extra__info='e1') | Q(creator__isnull=True)) q2 = Report.objects.filter(Q(creator__extra__info='e1')) | Report.objects.filter(Q(creator__isnull=True)) self.assertQuerysetEqual(q1, ["<Report: r1>", "<Report: r3>"], ordered=False) self.assertEqual(str(q1.query), str(q2.query)) q1 = Item.objects.filter(Q(creator=self.a1) | Q(creator__report__name='r1')).order_by() q2 = ( Item.objects .filter(Q(creator=self.a1)).order_by() | Item.objects.filter(Q(creator__report__name='r1')) .order_by() ) self.assertQuerysetEqual(q1, ["<Item: i1>"]) self.assertEqual(str(q1.query), str(q2.query)) q1 = Item.objects.filter(Q(creator__report__name='e1') | Q(creator=self.a1)).order_by() q2 = ( Item.objects.filter(Q(creator__report__name='e1')).order_by() | Item.objects.filter(Q(creator=self.a1)).order_by() ) self.assertQuerysetEqual(q1, ["<Item: i1>"]) self.assertEqual(str(q1.query), str(q2.query)) def test_combine_join_reuse(self): # Joins having identical connections are correctly recreated in the # rhs query, in case the query is ORed together (#18748). Report.objects.create(name='r4', creator=self.a1) q1 = Author.objects.filter(report__name='r5') q2 = Author.objects.filter(report__name='r4').filter(report__name='r1') combined = q1 | q2 self.assertEqual(str(combined.query).count('JOIN'), 2) self.assertEqual(len(combined), 1) self.assertEqual(combined[0].name, 'a1') def test_join_reuse_order(self): # Join aliases are reused in order. This shouldn't raise AssertionError # because change_map contains a circular reference (#26522). s1 = School.objects.create() s2 = School.objects.create() s3 = School.objects.create() t1 = Teacher.objects.create() otherteachers = Teacher.objects.exclude(pk=t1.pk).exclude(friends=t1) qs1 = otherteachers.filter(schools=s1).filter(schools=s2) qs2 = otherteachers.filter(schools=s1).filter(schools=s3) self.assertQuerysetEqual(qs1 | qs2, []) def test_ticket7095(self): # Updates that are filtered on the model being updated are somewhat # tricky in MySQL. ManagedModel.objects.create(data='mm1', tag=self.t1, public=True) self.assertEqual(ManagedModel.objects.update(data='mm'), 1) # A values() or values_list() query across joined models must use outer # joins appropriately. # Note: In Oracle, we expect a null CharField to return '' instead of # None. if connection.features.interprets_empty_strings_as_nulls: expected_null_charfield_repr = '' else: expected_null_charfield_repr = None self.assertSequenceEqual( Report.objects.values_list("creator__extra__info", flat=True).order_by("name"), ['e1', 'e2', expected_null_charfield_repr], ) # Similarly for select_related(), joins beyond an initial nullable join # must use outer joins so that all results are included. self.assertQuerysetEqual( Report.objects.select_related("creator", "creator__extra").order_by("name"), ['<Report: r1>', '<Report: r2>', '<Report: r3>'] ) # When there are multiple paths to a table from another table, we have # to be careful not to accidentally reuse an inappropriate join when # using select_related(). We used to return the parent's Detail record # here by mistake. d1 = Detail.objects.create(data="d1") d2 = Detail.objects.create(data="d2") m1 = Member.objects.create(name="m1", details=d1) m2 = Member.objects.create(name="m2", details=d2) Child.objects.create(person=m2, parent=m1) obj = m1.children.select_related("person__details")[0] self.assertEqual(obj.person.details.data, 'd2') def test_order_by_resetting(self): # Calling order_by() with no parameters removes any existing ordering on the # model. But it should still be possible to add new ordering after that. qs = Author.objects.order_by().order_by('name') self.assertIn('ORDER BY', qs.query.get_compiler(qs.db).as_sql()[0]) def test_order_by_reverse_fk(self): # It is possible to order by reverse of foreign key, although that can lead # to duplicate results. c1 = SimpleCategory.objects.create(name="category1") c2 = SimpleCategory.objects.create(name="category2") CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c1) self.assertSequenceEqual(SimpleCategory.objects.order_by('categoryitem', 'pk'), [c1, c2, c1]) def test_ticket10181(self): # Avoid raising an EmptyResultSet if an inner query is probably # empty (and hence, not executed). self.assertQuerysetEqual( Tag.objects.filter(id__in=Tag.objects.filter(id__in=[])), [] ) def test_ticket15316_filter_false(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") CategoryItem.objects.create(category=c1) ci2 = CategoryItem.objects.create(category=c2) ci3 = CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.filter(category__specialcategory__isnull=False) self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) def test_ticket15316_exclude_false(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") ci1 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.exclude(category__specialcategory__isnull=False) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_filter_true(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") ci1 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.filter(category__specialcategory__isnull=True) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_exclude_true(self): c1 = SimpleCategory.objects.create(name="category1") c2 = SpecialCategory.objects.create(name="named category1", special_name="special1") c3 = SpecialCategory.objects.create(name="named category2", special_name="special2") CategoryItem.objects.create(category=c1) ci2 = CategoryItem.objects.create(category=c2) ci3 = CategoryItem.objects.create(category=c3) qs = CategoryItem.objects.exclude(category__specialcategory__isnull=True) self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) def test_ticket15316_one2one_filter_false(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") CategoryItem.objects.create(category=c) ci2 = CategoryItem.objects.create(category=c0) ci3 = CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.filter(category__onetoonecategory__isnull=False).order_by('pk') self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) def test_ticket15316_one2one_exclude_false(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") ci1 = CategoryItem.objects.create(category=c) CategoryItem.objects.create(category=c0) CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.exclude(category__onetoonecategory__isnull=False) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_one2one_filter_true(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") ci1 = CategoryItem.objects.create(category=c) CategoryItem.objects.create(category=c0) CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.filter(category__onetoonecategory__isnull=True) self.assertEqual(qs.count(), 1) self.assertSequenceEqual(qs, [ci1]) def test_ticket15316_one2one_exclude_true(self): c = SimpleCategory.objects.create(name="cat") c0 = SimpleCategory.objects.create(name="cat0") c1 = SimpleCategory.objects.create(name="category1") OneToOneCategory.objects.create(category=c1, new_name="new1") OneToOneCategory.objects.create(category=c0, new_name="new2") CategoryItem.objects.create(category=c) ci2 = CategoryItem.objects.create(category=c0) ci3 = CategoryItem.objects.create(category=c1) qs = CategoryItem.objects.exclude(category__onetoonecategory__isnull=True).order_by('pk') self.assertEqual(qs.count(), 2) self.assertSequenceEqual(qs, [ci2, ci3]) class Queries5Tests(TestCase): @classmethod def setUpTestData(cls): # Ordering by 'rank' gives us rank2, rank1, rank3. Ordering by the # Meta.ordering will be rank3, rank2, rank1. n1 = Note.objects.create(note='n1', misc='foo', id=1) n2 = Note.objects.create(note='n2', misc='bar', id=2) e1 = ExtraInfo.objects.create(info='e1', note=n1) e2 = ExtraInfo.objects.create(info='e2', note=n2) a1 = Author.objects.create(name='a1', num=1001, extra=e1) a2 = Author.objects.create(name='a2', num=2002, extra=e1) a3 = Author.objects.create(name='a3', num=3003, extra=e2) cls.rank1 = Ranking.objects.create(rank=2, author=a2) Ranking.objects.create(rank=1, author=a3) Ranking.objects.create(rank=3, author=a1) def test_ordering(self): # Cross model ordering is possible in Meta, too. self.assertQuerysetEqual( Ranking.objects.all(), ['<Ranking: 3: a1>', '<Ranking: 2: a2>', '<Ranking: 1: a3>'] ) self.assertQuerysetEqual( Ranking.objects.all().order_by('rank'), ['<Ranking: 1: a3>', '<Ranking: 2: a2>', '<Ranking: 3: a1>'] ) # Ordering of extra() pieces is possible, too and you can mix extra # fields and model fields in the ordering. self.assertQuerysetEqual( Ranking.objects.extra(tables=['django_site'], order_by=['-django_site.id', 'rank']), ['<Ranking: 1: a3>', '<Ranking: 2: a2>', '<Ranking: 3: a1>'] ) sql = 'case when %s > 2 then 1 else 0 end' % connection.ops.quote_name('rank') qs = Ranking.objects.extra(select={'good': sql}) self.assertEqual( [o.good for o in qs.extra(order_by=('-good',))], [True, False, False] ) self.assertQuerysetEqual( qs.extra(order_by=('-good', 'id')), ['<Ranking: 3: a1>', '<Ranking: 2: a2>', '<Ranking: 1: a3>'] ) # Despite having some extra aliases in the query, we can still omit # them in a values() query. dicts = qs.values('id', 'rank').order_by('id') self.assertEqual( [d['rank'] for d in dicts], [2, 1, 3] ) def test_ticket7256(self): # An empty values() call includes all aliases, including those from an # extra() sql = 'case when %s > 2 then 1 else 0 end' % connection.ops.quote_name('rank') qs = Ranking.objects.extra(select={'good': sql}) dicts = qs.values().order_by('id') for d in dicts: del d['id'] del d['author_id'] self.assertEqual( [sorted(d.items()) for d in dicts], [[('good', 0), ('rank', 2)], [('good', 0), ('rank', 1)], [('good', 1), ('rank', 3)]] ) def test_ticket7045(self): # Extra tables used to crash SQL construction on the second use. qs = Ranking.objects.extra(tables=['django_site']) qs.query.get_compiler(qs.db).as_sql() # test passes if this doesn't raise an exception. qs.query.get_compiler(qs.db).as_sql() def test_ticket9848(self): # Make sure that updates which only filter on sub-tables don't # inadvertently update the wrong records (bug #9848). author_start = Author.objects.get(name='a1') ranking_start = Ranking.objects.get(author__name='a1') # Make sure that the IDs from different tables don't happen to match. self.assertQuerysetEqual( Ranking.objects.filter(author__name='a1'), ['<Ranking: 3: a1>'] ) self.assertEqual( Ranking.objects.filter(author__name='a1').update(rank=4636), 1 ) r = Ranking.objects.get(author__name='a1') self.assertEqual(r.id, ranking_start.id) self.assertEqual(r.author.id, author_start.id) self.assertEqual(r.rank, 4636) r.rank = 3 r.save() self.assertQuerysetEqual( Ranking.objects.all(), ['<Ranking: 3: a1>', '<Ranking: 2: a2>', '<Ranking: 1: a3>'] ) def test_ticket5261(self): # Test different empty excludes. self.assertQuerysetEqual( Note.objects.exclude(Q()), ['<Note: n1>', '<Note: n2>'] ) self.assertQuerysetEqual( Note.objects.filter(~Q()), ['<Note: n1>', '<Note: n2>'] ) self.assertQuerysetEqual( Note.objects.filter(~Q() | ~Q()), ['<Note: n1>', '<Note: n2>'] ) self.assertQuerysetEqual( Note.objects.exclude(~Q() & ~Q()), ['<Note: n1>', '<Note: n2>'] ) def test_extra_select_literal_percent_s(self): # Allow %%s to escape select clauses self.assertEqual( Note.objects.extra(select={'foo': "'%%s'"})[0].foo, '%s' ) self.assertEqual( Note.objects.extra(select={'foo': "'%%s bar %%s'"})[0].foo, '%s bar %s' ) self.assertEqual( Note.objects.extra(select={'foo': "'bar %%s'"})[0].foo, 'bar %s' ) class SelectRelatedTests(TestCase): def test_tickets_3045_3288(self): # Once upon a time, select_related() with circular relations would loop # infinitely if you forgot to specify "depth". Now we set an arbitrary # default upper bound. self.assertQuerysetEqual(X.objects.all(), []) self.assertQuerysetEqual(X.objects.select_related(), []) class SubclassFKTests(TestCase): def test_ticket7778(self): # Model subclasses could not be deleted if a nullable foreign key # relates to a model that relates back. num_celebs = Celebrity.objects.count() tvc = TvChef.objects.create(name="Huey") self.assertEqual(Celebrity.objects.count(), num_celebs + 1) Fan.objects.create(fan_of=tvc) Fan.objects.create(fan_of=tvc) tvc.delete() # The parent object should have been deleted as well. self.assertEqual(Celebrity.objects.count(), num_celebs) class CustomPkTests(TestCase): def test_ticket7371(self): self.assertQuerysetEqual(Related.objects.order_by('custom'), []) class NullableRelOrderingTests(TestCase): def test_ticket10028(self): # Ordering by model related to nullable relations(!) should use outer # joins, so that all results are included. Plaything.objects.create(name="p1") self.assertQuerysetEqual( Plaything.objects.all(), ['<Plaything: p1>'] ) def test_join_already_in_query(self): # Ordering by model related to nullable relations should not change # the join type of already existing joins. Plaything.objects.create(name="p1") s = SingleObject.objects.create(name='s') r = RelatedObject.objects.create(single=s, f=1) Plaything.objects.create(name="p2", others=r) qs = Plaything.objects.all().filter(others__isnull=False).order_by('pk') self.assertNotIn('JOIN', str(qs.query)) qs = Plaything.objects.all().filter(others__f__isnull=False).order_by('pk') self.assertIn('INNER', str(qs.query)) qs = qs.order_by('others__single__name') # The ordering by others__single__pk will add one new join (to single) # and that join must be LEFT join. The already existing join to related # objects must be kept INNER. So, we have both an INNER and a LEFT join # in the query. self.assertEqual(str(qs.query).count('LEFT'), 1) self.assertEqual(str(qs.query).count('INNER'), 1) self.assertQuerysetEqual( qs, ['<Plaything: p2>'] ) class DisjunctiveFilterTests(TestCase): @classmethod def setUpTestData(cls): cls.n1 = Note.objects.create(note='n1', misc='foo', id=1) ExtraInfo.objects.create(info='e1', note=cls.n1) def test_ticket7872(self): # Another variation on the disjunctive filtering theme. # For the purposes of this regression test, it's important that there is no # Join object related to the LeafA we create. LeafA.objects.create(data='first') self.assertQuerysetEqual(LeafA.objects.all(), ['<LeafA: first>']) self.assertQuerysetEqual( LeafA.objects.filter(Q(data='first') | Q(join__b__data='second')), ['<LeafA: first>'] ) def test_ticket8283(self): # Checking that applying filters after a disjunction works correctly. self.assertQuerysetEqual( (ExtraInfo.objects.filter(note=self.n1) | ExtraInfo.objects.filter(info='e2')).filter(note=self.n1), ['<ExtraInfo: e1>'] ) self.assertQuerysetEqual( (ExtraInfo.objects.filter(info='e2') | ExtraInfo.objects.filter(note=self.n1)).filter(note=self.n1), ['<ExtraInfo: e1>'] ) class Queries6Tests(TestCase): @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") cls.t1 = Tag.objects.create(name='t1', category=generic) cls.t2 = Tag.objects.create(name='t2', parent=cls.t1, category=generic) cls.t3 = Tag.objects.create(name='t3', parent=cls.t1) cls.t4 = Tag.objects.create(name='t4', parent=cls.t3) cls.t5 = Tag.objects.create(name='t5', parent=cls.t3) n1 = Note.objects.create(note='n1', misc='foo', id=1) ann1 = Annotation.objects.create(name='a1', tag=cls.t1) ann1.notes.add(n1) Annotation.objects.create(name='a2', tag=cls.t4) def test_parallel_iterators(self): # Parallel iterators work. qs = Tag.objects.all() i1, i2 = iter(qs), iter(qs) self.assertEqual(repr(next(i1)), '<Tag: t1>') self.assertEqual(repr(next(i1)), '<Tag: t2>') self.assertEqual(repr(next(i2)), '<Tag: t1>') self.assertEqual(repr(next(i2)), '<Tag: t2>') self.assertEqual(repr(next(i2)), '<Tag: t3>') self.assertEqual(repr(next(i1)), '<Tag: t3>') qs = X.objects.all() self.assertFalse(qs) self.assertFalse(qs) def test_nested_queries_sql(self): # Nested queries should not evaluate the inner query as part of constructing the # SQL (so we should see a nested query here, indicated by two "SELECT" calls). qs = Annotation.objects.filter(notes__in=Note.objects.filter(note="xyzzy")) self.assertEqual( qs.query.get_compiler(qs.db).as_sql()[0].count('SELECT'), 2 ) def test_tickets_8921_9188(self): # Incorrect SQL was being generated for certain types of exclude() # queries that crossed multi-valued relations (#8921, #9188 and some # preemptively discovered cases). self.assertQuerysetEqual( PointerA.objects.filter(connection__pointerb__id=1), [] ) self.assertQuerysetEqual( PointerA.objects.exclude(connection__pointerb__id=1), [] ) self.assertQuerysetEqual( Tag.objects.exclude(children=None), ['<Tag: t1>', '<Tag: t3>'] ) # This example is tricky because the parent could be NULL, so only checking # parents with annotations omits some results (tag t1, in this case). self.assertQuerysetEqual( Tag.objects.exclude(parent__annotation__name="a1"), ['<Tag: t1>', '<Tag: t4>', '<Tag: t5>'] ) # The annotation->tag link is single values and tag->children links is # multi-valued. So we have to split the exclude filter in the middle # and then optimize the inner query without losing results. self.assertQuerysetEqual( Annotation.objects.exclude(tag__children__name="t2"), ['<Annotation: a2>'] ) # Nested queries are possible (although should be used with care, since # they have performance problems on backends like MySQL. self.assertQuerysetEqual( Annotation.objects.filter(notes__in=Note.objects.filter(note="n1")), ['<Annotation: a1>'] ) def test_ticket3739(self): # The all() method on querysets returns a copy of the queryset. q1 = Tag.objects.order_by('name') self.assertIsNot(q1, q1.all()) def test_ticket_11320(self): qs = Tag.objects.exclude(category=None).exclude(category__name='foo') self.assertEqual(str(qs.query).count(' INNER JOIN '), 1) def test_distinct_ordered_sliced_subquery_aggregation(self): self.assertEqual(Tag.objects.distinct().order_by('category__name')[:3].count(), 3) def test_multiple_columns_with_the_same_name_slice(self): self.assertEqual( list(Tag.objects.order_by('name').values_list('name', 'category__name')[:2]), [('t1', 'Generic'), ('t2', 'Generic')], ) self.assertSequenceEqual( Tag.objects.order_by('name').select_related('category')[:2], [self.t1, self.t2], ) self.assertEqual( list(Tag.objects.order_by('-name').values_list('name', 'parent__name')[:2]), [('t5', 't3'), ('t4', 't3')], ) self.assertSequenceEqual( Tag.objects.order_by('-name').select_related('parent')[:2], [self.t5, self.t4], ) class RawQueriesTests(TestCase): def setUp(self): Note.objects.create(note='n1', misc='foo', id=1) def test_ticket14729(self): # Test representation of raw query with one or few parameters passed as list query = "SELECT * FROM queries_note WHERE note = %s" params = ['n1'] qs = Note.objects.raw(query, params=params) self.assertEqual(repr(qs), "<RawQuerySet: SELECT * FROM queries_note WHERE note = n1>") query = "SELECT * FROM queries_note WHERE note = %s and misc = %s" params = ['n1', 'foo'] qs = Note.objects.raw(query, params=params) self.assertEqual(repr(qs), "<RawQuerySet: SELECT * FROM queries_note WHERE note = n1 and misc = foo>") class GeneratorExpressionTests(SimpleTestCase): def test_ticket10432(self): # Using an empty iterator as the rvalue for an "__in" # lookup is legal. self.assertCountEqual(Note.objects.filter(pk__in=iter(())), []) class ComparisonTests(TestCase): def setUp(self): self.n1 = Note.objects.create(note='n1', misc='foo', id=1) e1 = ExtraInfo.objects.create(info='e1', note=self.n1) self.a2 = Author.objects.create(name='a2', num=2002, extra=e1) def test_ticket8597(self): # Regression tests for case-insensitive comparisons Item.objects.create(name="a_b", created=datetime.datetime.now(), creator=self.a2, note=self.n1) Item.objects.create(name="x%y", created=datetime.datetime.now(), creator=self.a2, note=self.n1) self.assertQuerysetEqual( Item.objects.filter(name__iexact="A_b"), ['<Item: a_b>'] ) self.assertQuerysetEqual( Item.objects.filter(name__iexact="x%Y"), ['<Item: x%y>'] ) self.assertQuerysetEqual( Item.objects.filter(name__istartswith="A_b"), ['<Item: a_b>'] ) self.assertQuerysetEqual( Item.objects.filter(name__iendswith="A_b"), ['<Item: a_b>'] ) class ExistsSql(TestCase): def test_exists(self): with CaptureQueriesContext(connection) as captured_queries: self.assertFalse(Tag.objects.exists()) # Ok - so the exist query worked - but did it include too many columns? self.assertEqual(len(captured_queries), 1) qstr = captured_queries[0]['sql'] id, name = connection.ops.quote_name('id'), connection.ops.quote_name('name') self.assertNotIn(id, qstr) self.assertNotIn(name, qstr) def test_ticket_18414(self): Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='two', created=datetime.datetime.now()) self.assertTrue(Article.objects.exists()) self.assertTrue(Article.objects.distinct().exists()) self.assertTrue(Article.objects.distinct()[1:3].exists()) self.assertFalse(Article.objects.distinct()[1:1].exists()) @skipUnlessDBFeature('can_distinct_on_fields') def test_ticket_18414_distinct_on(self): Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='two', created=datetime.datetime.now()) self.assertTrue(Article.objects.distinct('name').exists()) self.assertTrue(Article.objects.distinct('name')[1:2].exists()) self.assertFalse(Article.objects.distinct('name')[2:3].exists()) class QuerysetOrderedTests(unittest.TestCase): """ Tests for the Queryset.ordered attribute. """ def test_no_default_or_explicit_ordering(self): self.assertIs(Annotation.objects.all().ordered, False) def test_cleared_default_ordering(self): self.assertIs(Tag.objects.all().ordered, True) self.assertIs(Tag.objects.all().order_by().ordered, False) def test_explicit_ordering(self): self.assertIs(Annotation.objects.all().order_by('id').ordered, True) def test_empty_queryset(self): self.assertIs(Annotation.objects.none().ordered, True) def test_order_by_extra(self): self.assertIs(Annotation.objects.all().extra(order_by=['id']).ordered, True) def test_annotated_ordering(self): qs = Annotation.objects.annotate(num_notes=Count('notes')) self.assertIs(qs.ordered, False) self.assertIs(qs.order_by('num_notes').ordered, True) @skipUnlessDBFeature('allow_sliced_subqueries_with_in') class SubqueryTests(TestCase): @classmethod def setUpTestData(cls): NamedCategory.objects.create(id=1, name='first') NamedCategory.objects.create(id=2, name='second') NamedCategory.objects.create(id=3, name='third') NamedCategory.objects.create(id=4, name='fourth') def test_ordered_subselect(self): "Subselects honor any manual ordering" query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2]) self.assertEqual(set(query.values_list('id', flat=True)), {3, 4}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[:2]) self.assertEqual(set(query.values_list('id', flat=True)), {3, 4}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2]) self.assertEqual(set(query.values_list('id', flat=True)), {3}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[2:]) self.assertEqual(set(query.values_list('id', flat=True)), {1, 2}) def test_slice_subquery_and_query(self): """ Slice a query that has a sliced subquery """ query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2])[0:2] self.assertEqual({x.id for x in query}, {3, 4}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:3])[1:3] self.assertEqual({x.id for x in query}, {3}) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[2:])[1:] self.assertEqual({x.id for x in query}, {2}) def test_related_sliced_subquery(self): """ Related objects constraints can safely contain sliced subqueries. refs #22434 """ generic = NamedCategory.objects.create(id=5, name="Generic") t1 = Tag.objects.create(name='t1', category=generic) t2 = Tag.objects.create(name='t2', category=generic) ManagedModel.objects.create(data='mm1', tag=t1, public=True) mm2 = ManagedModel.objects.create(data='mm2', tag=t2, public=True) query = ManagedModel.normal_manager.filter( tag__in=Tag.objects.order_by('-id')[:1] ) self.assertEqual({x.id for x in query}, {mm2.id}) def test_sliced_delete(self): "Delete queries can safely contain sliced subqueries" DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:1]).delete() self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {1, 2, 3}) DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2]).delete() self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {1, 3}) DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:]).delete() self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {3}) def test_distinct_ordered_sliced_subquery(self): # Implicit values('id'). self.assertSequenceEqual( NamedCategory.objects.filter( id__in=NamedCategory.objects.distinct().order_by('name')[0:2], ).order_by('name').values_list('name', flat=True), ['first', 'fourth'] ) # Explicit values('id'). self.assertSequenceEqual( NamedCategory.objects.filter( id__in=NamedCategory.objects.distinct().order_by('-name').values('id')[0:2], ).order_by('name').values_list('name', flat=True), ['second', 'third'] ) # Annotated value. self.assertSequenceEqual( DumbCategory.objects.filter( id__in=DumbCategory.objects.annotate( double_id=F('id') * 2 ).order_by('id').distinct().values('double_id')[0:2], ).order_by('id').values_list('id', flat=True), [2, 4] ) @skipUnlessDBFeature('allow_sliced_subqueries_with_in') class QuerySetBitwiseOperationTests(TestCase): @classmethod def setUpTestData(cls): school = School.objects.create() cls.room_1 = Classroom.objects.create(school=school, has_blackboard=False, name='Room 1') cls.room_2 = Classroom.objects.create(school=school, has_blackboard=True, name='Room 2') cls.room_3 = Classroom.objects.create(school=school, has_blackboard=True, name='Room 3') cls.room_4 = Classroom.objects.create(school=school, has_blackboard=False, name='Room 4') def test_or_with_rhs_slice(self): qs1 = Classroom.objects.filter(has_blackboard=True) qs2 = Classroom.objects.filter(has_blackboard=False)[:1] self.assertCountEqual(qs1 | qs2, [self.room_1, self.room_2, self.room_3]) def test_or_with_lhs_slice(self): qs1 = Classroom.objects.filter(has_blackboard=True)[:1] qs2 = Classroom.objects.filter(has_blackboard=False) self.assertCountEqual(qs1 | qs2, [self.room_1, self.room_2, self.room_4]) def test_or_with_both_slice(self): qs1 = Classroom.objects.filter(has_blackboard=False)[:1] qs2 = Classroom.objects.filter(has_blackboard=True)[:1] self.assertCountEqual(qs1 | qs2, [self.room_1, self.room_2]) def test_or_with_both_slice_and_ordering(self): qs1 = Classroom.objects.filter(has_blackboard=False).order_by('-pk')[:1] qs2 = Classroom.objects.filter(has_blackboard=True).order_by('-name')[:1] self.assertCountEqual(qs1 | qs2, [self.room_3, self.room_4]) class CloneTests(TestCase): def test_evaluated_queryset_as_argument(self): "#13227 -- If a queryset is already evaluated, it can still be used as a query arg" n = Note(note='Test1', misc='misc') n.save() e = ExtraInfo(info='good', note=n) e.save() n_list = Note.objects.all() # Evaluate the Note queryset, populating the query cache list(n_list) # Use the note queryset in a query, and evaluate # that query in a way that involves cloning. self.assertEqual(ExtraInfo.objects.filter(note__in=n_list)[0].info, 'good') def test_no_model_options_cloning(self): """ Cloning a queryset does not get out of hand. While complete testing is impossible, this is a sanity check against invalid use of deepcopy. refs #16759. """ opts_class = type(Note._meta) note_deepcopy = getattr(opts_class, "__deepcopy__", None) opts_class.__deepcopy__ = lambda obj, memo: self.fail("Model options shouldn't be cloned.") try: Note.objects.filter(pk__lte=F('pk') + 1).all() finally: if note_deepcopy is None: delattr(opts_class, "__deepcopy__") else: opts_class.__deepcopy__ = note_deepcopy def test_no_fields_cloning(self): """ Cloning a queryset does not get out of hand. While complete testing is impossible, this is a sanity check against invalid use of deepcopy. refs #16759. """ opts_class = type(Note._meta.get_field("misc")) note_deepcopy = getattr(opts_class, "__deepcopy__", None) opts_class.__deepcopy__ = lambda obj, memo: self.fail("Model fields shouldn't be cloned") try: Note.objects.filter(note=F('misc')).all() finally: if note_deepcopy is None: delattr(opts_class, "__deepcopy__") else: opts_class.__deepcopy__ = note_deepcopy class EmptyQuerySetTests(SimpleTestCase): def test_emptyqueryset_values(self): # #14366 -- Calling .values() on an empty QuerySet and then cloning # that should not cause an error self.assertCountEqual(Number.objects.none().values('num').order_by('num'), []) def test_values_subquery(self): self.assertCountEqual(Number.objects.filter(pk__in=Number.objects.none().values('pk')), []) self.assertCountEqual(Number.objects.filter(pk__in=Number.objects.none().values_list('pk')), []) def test_ticket_19151(self): # #19151 -- Calling .values() or .values_list() on an empty QuerySet # should return an empty QuerySet and not cause an error. q = Author.objects.none() self.assertCountEqual(q.values(), []) self.assertCountEqual(q.values_list(), []) class ValuesQuerysetTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.create(num=72) def test_flat_values_list(self): qs = Number.objects.values_list("num") qs = qs.values_list("num", flat=True) self.assertSequenceEqual(qs, [72]) def test_extra_values(self): # testing for ticket 14930 issues qs = Number.objects.extra(select={'value_plus_x': 'num+%s', 'value_minus_x': 'num-%s'}, select_params=(1, 2)) qs = qs.order_by('value_minus_x') qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_values_order_twice(self): # testing for ticket 14930 issues qs = Number.objects.extra(select={'value_plus_one': 'num+1', 'value_minus_one': 'num-1'}) qs = qs.order_by('value_minus_one').order_by('value_plus_one') qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_values_order_multiple(self): # Postgres doesn't allow constants in order by, so check for that. qs = Number.objects.extra(select={ 'value_plus_one': 'num+1', 'value_minus_one': 'num-1', 'constant_value': '1' }) qs = qs.order_by('value_plus_one', 'value_minus_one', 'constant_value') qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_values_order_in_extra(self): # testing for ticket 14930 issues qs = Number.objects.extra( select={'value_plus_one': 'num+1', 'value_minus_one': 'num-1'}, order_by=['value_minus_one'], ) qs = qs.values('num') def test_extra_select_params_values_order_in_extra(self): # testing for 23259 issue qs = Number.objects.extra( select={'value_plus_x': 'num+%s'}, select_params=[1], order_by=['value_plus_x'], ) qs = qs.filter(num=72) qs = qs.values('num') self.assertSequenceEqual(qs, [{'num': 72}]) def test_extra_multiple_select_params_values_order_by(self): # testing for 23259 issue qs = Number.objects.extra(select={'value_plus_x': 'num+%s', 'value_minus_x': 'num-%s'}, select_params=(72, 72)) qs = qs.order_by('value_minus_x') qs = qs.filter(num=1) qs = qs.values('num') self.assertSequenceEqual(qs, []) def test_extra_values_list(self): # testing for ticket 14930 issues qs = Number.objects.extra(select={'value_plus_one': 'num+1'}) qs = qs.order_by('value_plus_one') qs = qs.values_list('num') self.assertSequenceEqual(qs, [(72,)]) def test_flat_extra_values_list(self): # testing for ticket 14930 issues qs = Number.objects.extra(select={'value_plus_one': 'num+1'}) qs = qs.order_by('value_plus_one') qs = qs.values_list('num', flat=True) self.assertSequenceEqual(qs, [72]) def test_field_error_values_list(self): # see #23443 msg = "Cannot resolve keyword %r into field. Join on 'name' not permitted." % 'foo' with self.assertRaisesMessage(FieldError, msg): Tag.objects.values_list('name__foo') def test_named_values_list_flat(self): msg = "'flat' and 'named' can't be used together." with self.assertRaisesMessage(TypeError, msg): Number.objects.values_list('num', flat=True, named=True) def test_named_values_list_bad_field_name(self): msg = "Type names and field names must be valid identifiers: '1'" with self.assertRaisesMessage(ValueError, msg): Number.objects.extra(select={'1': 'num+1'}).values_list('1', named=True).first() def test_named_values_list_with_fields(self): qs = Number.objects.extra(select={'num2': 'num+1'}).annotate(Count('id')) values = qs.values_list('num', 'num2', named=True).first() self.assertEqual(type(values).__name__, 'Row') self.assertEqual(values._fields, ('num', 'num2')) self.assertEqual(values.num, 72) self.assertEqual(values.num2, 73) def test_named_values_list_without_fields(self): qs = Number.objects.extra(select={'num2': 'num+1'}).annotate(Count('id')) values = qs.values_list(named=True).first() self.assertEqual(type(values).__name__, 'Row') self.assertEqual(values._fields, ('num2', 'id', 'num', 'id__count')) self.assertEqual(values.num, 72) self.assertEqual(values.num2, 73) self.assertEqual(values.id__count, 1) def test_named_values_list_expression_with_default_alias(self): expr = Count('id') values = Number.objects.annotate(id__count1=expr).values_list(expr, 'id__count1', named=True).first() self.assertEqual(values._fields, ('id__count2', 'id__count1')) def test_named_values_list_expression(self): expr = F('num') + 1 qs = Number.objects.annotate(combinedexpression1=expr).values_list(expr, 'combinedexpression1', named=True) values = qs.first() self.assertEqual(values._fields, ('combinedexpression2', 'combinedexpression1')) class QuerySetSupportsPythonIdioms(TestCase): @classmethod def setUpTestData(cls): some_date = datetime.datetime(2014, 5, 16, 12, 1) for i in range(1, 8): Article.objects.create( name="Article {}".format(i), created=some_date) def get_ordered_articles(self): return Article.objects.all().order_by('name') def test_can_get_items_using_index_and_slice_notation(self): self.assertEqual(self.get_ordered_articles()[0].name, 'Article 1') self.assertQuerysetEqual( self.get_ordered_articles()[1:3], ["<Article: Article 2>", "<Article: Article 3>"] ) def test_slicing_with_steps_can_be_used(self): self.assertQuerysetEqual( self.get_ordered_articles()[::2], [ "<Article: Article 1>", "<Article: Article 3>", "<Article: Article 5>", "<Article: Article 7>" ] ) def test_slicing_without_step_is_lazy(self): with self.assertNumQueries(0): self.get_ordered_articles()[0:5] def test_slicing_with_tests_is_not_lazy(self): with self.assertNumQueries(1): self.get_ordered_articles()[0:5:3] def test_slicing_can_slice_again_after_slicing(self): self.assertQuerysetEqual( self.get_ordered_articles()[0:5][0:2], ["<Article: Article 1>", "<Article: Article 2>"] ) self.assertQuerysetEqual(self.get_ordered_articles()[0:5][4:], ["<Article: Article 5>"]) self.assertQuerysetEqual(self.get_ordered_articles()[0:5][5:], []) # Some more tests! self.assertQuerysetEqual( self.get_ordered_articles()[2:][0:2], ["<Article: Article 3>", "<Article: Article 4>"] ) self.assertQuerysetEqual( self.get_ordered_articles()[2:][:2], ["<Article: Article 3>", "<Article: Article 4>"] ) self.assertQuerysetEqual(self.get_ordered_articles()[2:][2:3], ["<Article: Article 5>"]) # Using an offset without a limit is also possible. self.assertQuerysetEqual( self.get_ordered_articles()[5:], ["<Article: Article 6>", "<Article: Article 7>"] ) def test_slicing_cannot_filter_queryset_once_sliced(self): with self.assertRaisesMessage(AssertionError, "Cannot filter a query once a slice has been taken."): Article.objects.all()[0:5].filter(id=1) def test_slicing_cannot_reorder_queryset_once_sliced(self): with self.assertRaisesMessage(AssertionError, "Cannot reorder a query once a slice has been taken."): Article.objects.all()[0:5].order_by('id') def test_slicing_cannot_combine_queries_once_sliced(self): with self.assertRaisesMessage(AssertionError, "Cannot combine queries once a slice has been taken."): Article.objects.all()[0:1] & Article.objects.all()[4:5] def test_slicing_negative_indexing_not_supported_for_single_element(self): """hint: inverting your ordering might do what you need""" with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."): Article.objects.all()[-1] def test_slicing_negative_indexing_not_supported_for_range(self): """hint: inverting your ordering might do what you need""" with self.assertRaisesMessage(AssertionError, "Negative indexing is not supported."): Article.objects.all()[0:-5] def test_can_get_number_of_items_in_queryset_using_standard_len(self): self.assertEqual(len(Article.objects.filter(name__exact='Article 1')), 1) def test_can_combine_queries_using_and_and_or_operators(self): s1 = Article.objects.filter(name__exact='Article 1') s2 = Article.objects.filter(name__exact='Article 2') self.assertQuerysetEqual( (s1 | s2).order_by('name'), ["<Article: Article 1>", "<Article: Article 2>"] ) self.assertQuerysetEqual(s1 & s2, []) class WeirdQuerysetSlicingTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.create(num=1) Number.objects.create(num=2) Article.objects.create(name='one', created=datetime.datetime.now()) Article.objects.create(name='two', created=datetime.datetime.now()) Article.objects.create(name='three', created=datetime.datetime.now()) Article.objects.create(name='four', created=datetime.datetime.now()) food = Food.objects.create(name='spam') Eaten.objects.create(meal='spam with eggs', food=food) def test_tickets_7698_10202(self): # People like to slice with '0' as the high-water mark. self.assertQuerysetEqual(Article.objects.all()[0:0], []) self.assertQuerysetEqual(Article.objects.all()[0:0][:10], []) self.assertEqual(Article.objects.all()[:0].count(), 0) with self.assertRaisesMessage(TypeError, 'Cannot reverse a query once a slice has been taken.'): Article.objects.all()[:0].latest('created') def test_empty_resultset_sql(self): # ticket #12192 self.assertNumQueries(0, lambda: list(Number.objects.all()[1:1])) def test_empty_sliced_subquery(self): self.assertEqual(Eaten.objects.filter(food__in=Food.objects.all()[0:0]).count(), 0) def test_empty_sliced_subquery_exclude(self): self.assertEqual(Eaten.objects.exclude(food__in=Food.objects.all()[0:0]).count(), 1) def test_zero_length_values_slicing(self): n = 42 with self.assertNumQueries(0): self.assertQuerysetEqual(Article.objects.values()[n:n], []) self.assertQuerysetEqual(Article.objects.values_list()[n:n], []) class EscapingTests(TestCase): def test_ticket_7302(self): # Reserved names are appropriately escaped ReservedName.objects.create(name='a', order=42) ReservedName.objects.create(name='b', order=37) self.assertQuerysetEqual( ReservedName.objects.all().order_by('order'), ['<ReservedName: b>', '<ReservedName: a>'] ) self.assertQuerysetEqual( ReservedName.objects.extra(select={'stuff': 'name'}, order_by=('order', 'stuff')), ['<ReservedName: b>', '<ReservedName: a>'] ) class ToFieldTests(TestCase): def test_in_query(self): apple = Food.objects.create(name="apple") pear = Food.objects.create(name="pear") lunch = Eaten.objects.create(food=apple, meal="lunch") dinner = Eaten.objects.create(food=pear, meal="dinner") self.assertEqual( set(Eaten.objects.filter(food__in=[apple, pear])), {lunch, dinner}, ) def test_in_subquery(self): apple = Food.objects.create(name="apple") lunch = Eaten.objects.create(food=apple, meal="lunch") self.assertEqual( set(Eaten.objects.filter(food__in=Food.objects.filter(name='apple'))), {lunch} ) self.assertEqual( set(Eaten.objects.filter(food__in=Food.objects.filter(name='apple').values('eaten__meal'))), set() ) self.assertEqual( set(Food.objects.filter(eaten__in=Eaten.objects.filter(meal='lunch'))), {apple} ) def test_nested_in_subquery(self): extra = ExtraInfo.objects.create() author = Author.objects.create(num=42, extra=extra) report = Report.objects.create(creator=author) comment = ReportComment.objects.create(report=report) comments = ReportComment.objects.filter( report__in=Report.objects.filter( creator__in=extra.author_set.all(), ), ) self.assertSequenceEqual(comments, [comment]) def test_reverse_in(self): apple = Food.objects.create(name="apple") pear = Food.objects.create(name="pear") lunch_apple = Eaten.objects.create(food=apple, meal="lunch") lunch_pear = Eaten.objects.create(food=pear, meal="dinner") self.assertEqual( set(Food.objects.filter(eaten__in=[lunch_apple, lunch_pear])), {apple, pear} ) def test_single_object(self): apple = Food.objects.create(name="apple") lunch = Eaten.objects.create(food=apple, meal="lunch") dinner = Eaten.objects.create(food=apple, meal="dinner") self.assertEqual( set(Eaten.objects.filter(food=apple)), {lunch, dinner} ) def test_single_object_reverse(self): apple = Food.objects.create(name="apple") lunch = Eaten.objects.create(food=apple, meal="lunch") self.assertEqual( set(Food.objects.filter(eaten=lunch)), {apple} ) def test_recursive_fk(self): node1 = Node.objects.create(num=42) node2 = Node.objects.create(num=1, parent=node1) self.assertEqual( list(Node.objects.filter(parent=node1)), [node2] ) def test_recursive_fk_reverse(self): node1 = Node.objects.create(num=42) node2 = Node.objects.create(num=1, parent=node1) self.assertEqual( list(Node.objects.filter(node=node2)), [node1] ) class IsNullTests(TestCase): def test_primary_key(self): custom = CustomPk.objects.create(name='pk') null = Related.objects.create() notnull = Related.objects.create(custom=custom) self.assertSequenceEqual(Related.objects.filter(custom__isnull=False), [notnull]) self.assertSequenceEqual(Related.objects.filter(custom__isnull=True), [null]) def test_to_field(self): apple = Food.objects.create(name="apple") Eaten.objects.create(food=apple, meal="lunch") Eaten.objects.create(meal="lunch") self.assertQuerysetEqual( Eaten.objects.filter(food__isnull=False), ['<Eaten: apple at lunch>'] ) self.assertQuerysetEqual( Eaten.objects.filter(food__isnull=True), ['<Eaten: None at lunch>'] ) class ConditionalTests(TestCase): """Tests whose execution depend on different environment conditions like Python version or DB backend features""" @classmethod def setUpTestData(cls): generic = NamedCategory.objects.create(name="Generic") t1 = Tag.objects.create(name='t1', category=generic) Tag.objects.create(name='t2', parent=t1, category=generic) t3 = Tag.objects.create(name='t3', parent=t1) Tag.objects.create(name='t4', parent=t3) Tag.objects.create(name='t5', parent=t3) def test_infinite_loop(self): # If you're not careful, it's possible to introduce infinite loops via # default ordering on foreign keys in a cycle. We detect that. with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'): list(LoopX.objects.all()) # Force queryset evaluation with list() with self.assertRaisesMessage(FieldError, 'Infinite loop caused by ordering.'): list(LoopZ.objects.all()) # Force queryset evaluation with list() # Note that this doesn't cause an infinite loop, since the default # ordering on the Tag model is empty (and thus defaults to using "id" # for the related field). self.assertEqual(len(Tag.objects.order_by('parent')), 5) # ... but you can still order in a non-recursive fashion among linked # fields (the previous test failed because the default ordering was # recursive). self.assertQuerysetEqual( LoopX.objects.all().order_by('y__x__y__x__id'), [] ) # When grouping without specifying ordering, we add an explicit "ORDER BY NULL" # portion in MySQL to prevent unnecessary sorting. @skipUnlessDBFeature('requires_explicit_null_ordering_when_grouping') def test_null_ordering_added(self): query = Tag.objects.values_list('parent_id', flat=True).order_by().query query.group_by = ['parent_id'] sql = query.get_compiler(DEFAULT_DB_ALIAS).as_sql()[0] fragment = "ORDER BY " pos = sql.find(fragment) self.assertEqual(sql.find(fragment, pos + 1), -1) self.assertEqual(sql.find("NULL", pos + len(fragment)), pos + len(fragment)) def test_in_list_limit(self): # The "in" lookup works with lists of 1000 items or more. # The numbers amount is picked to force three different IN batches # for Oracle, yet to be less than 2100 parameter limit for MSSQL. numbers = list(range(2050)) max_query_params = connection.features.max_query_params if max_query_params is None or max_query_params >= len(numbers): Number.objects.bulk_create(Number(num=num) for num in numbers) for number in [1000, 1001, 2000, len(numbers)]: with self.subTest(number=number): self.assertEqual(Number.objects.filter(num__in=numbers[:number]).count(), number) class UnionTests(unittest.TestCase): """ Tests for the union of two querysets. Bug #12252. """ @classmethod def setUpTestData(cls): objectas = [] objectbs = [] objectcs = [] a_info = ['one', 'two', 'three'] for name in a_info: o = ObjectA(name=name) o.save() objectas.append(o) b_info = [('un', 1, objectas[0]), ('deux', 2, objectas[0]), ('trois', 3, objectas[2])] for name, number, objecta in b_info: o = ObjectB(name=name, num=number, objecta=objecta) o.save() objectbs.append(o) c_info = [('ein', objectas[2], objectbs[2]), ('zwei', objectas[1], objectbs[1])] for name, objecta, objectb in c_info: o = ObjectC(name=name, objecta=objecta, objectb=objectb) o.save() objectcs.append(o) def check_union(self, model, Q1, Q2): filter = model.objects.filter self.assertEqual(set(filter(Q1) | filter(Q2)), set(filter(Q1 | Q2))) self.assertEqual(set(filter(Q2) | filter(Q1)), set(filter(Q1 | Q2))) def test_A_AB(self): Q1 = Q(name='two') Q2 = Q(objectb__name='deux') self.check_union(ObjectA, Q1, Q2) def test_A_AB2(self): Q1 = Q(name='two') Q2 = Q(objectb__name='deux', objectb__num=2) self.check_union(ObjectA, Q1, Q2) def test_AB_ACB(self): Q1 = Q(objectb__name='deux') Q2 = Q(objectc__objectb__name='deux') self.check_union(ObjectA, Q1, Q2) def test_BAB_BAC(self): Q1 = Q(objecta__objectb__name='deux') Q2 = Q(objecta__objectc__name='ein') self.check_union(ObjectB, Q1, Q2) def test_BAB_BACB(self): Q1 = Q(objecta__objectb__name='deux') Q2 = Q(objecta__objectc__objectb__name='trois') self.check_union(ObjectB, Q1, Q2) def test_BA_BCA__BAB_BAC_BCA(self): Q1 = Q(objecta__name='one', objectc__objecta__name='two') Q2 = Q(objecta__objectc__name='ein', objectc__objecta__name='three', objecta__objectb__name='trois') self.check_union(ObjectB, Q1, Q2) class DefaultValuesInsertTest(TestCase): def test_no_extra_params(self): """ Can create an instance of a model with only the PK field (#17056)." """ DumbCategory.objects.create() class ExcludeTests(TestCase): @classmethod def setUpTestData(cls): f1 = Food.objects.create(name='apples') Food.objects.create(name='oranges') Eaten.objects.create(food=f1, meal='dinner') j1 = Job.objects.create(name='Manager') r1 = Responsibility.objects.create(description='Playing golf') j2 = Job.objects.create(name='Programmer') r2 = Responsibility.objects.create(description='Programming') JobResponsibilities.objects.create(job=j1, responsibility=r1) JobResponsibilities.objects.create(job=j2, responsibility=r2) def test_to_field(self): self.assertQuerysetEqual( Food.objects.exclude(eaten__meal='dinner'), ['<Food: oranges>']) self.assertQuerysetEqual( Job.objects.exclude(responsibilities__description='Playing golf'), ['<Job: Programmer>']) self.assertQuerysetEqual( Responsibility.objects.exclude(jobs__name='Manager'), ['<Responsibility: Programming>']) def test_ticket14511(self): alex = Person.objects.get_or_create(name='Alex')[0] jane = Person.objects.get_or_create(name='Jane')[0] oracle = Company.objects.get_or_create(name='Oracle')[0] google = Company.objects.get_or_create(name='Google')[0] microsoft = Company.objects.get_or_create(name='Microsoft')[0] intel = Company.objects.get_or_create(name='Intel')[0] def employ(employer, employee, title): Employment.objects.get_or_create(employee=employee, employer=employer, title=title) employ(oracle, alex, 'Engineer') employ(oracle, alex, 'Developer') employ(google, alex, 'Engineer') employ(google, alex, 'Manager') employ(microsoft, alex, 'Manager') employ(intel, alex, 'Manager') employ(microsoft, jane, 'Developer') employ(intel, jane, 'Manager') alex_tech_employers = alex.employers.filter( employment__title__in=('Engineer', 'Developer')).distinct().order_by('name') self.assertSequenceEqual(alex_tech_employers, [google, oracle]) alex_nontech_employers = alex.employers.exclude( employment__title__in=('Engineer', 'Developer')).distinct().order_by('name') self.assertSequenceEqual(alex_nontech_employers, [google, intel, microsoft]) def test_exclude_reverse_fk_field_ref(self): tag = Tag.objects.create() Note.objects.create(tag=tag, note='note') annotation = Annotation.objects.create(name='annotation', tag=tag) self.assertEqual(Annotation.objects.exclude(tag__note__note=F('name')).get(), annotation) def test_exclude_with_circular_fk_relation(self): self.assertEqual(ObjectB.objects.exclude(objecta__objectb__name=F('name')).count(), 0) class ExcludeTest17600(TestCase): """ Some regressiontests for ticket #17600. Some of these likely duplicate other existing tests. """ @classmethod def setUpTestData(cls): # Create a few Orders. cls.o1 = Order.objects.create(pk=1) cls.o2 = Order.objects.create(pk=2) cls.o3 = Order.objects.create(pk=3) # Create some OrderItems for the first order with homogeneous # status_id values cls.oi1 = OrderItem.objects.create(order=cls.o1, status=1) cls.oi2 = OrderItem.objects.create(order=cls.o1, status=1) cls.oi3 = OrderItem.objects.create(order=cls.o1, status=1) # Create some OrderItems for the second order with heterogeneous # status_id values cls.oi4 = OrderItem.objects.create(order=cls.o2, status=1) cls.oi5 = OrderItem.objects.create(order=cls.o2, status=2) cls.oi6 = OrderItem.objects.create(order=cls.o2, status=3) # Create some OrderItems for the second order with heterogeneous # status_id values cls.oi7 = OrderItem.objects.create(order=cls.o3, status=2) cls.oi8 = OrderItem.objects.create(order=cls.o3, status=3) cls.oi9 = OrderItem.objects.create(order=cls.o3, status=4) def test_exclude_plain(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(items__status=1), ['<Order: 3>']) def test_exclude_plain_distinct(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(items__status=1).distinct(), ['<Order: 3>']) def test_exclude_with_q_object_distinct(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(Q(items__status=1)).distinct(), ['<Order: 3>']) def test_exclude_with_q_object_no_distinct(self): """ This should exclude Orders which have some items with status 1 """ self.assertQuerysetEqual( Order.objects.exclude(Q(items__status=1)), ['<Order: 3>']) def test_exclude_with_q_is_equal_to_plain_exclude(self): """ Using exclude(condition) and exclude(Q(condition)) should yield the same QuerySet """ self.assertEqual( list(Order.objects.exclude(items__status=1).distinct()), list(Order.objects.exclude(Q(items__status=1)).distinct())) def test_exclude_with_q_is_equal_to_plain_exclude_variation(self): """ Using exclude(condition) and exclude(Q(condition)) should yield the same QuerySet """ self.assertEqual( list(Order.objects.exclude(items__status=1)), list(Order.objects.exclude(Q(items__status=1)).distinct())) @unittest.expectedFailure def test_only_orders_with_all_items_having_status_1(self): """ This should only return orders having ALL items set to status 1, or those items not having any orders at all. The correct way to write this query in SQL seems to be using two nested subqueries. """ self.assertQuerysetEqual( Order.objects.exclude(~Q(items__status=1)).distinct(), ['<Order: 1>']) class Exclude15786(TestCase): """Regression test for #15786""" def test_ticket15786(self): c1 = SimpleCategory.objects.create(name='c1') c2 = SimpleCategory.objects.create(name='c2') OneToOneCategory.objects.create(category=c1) OneToOneCategory.objects.create(category=c2) rel = CategoryRelationship.objects.create(first=c1, second=c2) self.assertEqual( CategoryRelationship.objects.exclude( first__onetoonecategory=F('second__onetoonecategory') ).get(), rel ) class NullInExcludeTest(TestCase): @classmethod def setUpTestData(cls): NullableName.objects.create(name='i1') NullableName.objects.create() def test_null_in_exclude_qs(self): none_val = '' if connection.features.interprets_empty_strings_as_nulls else None self.assertQuerysetEqual( NullableName.objects.exclude(name__in=[]), ['i1', none_val], attrgetter('name')) self.assertQuerysetEqual( NullableName.objects.exclude(name__in=['i1']), [none_val], attrgetter('name')) self.assertQuerysetEqual( NullableName.objects.exclude(name__in=['i3']), ['i1', none_val], attrgetter('name')) inner_qs = NullableName.objects.filter(name='i1').values_list('name') self.assertQuerysetEqual( NullableName.objects.exclude(name__in=inner_qs), [none_val], attrgetter('name')) # The inner queryset wasn't executed - it should be turned # into subquery above self.assertIs(inner_qs._result_cache, None) @unittest.expectedFailure def test_col_not_in_list_containing_null(self): """ The following case is not handled properly because SQL's COL NOT IN (list containing null) handling is too weird to abstract away. """ self.assertQuerysetEqual( NullableName.objects.exclude(name__in=[None]), ['i1'], attrgetter('name')) def test_double_exclude(self): self.assertEqual( list(NullableName.objects.filter(~~Q(name='i1'))), list(NullableName.objects.filter(Q(name='i1')))) self.assertNotIn( 'IS NOT NULL', str(NullableName.objects.filter(~~Q(name='i1')).query)) class EmptyStringsAsNullTest(TestCase): """ Filtering on non-null character fields works as expected. The reason for these tests is that Oracle treats '' as NULL, and this can cause problems in query construction. Refs #17957. """ @classmethod def setUpTestData(cls): cls.nc = NamedCategory.objects.create(name='') def test_direct_exclude(self): self.assertQuerysetEqual( NamedCategory.objects.exclude(name__in=['nonexistent']), [self.nc.pk], attrgetter('pk') ) def test_joined_exclude(self): self.assertQuerysetEqual( DumbCategory.objects.exclude(namedcategory__name__in=['nonexistent']), [self.nc.pk], attrgetter('pk') ) def test_21001(self): foo = NamedCategory.objects.create(name='foo') self.assertQuerysetEqual( NamedCategory.objects.exclude(name=''), [foo.pk], attrgetter('pk') ) class ProxyQueryCleanupTest(TestCase): def test_evaluated_proxy_count(self): """ Generating the query string doesn't alter the query's state in irreversible ways. Refs #18248. """ ProxyCategory.objects.create() qs = ProxyCategory.objects.all() self.assertEqual(qs.count(), 1) str(qs.query) self.assertEqual(qs.count(), 1) class WhereNodeTest(SimpleTestCase): class DummyNode: def as_sql(self, compiler, connection): return 'dummy', [] class MockCompiler: def compile(self, node): return node.as_sql(self, connection) def __call__(self, name): return connection.ops.quote_name(name) def test_empty_full_handling_conjunction(self): compiler = WhereNodeTest.MockCompiler() w = WhereNode(children=[NothingNode()]) with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[self.DummyNode(), self.DummyNode()]) self.assertEqual(w.as_sql(compiler, connection), ('(dummy AND dummy)', [])) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy AND dummy)', [])) w = WhereNode(children=[NothingNode(), self.DummyNode()]) with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) def test_empty_full_handling_disjunction(self): compiler = WhereNodeTest.MockCompiler() w = WhereNode(children=[NothingNode()], connector='OR') with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[self.DummyNode(), self.DummyNode()], connector='OR') self.assertEqual(w.as_sql(compiler, connection), ('(dummy OR dummy)', [])) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy OR dummy)', [])) w = WhereNode(children=[NothingNode(), self.DummyNode()], connector='OR') self.assertEqual(w.as_sql(compiler, connection), ('dummy', [])) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('NOT (dummy)', [])) def test_empty_nodes(self): compiler = WhereNodeTest.MockCompiler() empty_w = WhereNode() w = WhereNode(children=[empty_w, empty_w]) self.assertEqual(w.as_sql(compiler, connection), ('', [])) w.negate() with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.connector = 'OR' with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) w.negate() self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[empty_w, NothingNode()], connector='OR') self.assertEqual(w.as_sql(compiler, connection), ('', [])) w = WhereNode(children=[empty_w, NothingNode()], connector='AND') with self.assertRaises(EmptyResultSet): w.as_sql(compiler, connection) class QuerySetExceptionTests(SimpleTestCase): def test_iter_exceptions(self): qs = ExtraInfo.objects.only('author') msg = "'ManyToOneRel' object has no attribute 'attname'" with self.assertRaisesMessage(AttributeError, msg): list(qs) def test_invalid_qs_list(self): # Test for #19895 - second iteration over invalid queryset # raises errors. qs = Article.objects.order_by('invalid_column') msg = "Cannot resolve keyword 'invalid_column' into field." with self.assertRaisesMessage(FieldError, msg): list(qs) with self.assertRaisesMessage(FieldError, msg): list(qs) def test_invalid_order_by(self): msg = "Invalid order_by arguments: ['*']" with self.assertRaisesMessage(FieldError, msg): list(Article.objects.order_by('*')) def test_invalid_queryset_model(self): msg = 'Cannot use QuerySet for "Article": Use a QuerySet for "ExtraInfo".' with self.assertRaisesMessage(ValueError, msg): list(Author.objects.filter(extra=Article.objects.all())) class NullJoinPromotionOrTest(TestCase): @classmethod def setUpTestData(cls): cls.d1 = ModelD.objects.create(name='foo') d2 = ModelD.objects.create(name='bar') cls.a1 = ModelA.objects.create(name='a1', d=cls.d1) c = ModelC.objects.create(name='c') b = ModelB.objects.create(name='b', c=c) cls.a2 = ModelA.objects.create(name='a2', b=b, d=d2) def test_ticket_17886(self): # The first Q-object is generating the match, the rest of the filters # should not remove the match even if they do not match anything. The # problem here was that b__name generates a LOUTER JOIN, then # b__c__name generates join to c, which the ORM tried to promote but # failed as that join isn't nullable. q_obj = ( Q(d__name='foo') | Q(b__name='foo') | Q(b__c__name='foo') ) qset = ModelA.objects.filter(q_obj) self.assertEqual(list(qset), [self.a1]) # We generate one INNER JOIN to D. The join is direct and not nullable # so we can use INNER JOIN for it. However, we can NOT use INNER JOIN # for the b->c join, as a->b is nullable. self.assertEqual(str(qset.query).count('INNER JOIN'), 1) def test_isnull_filter_promotion(self): qs = ModelA.objects.filter(Q(b__name__isnull=True)) self.assertEqual(str(qs.query).count('LEFT OUTER'), 1) self.assertEqual(list(qs), [self.a1]) qs = ModelA.objects.filter(~Q(b__name__isnull=True)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(list(qs), [self.a2]) qs = ModelA.objects.filter(~~Q(b__name__isnull=True)) self.assertEqual(str(qs.query).count('LEFT OUTER'), 1) self.assertEqual(list(qs), [self.a1]) qs = ModelA.objects.filter(Q(b__name__isnull=False)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(list(qs), [self.a2]) qs = ModelA.objects.filter(~Q(b__name__isnull=False)) self.assertEqual(str(qs.query).count('LEFT OUTER'), 1) self.assertEqual(list(qs), [self.a1]) qs = ModelA.objects.filter(~~Q(b__name__isnull=False)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(list(qs), [self.a2]) def test_null_join_demotion(self): qs = ModelA.objects.filter(Q(b__name__isnull=False) & Q(b__name__isnull=True)) self.assertIn(' INNER JOIN ', str(qs.query)) qs = ModelA.objects.filter(Q(b__name__isnull=True) & Q(b__name__isnull=False)) self.assertIn(' INNER JOIN ', str(qs.query)) qs = ModelA.objects.filter(Q(b__name__isnull=False) | Q(b__name__isnull=True)) self.assertIn(' LEFT OUTER JOIN ', str(qs.query)) qs = ModelA.objects.filter(Q(b__name__isnull=True) | Q(b__name__isnull=False)) self.assertIn(' LEFT OUTER JOIN ', str(qs.query)) def test_ticket_21366(self): n = Note.objects.create(note='n', misc='m') e = ExtraInfo.objects.create(info='info', note=n) a = Author.objects.create(name='Author1', num=1, extra=e) Ranking.objects.create(rank=1, author=a) r1 = Report.objects.create(name='Foo', creator=a) r2 = Report.objects.create(name='Bar') Report.objects.create(name='Bar', creator=a) qs = Report.objects.filter( Q(creator__ranking__isnull=True) | Q(creator__ranking__rank=1, name='Foo') ) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) self.assertEqual(str(qs.query).count(' JOIN '), 2) self.assertSequenceEqual(qs.order_by('name'), [r2, r1]) def test_ticket_21748(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') i3 = Identifier.objects.create(name='i3') Program.objects.create(identifier=i1) Channel.objects.create(identifier=i1) Program.objects.create(identifier=i2) self.assertSequenceEqual(Identifier.objects.filter(program=None, channel=None), [i3]) self.assertSequenceEqual(Identifier.objects.exclude(program=None, channel=None).order_by('name'), [i1, i2]) def test_ticket_21748_double_negated_and(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') Identifier.objects.create(name='i3') p1 = Program.objects.create(identifier=i1) c1 = Channel.objects.create(identifier=i1) Program.objects.create(identifier=i2) # Check the ~~Q() (or equivalently .exclude(~Q)) works like Q() for # join promotion. qs1_doubleneg = Identifier.objects.exclude(~Q(program__id=p1.id, channel__id=c1.id)).order_by('pk') qs1_filter = Identifier.objects.filter(program__id=p1.id, channel__id=c1.id).order_by('pk') self.assertQuerysetEqual(qs1_doubleneg, qs1_filter, lambda x: x) self.assertEqual(str(qs1_filter.query).count('JOIN'), str(qs1_doubleneg.query).count('JOIN')) self.assertEqual(2, str(qs1_doubleneg.query).count('INNER JOIN')) self.assertEqual(str(qs1_filter.query).count('INNER JOIN'), str(qs1_doubleneg.query).count('INNER JOIN')) def test_ticket_21748_double_negated_or(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') Identifier.objects.create(name='i3') p1 = Program.objects.create(identifier=i1) c1 = Channel.objects.create(identifier=i1) p2 = Program.objects.create(identifier=i2) # Test OR + doubleneg. The expected result is that channel is LOUTER # joined, program INNER joined qs1_filter = Identifier.objects.filter( Q(program__id=p2.id, channel__id=c1.id) | Q(program__id=p1.id) ).order_by('pk') qs1_doubleneg = Identifier.objects.exclude( ~Q(Q(program__id=p2.id, channel__id=c1.id) | Q(program__id=p1.id)) ).order_by('pk') self.assertQuerysetEqual(qs1_doubleneg, qs1_filter, lambda x: x) self.assertEqual(str(qs1_filter.query).count('JOIN'), str(qs1_doubleneg.query).count('JOIN')) self.assertEqual(1, str(qs1_doubleneg.query).count('INNER JOIN')) self.assertEqual(str(qs1_filter.query).count('INNER JOIN'), str(qs1_doubleneg.query).count('INNER JOIN')) def test_ticket_21748_complex_filter(self): i1 = Identifier.objects.create(name='i1') i2 = Identifier.objects.create(name='i2') Identifier.objects.create(name='i3') p1 = Program.objects.create(identifier=i1) c1 = Channel.objects.create(identifier=i1) p2 = Program.objects.create(identifier=i2) # Finally, a more complex case, one time in a way where each # NOT is pushed to lowest level in the boolean tree, and # another query where this isn't done. qs1 = Identifier.objects.filter( ~Q(~Q(program__id=p2.id, channel__id=c1.id) & Q(program__id=p1.id)) ).order_by('pk') qs2 = Identifier.objects.filter( Q(Q(program__id=p2.id, channel__id=c1.id) | ~Q(program__id=p1.id)) ).order_by('pk') self.assertQuerysetEqual(qs1, qs2, lambda x: x) self.assertEqual(str(qs1.query).count('JOIN'), str(qs2.query).count('JOIN')) self.assertEqual(0, str(qs1.query).count('INNER JOIN')) self.assertEqual(str(qs1.query).count('INNER JOIN'), str(qs2.query).count('INNER JOIN')) class ReverseJoinTrimmingTest(TestCase): def test_reverse_trimming(self): # We don't accidentally trim reverse joins - we can't know if there is # anything on the other side of the join, so trimming reverse joins # can't be done, ever. t = Tag.objects.create() qs = Tag.objects.filter(annotation__tag=t.pk) self.assertIn('INNER JOIN', str(qs.query)) self.assertEqual(list(qs), []) class JoinReuseTest(TestCase): """ The queries reuse joins sensibly (for example, direct joins are always reused). """ def test_fk_reuse(self): qs = Annotation.objects.filter(tag__name='foo').filter(tag__name='bar') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_select_related(self): qs = Annotation.objects.filter(tag__name='foo').select_related('tag') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_annotation(self): qs = Annotation.objects.filter(tag__name='foo').annotate(cnt=Count('tag__name')) self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_disjunction(self): qs = Annotation.objects.filter(Q(tag__name='foo') | Q(tag__name='bar')) self.assertEqual(str(qs.query).count('JOIN'), 1) def test_fk_reuse_order_by(self): qs = Annotation.objects.filter(tag__name='foo').order_by('tag__name') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_revo2o_reuse(self): qs = Detail.objects.filter(member__name='foo').filter(member__name='foo') self.assertEqual(str(qs.query).count('JOIN'), 1) def test_revfk_noreuse(self): qs = Author.objects.filter(report__name='r4').filter(report__name='r1') self.assertEqual(str(qs.query).count('JOIN'), 2) def test_inverted_q_across_relations(self): """ When a trimmable join is specified in the query (here school__), the ORM detects it and removes unnecessary joins. The set of reusable joins are updated after trimming the query so that other lookups don't consider that the outer query's filters are in effect for the subquery (#26551). """ springfield_elementary = School.objects.create() hogward = School.objects.create() Student.objects.create(school=springfield_elementary) hp = Student.objects.create(school=hogward) Classroom.objects.create(school=hogward, name='Potion') Classroom.objects.create(school=springfield_elementary, name='Main') qs = Student.objects.filter( ~(Q(school__classroom__name='Main') & Q(school__classroom__has_blackboard=None)) ) self.assertSequenceEqual(qs, [hp]) class DisjunctionPromotionTests(TestCase): def test_disjunction_promotion_select_related(self): fk1 = FK1.objects.create(f1='f1', f2='f2') basea = BaseA.objects.create(a=fk1) qs = BaseA.objects.filter(Q(a=fk1) | Q(b=2)) self.assertEqual(str(qs.query).count(' JOIN '), 0) qs = qs.select_related('a', 'b') self.assertEqual(str(qs.query).count(' INNER JOIN '), 0) self.assertEqual(str(qs.query).count(' LEFT OUTER JOIN '), 2) with self.assertNumQueries(1): self.assertSequenceEqual(qs, [basea]) self.assertEqual(qs[0].a, fk1) self.assertIs(qs[0].b, None) def test_disjunction_promotion1(self): # Pre-existing join, add two ORed filters to the same join, # all joins can be INNER JOINS. qs = BaseA.objects.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = qs.filter(Q(b__f1='foo') | Q(b__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) # Reverse the order of AND and OR filters. qs = BaseA.objects.filter(Q(b__f1='foo') | Q(b__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = qs.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 2) def test_disjunction_promotion2(self): qs = BaseA.objects.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) # Now we have two different joins in an ORed condition, these # must be OUTER joins. The pre-existing join should remain INNER. qs = qs.filter(Q(b__f1='foo') | Q(c__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) # Reverse case. qs = BaseA.objects.filter(Q(b__f1='foo') | Q(c__f2='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) qs = qs.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) def test_disjunction_promotion3(self): qs = BaseA.objects.filter(a__f2='bar') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) # The ANDed a__f2 filter allows us to use keep using INNER JOIN # even inside the ORed case. If the join to a__ returns nothing, # the ANDed filter for a__f2 can't be true. qs = qs.filter(Q(a__f1='foo') | Q(b__f2='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) def test_disjunction_promotion3_demote(self): # This one needs demotion logic: the first filter causes a to be # outer joined, the second filter makes it inner join again. qs = BaseA.objects.filter( Q(a__f1='foo') | Q(b__f2='foo')).filter(a__f2='bar') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) def test_disjunction_promotion4_demote(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('JOIN'), 0) # Demote needed for the "a" join. It is marked as outer join by # above filter (even if it is trimmed away). qs = qs.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) def test_disjunction_promotion4(self): qs = BaseA.objects.filter(a__f1='foo') self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = qs.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) def test_disjunction_promotion5_demote(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) # Note that the above filters on a force the join to an # inner join even if it is trimmed. self.assertEqual(str(qs.query).count('JOIN'), 0) qs = qs.filter(Q(a__f1='foo') | Q(b__f1='foo')) # So, now the a__f1 join doesn't need promotion. self.assertEqual(str(qs.query).count('INNER JOIN'), 1) # But b__f1 does. self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) qs = BaseA.objects.filter(Q(a__f1='foo') | Q(b__f1='foo')) # Now the join to a is created as LOUTER self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) qs = qs.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) def test_disjunction_promotion6(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('JOIN'), 0) qs = BaseA.objects.filter(Q(a__f1='foo') & Q(b__f1='foo')) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 0) qs = BaseA.objects.filter(Q(a__f1='foo') & Q(b__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 0) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) qs = qs.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('INNER JOIN'), 2) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 0) def test_disjunction_promotion7(self): qs = BaseA.objects.filter(Q(a=1) | Q(a=2)) self.assertEqual(str(qs.query).count('JOIN'), 0) qs = BaseA.objects.filter(Q(a__f1='foo') | (Q(b__f1='foo') & Q(a__f1='bar'))) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) qs = BaseA.objects.filter( (Q(a__f1='foo') | Q(b__f1='foo')) & (Q(a__f1='bar') | Q(c__f1='foo')) ) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 3) self.assertEqual(str(qs.query).count('INNER JOIN'), 0) qs = BaseA.objects.filter( (Q(a__f1='foo') | (Q(a__f1='bar')) & (Q(b__f1='bar') | Q(c__f1='foo'))) ) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) def test_disjunction_promotion_fexpression(self): qs = BaseA.objects.filter(Q(a__f1=F('b__f1')) | Q(b__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 1) self.assertEqual(str(qs.query).count('INNER JOIN'), 1) qs = BaseA.objects.filter(Q(a__f1=F('c__f1')) | Q(b__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 3) qs = BaseA.objects.filter(Q(a__f1=F('b__f1')) | Q(a__f2=F('b__f2')) | Q(c__f1='foo')) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 3) qs = BaseA.objects.filter(Q(a__f1=F('c__f1')) | (Q(pk=1) & Q(pk=2))) self.assertEqual(str(qs.query).count('LEFT OUTER JOIN'), 2) self.assertEqual(str(qs.query).count('INNER JOIN'), 0) class ManyToManyExcludeTest(TestCase): def test_exclude_many_to_many(self): Identifier.objects.create(name='extra') program = Program.objects.create(identifier=Identifier.objects.create(name='program')) channel = Channel.objects.create(identifier=Identifier.objects.create(name='channel')) channel.programs.add(program) # channel contains 'program1', so all Identifiers except that one # should be returned self.assertQuerysetEqual( Identifier.objects.exclude(program__channel=channel).order_by('name'), ['<Identifier: channel>', '<Identifier: extra>'] ) self.assertQuerysetEqual( Identifier.objects.exclude(program__channel=None).order_by('name'), ['<Identifier: program>'] ) def test_ticket_12823(self): pg3 = Page.objects.create(text='pg3') pg2 = Page.objects.create(text='pg2') pg1 = Page.objects.create(text='pg1') pa1 = Paragraph.objects.create(text='pa1') pa1.page.set([pg1, pg2]) pa2 = Paragraph.objects.create(text='pa2') pa2.page.set([pg2, pg3]) pa3 = Paragraph.objects.create(text='pa3') ch1 = Chapter.objects.create(title='ch1', paragraph=pa1) ch2 = Chapter.objects.create(title='ch2', paragraph=pa2) ch3 = Chapter.objects.create(title='ch3', paragraph=pa3) b1 = Book.objects.create(title='b1', chapter=ch1) b2 = Book.objects.create(title='b2', chapter=ch2) b3 = Book.objects.create(title='b3', chapter=ch3) q = Book.objects.exclude(chapter__paragraph__page__text='pg1') self.assertNotIn('IS NOT NULL', str(q.query)) self.assertEqual(len(q), 2) self.assertNotIn(b1, q) self.assertIn(b2, q) self.assertIn(b3, q) class RelabelCloneTest(TestCase): def test_ticket_19964(self): my1 = MyObject.objects.create(data='foo') my1.parent = my1 my1.save() my2 = MyObject.objects.create(data='bar', parent=my1) parents = MyObject.objects.filter(parent=F('id')) children = MyObject.objects.filter(parent__in=parents).exclude(parent=F('id')) self.assertEqual(list(parents), [my1]) # Evaluating the children query (which has parents as part of it) does # not change results for the parents query. self.assertEqual(list(children), [my2]) self.assertEqual(list(parents), [my1]) class Ticket20101Tests(TestCase): def test_ticket_20101(self): """ Tests QuerySet ORed combining in exclude subquery case. """ t = Tag.objects.create(name='foo') a1 = Annotation.objects.create(tag=t, name='a1') a2 = Annotation.objects.create(tag=t, name='a2') a3 = Annotation.objects.create(tag=t, name='a3') n = Note.objects.create(note='foo', misc='bar') qs1 = Note.objects.exclude(annotation__in=[a1, a2]) qs2 = Note.objects.filter(annotation__in=[a3]) self.assertIn(n, qs1) self.assertNotIn(n, qs2) self.assertIn(n, (qs1 | qs2)) class EmptyStringPromotionTests(SimpleTestCase): def test_empty_string_promotion(self): qs = RelatedObject.objects.filter(single__name='') if connection.features.interprets_empty_strings_as_nulls: self.assertIn('LEFT OUTER JOIN', str(qs.query)) else: self.assertNotIn('LEFT OUTER JOIN', str(qs.query)) class ValuesSubqueryTests(TestCase): def test_values_in_subquery(self): # If a values() queryset is used, then the given values # will be used instead of forcing use of the relation's field. o1 = Order.objects.create(id=-2) o2 = Order.objects.create(id=-1) oi1 = OrderItem.objects.create(order=o1, status=0) oi1.status = oi1.pk oi1.save() OrderItem.objects.create(order=o2, status=0) # The query below should match o1 as it has related order_item # with id == status. self.assertSequenceEqual(Order.objects.filter(items__in=OrderItem.objects.values_list('status')), [o1]) class DoubleInSubqueryTests(TestCase): def test_double_subquery_in(self): lfa1 = LeafA.objects.create(data='foo') lfa2 = LeafA.objects.create(data='bar') lfb1 = LeafB.objects.create(data='lfb1') lfb2 = LeafB.objects.create(data='lfb2') Join.objects.create(a=lfa1, b=lfb1) Join.objects.create(a=lfa2, b=lfb2) leaf_as = LeafA.objects.filter(data='foo').values_list('pk', flat=True) joins = Join.objects.filter(a__in=leaf_as).values_list('b__id', flat=True) qs = LeafB.objects.filter(pk__in=joins) self.assertSequenceEqual(qs, [lfb1]) class Ticket18785Tests(SimpleTestCase): def test_ticket_18785(self): # Test join trimming from ticket18785 qs = Item.objects.exclude( note__isnull=False ).filter( name='something', creator__extra__isnull=True ).order_by() self.assertEqual(1, str(qs.query).count('INNER JOIN')) self.assertEqual(0, str(qs.query).count('OUTER JOIN')) class Ticket20788Tests(TestCase): def test_ticket_20788(self): Paragraph.objects.create() paragraph = Paragraph.objects.create() page = paragraph.page.create() chapter = Chapter.objects.create(paragraph=paragraph) Book.objects.create(chapter=chapter) paragraph2 = Paragraph.objects.create() Page.objects.create() chapter2 = Chapter.objects.create(paragraph=paragraph2) book2 = Book.objects.create(chapter=chapter2) sentences_not_in_pub = Book.objects.exclude(chapter__paragraph__page=page) self.assertSequenceEqual(sentences_not_in_pub, [book2]) class Ticket12807Tests(TestCase): def test_ticket_12807(self): p1 = Paragraph.objects.create() p2 = Paragraph.objects.create() # The ORed condition below should have no effect on the query - the # ~Q(pk__in=[]) will always be True. qs = Paragraph.objects.filter((Q(pk=p2.pk) | ~Q(pk__in=[])) & Q(pk=p1.pk)) self.assertSequenceEqual(qs, [p1]) class RelatedLookupTypeTests(TestCase): error = 'Cannot query "%s": Must be "%s" instance.' @classmethod def setUpTestData(cls): cls.oa = ObjectA.objects.create(name="oa") cls.poa = ProxyObjectA.objects.get(name="oa") cls.coa = ChildObjectA.objects.create(name="coa") cls.wrong_type = Order.objects.create(id=cls.oa.pk) cls.ob = ObjectB.objects.create(name="ob", objecta=cls.oa, num=1) ProxyObjectB.objects.create(name="pob", objecta=cls.oa, num=2) cls.pob = ProxyObjectB.objects.all() ObjectC.objects.create(childobjecta=cls.coa) def test_wrong_type_lookup(self): """ A ValueError is raised when the incorrect object type is passed to a query lookup. """ # Passing incorrect object type with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectA._meta.object_name)): ObjectB.objects.get(objecta=self.wrong_type) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectA._meta.object_name)): ObjectB.objects.filter(objecta__in=[self.wrong_type]) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectA._meta.object_name)): ObjectB.objects.filter(objecta=self.wrong_type) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectB._meta.object_name)): ObjectA.objects.filter(objectb__in=[self.wrong_type, self.ob]) # Passing an object of the class on which query is done. with self.assertRaisesMessage(ValueError, self.error % (self.ob, ObjectA._meta.object_name)): ObjectB.objects.filter(objecta__in=[self.poa, self.ob]) with self.assertRaisesMessage(ValueError, self.error % (self.ob, ChildObjectA._meta.object_name)): ObjectC.objects.exclude(childobjecta__in=[self.coa, self.ob]) def test_wrong_backward_lookup(self): """ A ValueError is raised when the incorrect object type is passed to a query lookup for backward relations. """ with self.assertRaisesMessage(ValueError, self.error % (self.oa, ObjectB._meta.object_name)): ObjectA.objects.filter(objectb__in=[self.oa, self.ob]) with self.assertRaisesMessage(ValueError, self.error % (self.oa, ObjectB._meta.object_name)): ObjectA.objects.exclude(objectb=self.oa) with self.assertRaisesMessage(ValueError, self.error % (self.wrong_type, ObjectB._meta.object_name)): ObjectA.objects.get(objectb=self.wrong_type) def test_correct_lookup(self): """ When passing proxy model objects, child objects, or parent objects, lookups work fine. """ out_a = ['<ObjectA: oa>'] out_b = ['<ObjectB: ob>', '<ObjectB: pob>'] out_c = ['<ObjectC: >'] # proxy model objects self.assertQuerysetEqual(ObjectB.objects.filter(objecta=self.poa).order_by('name'), out_b) self.assertQuerysetEqual(ObjectA.objects.filter(objectb__in=self.pob).order_by('pk'), out_a * 2) # child objects self.assertQuerysetEqual(ObjectB.objects.filter(objecta__in=[self.coa]), []) self.assertQuerysetEqual(ObjectB.objects.filter(objecta__in=[self.poa, self.coa]).order_by('name'), out_b) self.assertQuerysetEqual( ObjectB.objects.filter(objecta__in=iter([self.poa, self.coa])).order_by('name'), out_b ) # parent objects self.assertQuerysetEqual(ObjectC.objects.exclude(childobjecta=self.oa), out_c) # QuerySet related object type checking shouldn't issue queries # (the querysets aren't evaluated here, hence zero queries) (#23266). with self.assertNumQueries(0): ObjectB.objects.filter(objecta__in=ObjectA.objects.all()) def test_values_queryset_lookup(self): """ #23396 - Ensure ValueQuerySets are not checked for compatibility with the lookup field """ # Make sure the num and objecta field values match. ob = ObjectB.objects.get(name='ob') ob.num = ob.objecta.pk ob.save() pob = ObjectB.objects.get(name='pob') pob.num = pob.objecta.pk pob.save() self.assertQuerysetEqual(ObjectB.objects.filter( objecta__in=ObjectB.objects.all().values_list('num') ).order_by('pk'), ['<ObjectB: ob>', '<ObjectB: pob>']) class Ticket14056Tests(TestCase): def test_ticket_14056(self): s1 = SharedConnection.objects.create(data='s1') s2 = SharedConnection.objects.create(data='s2') s3 = SharedConnection.objects.create(data='s3') PointerA.objects.create(connection=s2) expected_ordering = ( [s1, s3, s2] if connection.features.nulls_order_largest else [s2, s1, s3] ) self.assertSequenceEqual(SharedConnection.objects.order_by('-pointera__connection', 'pk'), expected_ordering) class Ticket20955Tests(TestCase): def test_ticket_20955(self): jack = Staff.objects.create(name='jackstaff') jackstaff = StaffUser.objects.create(staff=jack) jill = Staff.objects.create(name='jillstaff') jillstaff = StaffUser.objects.create(staff=jill) task = Task.objects.create(creator=jackstaff, owner=jillstaff, title="task") task_get = Task.objects.get(pk=task.pk) # Load data so that assertNumQueries doesn't complain about the get # version's queries. task_get.creator.staffuser.staff task_get.owner.staffuser.staff qs = Task.objects.select_related( 'creator__staffuser__staff', 'owner__staffuser__staff') self.assertEqual(str(qs.query).count(' JOIN '), 6) task_select_related = qs.get(pk=task.pk) with self.assertNumQueries(0): self.assertEqual(task_select_related.creator.staffuser.staff, task_get.creator.staffuser.staff) self.assertEqual(task_select_related.owner.staffuser.staff, task_get.owner.staffuser.staff) class Ticket21203Tests(TestCase): def test_ticket_21203(self): p = Ticket21203Parent.objects.create(parent_bool=True) c = Ticket21203Child.objects.create(parent=p) qs = Ticket21203Child.objects.select_related('parent').defer('parent__created') self.assertSequenceEqual(qs, [c]) self.assertIs(qs[0].parent.parent_bool, True) class ValuesJoinPromotionTests(TestCase): def test_values_no_promotion_for_existing(self): qs = Node.objects.filter(parent__parent__isnull=False) self.assertIn(' INNER JOIN ', str(qs.query)) qs = qs.values('parent__parent__id') self.assertIn(' INNER JOIN ', str(qs.query)) # Make sure there is a left outer join without the filter. qs = Node.objects.values('parent__parent__id') self.assertIn(' LEFT OUTER JOIN ', str(qs.query)) def test_non_nullable_fk_not_promoted(self): qs = ObjectB.objects.values('objecta__name') self.assertIn(' INNER JOIN ', str(qs.query)) def test_ticket_21376(self): a = ObjectA.objects.create() ObjectC.objects.create(objecta=a) qs = ObjectC.objects.filter( Q(objecta=a) | Q(objectb__objecta=a), ) qs = qs.filter( Q(objectb=1) | Q(objecta=a), ) self.assertEqual(qs.count(), 1) tblname = connection.ops.quote_name(ObjectB._meta.db_table) self.assertIn(' LEFT OUTER JOIN %s' % tblname, str(qs.query)) class ForeignKeyToBaseExcludeTests(TestCase): def test_ticket_21787(self): sc1 = SpecialCategory.objects.create(special_name='sc1', name='sc1') sc2 = SpecialCategory.objects.create(special_name='sc2', name='sc2') sc3 = SpecialCategory.objects.create(special_name='sc3', name='sc3') c1 = CategoryItem.objects.create(category=sc1) CategoryItem.objects.create(category=sc2) self.assertSequenceEqual(SpecialCategory.objects.exclude(categoryitem__id=c1.pk).order_by('name'), [sc2, sc3]) self.assertSequenceEqual(SpecialCategory.objects.filter(categoryitem__id=c1.pk), [sc1]) class ReverseM2MCustomPkTests(TestCase): def test_ticket_21879(self): cpt1 = CustomPkTag.objects.create(id='cpt1', tag='cpt1') cp1 = CustomPk.objects.create(name='cp1', extra='extra') cp1.custompktag_set.add(cpt1) self.assertSequenceEqual(CustomPk.objects.filter(custompktag=cpt1), [cp1]) self.assertSequenceEqual(CustomPkTag.objects.filter(custom_pk=cp1), [cpt1]) class Ticket22429Tests(TestCase): def test_ticket_22429(self): sc1 = School.objects.create() st1 = Student.objects.create(school=sc1) sc2 = School.objects.create() st2 = Student.objects.create(school=sc2) cr = Classroom.objects.create(school=sc1) cr.students.add(st1) queryset = Student.objects.filter(~Q(classroom__school=F('school'))) self.assertSequenceEqual(queryset, [st2]) class Ticket23605Tests(TestCase): def test_ticket_23605(self): # Test filtering on a complicated q-object from ticket's report. # The query structure is such that we have multiple nested subqueries. # The original problem was that the inner queries weren't relabeled # correctly. # See also #24090. a1 = Ticket23605A.objects.create() a2 = Ticket23605A.objects.create() c1 = Ticket23605C.objects.create(field_c0=10000.0) Ticket23605B.objects.create( field_b0=10000.0, field_b1=True, modelc_fk=c1, modela_fk=a1) complex_q = Q(pk__in=Ticket23605A.objects.filter( Q( # True for a1 as field_b0 = 10000, field_c0=10000 # False for a2 as no ticket23605b found ticket23605b__field_b0__gte=1000000 / F("ticket23605b__modelc_fk__field_c0") ) & # True for a1 (field_b1=True) Q(ticket23605b__field_b1=True) & ~Q(ticket23605b__pk__in=Ticket23605B.objects.filter( ~( # Same filters as above commented filters, but # double-negated (one for Q() above, one for # parentheses). So, again a1 match, a2 not. Q(field_b1=True) & Q(field_b0__gte=1000000 / F("modelc_fk__field_c0")) ) ))).filter(ticket23605b__field_b1=True)) qs1 = Ticket23605A.objects.filter(complex_q) self.assertSequenceEqual(qs1, [a1]) qs2 = Ticket23605A.objects.exclude(complex_q) self.assertSequenceEqual(qs2, [a2]) class TestTicket24279(TestCase): def test_ticket_24278(self): School.objects.create() qs = School.objects.filter(Q(pk__in=()) | Q()) self.assertQuerysetEqual(qs, []) class TestInvalidValuesRelation(SimpleTestCase): def test_invalid_values(self): msg = "invalid literal for int() with base 10: 'abc'" with self.assertRaisesMessage(ValueError, msg): Annotation.objects.filter(tag='abc') with self.assertRaisesMessage(ValueError, msg): Annotation.objects.filter(tag__in=[123, 'abc']) class TestTicket24605(TestCase): def test_ticket_24605(self): """ Subquery table names should be quoted. """ i1 = Individual.objects.create(alive=True) RelatedIndividual.objects.create(related=i1) i2 = Individual.objects.create(alive=False) RelatedIndividual.objects.create(related=i2) i3 = Individual.objects.create(alive=True) i4 = Individual.objects.create(alive=False) self.assertSequenceEqual(Individual.objects.filter(Q(alive=False), Q(related_individual__isnull=True)), [i4]) self.assertSequenceEqual( Individual.objects.exclude(Q(alive=False), Q(related_individual__isnull=True)).order_by('pk'), [i1, i2, i3] ) class Ticket23622Tests(TestCase): @skipUnlessDBFeature('can_distinct_on_fields') def test_ticket_23622(self): """ Make sure __pk__in and __in work the same for related fields when using a distinct on subquery. """ a1 = Ticket23605A.objects.create() a2 = Ticket23605A.objects.create() c1 = Ticket23605C.objects.create(field_c0=0.0) Ticket23605B.objects.create( modela_fk=a1, field_b0=123, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a1, field_b0=23, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a1, field_b0=234, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a1, field_b0=12, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=567, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=76, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=7, field_b1=True, modelc_fk=c1, ) Ticket23605B.objects.create( modela_fk=a2, field_b0=56, field_b1=True, modelc_fk=c1, ) qx = ( Q(ticket23605b__pk__in=Ticket23605B.objects.order_by('modela_fk', '-field_b1').distinct('modela_fk')) & Q(ticket23605b__field_b0__gte=300) ) qy = ( Q(ticket23605b__in=Ticket23605B.objects.order_by('modela_fk', '-field_b1').distinct('modela_fk')) & Q(ticket23605b__field_b0__gte=300) ) self.assertEqual( set(Ticket23605A.objects.filter(qx).values_list('pk', flat=True)), set(Ticket23605A.objects.filter(qy).values_list('pk', flat=True)) ) self.assertSequenceEqual(Ticket23605A.objects.filter(qx), [a2])
aa71a082500b75926030d66b67e08c5ddcb8e70cc6273956be022b6de7d01159
""" Various complex queries that have been problematic in the past. """ import threading from django.db import models class DumbCategory(models.Model): pass class ProxyCategory(DumbCategory): class Meta: proxy = True class NamedCategory(DumbCategory): name = models.CharField(max_length=10) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=10) parent = models.ForeignKey( 'self', models.SET_NULL, blank=True, null=True, related_name='children', ) category = models.ForeignKey(NamedCategory, models.SET_NULL, null=True, default=None) class Meta: ordering = ['name'] def __str__(self): return self.name class Note(models.Model): note = models.CharField(max_length=100) misc = models.CharField(max_length=10) tag = models.ForeignKey(Tag, models.SET_NULL, blank=True, null=True) class Meta: ordering = ['note'] def __str__(self): return self.note def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Regression for #13227 -- having an attribute that # is unpicklable doesn't stop you from cloning queries # that use objects of that type as an argument. self.lock = threading.Lock() class Annotation(models.Model): name = models.CharField(max_length=10) tag = models.ForeignKey(Tag, models.CASCADE) notes = models.ManyToManyField(Note) def __str__(self): return self.name class ExtraInfo(models.Model): info = models.CharField(max_length=100) note = models.ForeignKey(Note, models.CASCADE, null=True) value = models.IntegerField(null=True) class Meta: ordering = ['info'] def __str__(self): return self.info class Author(models.Model): name = models.CharField(max_length=10) num = models.IntegerField(unique=True) extra = models.ForeignKey(ExtraInfo, models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=10) created = models.DateTimeField() modified = models.DateTimeField(blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True) creator = models.ForeignKey(Author, models.CASCADE) note = models.ForeignKey(Note, models.CASCADE) class Meta: ordering = ['-note', 'name'] def __str__(self): return self.name class Report(models.Model): name = models.CharField(max_length=10) creator = models.ForeignKey(Author, models.SET_NULL, to_field='num', null=True) def __str__(self): return self.name class ReportComment(models.Model): report = models.ForeignKey(Report, models.CASCADE) class Ranking(models.Model): rank = models.IntegerField() author = models.ForeignKey(Author, models.CASCADE) class Meta: # A complex ordering specification. Should stress the system a bit. ordering = ('author__extra__note', 'author__name', 'rank') def __str__(self): return '%d: %s' % (self.rank, self.author.name) class Cover(models.Model): title = models.CharField(max_length=50) item = models.ForeignKey(Item, models.CASCADE) class Meta: ordering = ['item'] def __str__(self): return self.title class Number(models.Model): num = models.IntegerField() def __str__(self): return str(self.num) # Symmetrical m2m field with a normal field using the reverse accessor name # ("valid"). class Valid(models.Model): valid = models.CharField(max_length=10) parent = models.ManyToManyField('self') class Meta: ordering = ['valid'] # Some funky cross-linked models for testing a couple of infinite recursion # cases. class X(models.Model): y = models.ForeignKey('Y', models.CASCADE) class Y(models.Model): x1 = models.ForeignKey(X, models.CASCADE, related_name='y1') # Some models with a cycle in the default ordering. This would be bad if we # didn't catch the infinite loop. class LoopX(models.Model): y = models.ForeignKey('LoopY', models.CASCADE) class Meta: ordering = ['y'] class LoopY(models.Model): x = models.ForeignKey(LoopX, models.CASCADE) class Meta: ordering = ['x'] class LoopZ(models.Model): z = models.ForeignKey('self', models.CASCADE) class Meta: ordering = ['z'] # A model and custom default manager combination. class CustomManager(models.Manager): def get_queryset(self): qs = super().get_queryset() return qs.filter(public=True, tag__name='t1') class ManagedModel(models.Model): data = models.CharField(max_length=10) tag = models.ForeignKey(Tag, models.CASCADE) public = models.BooleanField(default=True) objects = CustomManager() normal_manager = models.Manager() def __str__(self): return self.data # An inter-related setup with multiple paths from Child to Detail. class Detail(models.Model): data = models.CharField(max_length=10) class MemberManager(models.Manager): def get_queryset(self): return super().get_queryset().select_related("details") class Member(models.Model): name = models.CharField(max_length=10) details = models.OneToOneField(Detail, models.CASCADE, primary_key=True) objects = MemberManager() class Child(models.Model): person = models.OneToOneField(Member, models.CASCADE, primary_key=True) parent = models.ForeignKey(Member, models.CASCADE, related_name="children") # Custom primary keys interfered with ordering in the past. class CustomPk(models.Model): name = models.CharField(max_length=10, primary_key=True) extra = models.CharField(max_length=10) class Meta: ordering = ['name', 'extra'] class Related(models.Model): custom = models.ForeignKey(CustomPk, models.CASCADE, null=True) class CustomPkTag(models.Model): id = models.CharField(max_length=20, primary_key=True) custom_pk = models.ManyToManyField(CustomPk) tag = models.CharField(max_length=20) # An inter-related setup with a model subclass that has a nullable # path to another model, and a return path from that model. class Celebrity(models.Model): name = models.CharField("Name", max_length=20) greatest_fan = models.ForeignKey("Fan", models.SET_NULL, null=True, unique=True) def __str__(self): return self.name class TvChef(Celebrity): pass class Fan(models.Model): fan_of = models.ForeignKey(Celebrity, models.CASCADE) # Multiple foreign keys class LeafA(models.Model): data = models.CharField(max_length=10) def __str__(self): return self.data class LeafB(models.Model): data = models.CharField(max_length=10) class Join(models.Model): a = models.ForeignKey(LeafA, models.CASCADE) b = models.ForeignKey(LeafB, models.CASCADE) class ReservedName(models.Model): name = models.CharField(max_length=20) order = models.IntegerField() def __str__(self): return self.name # A simpler shared-foreign-key setup that can expose some problems. class SharedConnection(models.Model): data = models.CharField(max_length=10) def __str__(self): return self.data class PointerA(models.Model): connection = models.ForeignKey(SharedConnection, models.CASCADE) class PointerB(models.Model): connection = models.ForeignKey(SharedConnection, models.CASCADE) # Multi-layer ordering class SingleObject(models.Model): name = models.CharField(max_length=10) class Meta: ordering = ['name'] def __str__(self): return self.name class RelatedObject(models.Model): single = models.ForeignKey(SingleObject, models.SET_NULL, null=True) f = models.IntegerField(null=True) class Meta: ordering = ['single'] class Plaything(models.Model): name = models.CharField(max_length=10) others = models.ForeignKey(RelatedObject, models.SET_NULL, null=True) class Meta: ordering = ['others'] def __str__(self): return self.name class Article(models.Model): name = models.CharField(max_length=20) created = models.DateTimeField() def __str__(self): return self.name class Food(models.Model): name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class Eaten(models.Model): food = models.ForeignKey(Food, models.SET_NULL, to_field="name", null=True) meal = models.CharField(max_length=20) def __str__(self): return "%s at %s" % (self.food, self.meal) class Node(models.Model): num = models.IntegerField(unique=True) parent = models.ForeignKey("self", models.SET_NULL, to_field="num", null=True) def __str__(self): return "%s" % self.num # Bug #12252 class ObjectA(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name def __iter__(self): # Ticket #23721 assert False, 'type checking should happen without calling model __iter__' class ProxyObjectA(ObjectA): class Meta: proxy = True class ChildObjectA(ObjectA): pass class ObjectB(models.Model): name = models.CharField(max_length=50) objecta = models.ForeignKey(ObjectA, models.CASCADE) num = models.PositiveSmallIntegerField() def __str__(self): return self.name class ProxyObjectB(ObjectB): class Meta: proxy = True class ObjectC(models.Model): name = models.CharField(max_length=50) objecta = models.ForeignKey(ObjectA, models.SET_NULL, null=True) objectb = models.ForeignKey(ObjectB, models.SET_NULL, null=True) childobjecta = models.ForeignKey(ChildObjectA, models.SET_NULL, null=True, related_name='ca_pk') def __str__(self): return self.name class SimpleCategory(models.Model): name = models.CharField(max_length=15) def __str__(self): return self.name class SpecialCategory(SimpleCategory): special_name = models.CharField(max_length=15) def __str__(self): return self.name + " " + self.special_name class CategoryItem(models.Model): category = models.ForeignKey(SimpleCategory, models.CASCADE) def __str__(self): return "category item: " + str(self.category) class MixedCaseFieldCategoryItem(models.Model): CaTeGoRy = models.ForeignKey(SimpleCategory, models.CASCADE) class MixedCaseDbColumnCategoryItem(models.Model): category = models.ForeignKey(SimpleCategory, models.CASCADE, db_column='CaTeGoRy_Id') class OneToOneCategory(models.Model): new_name = models.CharField(max_length=15) category = models.OneToOneField(SimpleCategory, models.CASCADE) def __str__(self): return "one2one " + self.new_name class CategoryRelationship(models.Model): first = models.ForeignKey(SimpleCategory, models.CASCADE, related_name='first_rel') second = models.ForeignKey(SimpleCategory, models.CASCADE, related_name='second_rel') class CommonMixedCaseForeignKeys(models.Model): category = models.ForeignKey(CategoryItem, models.CASCADE) mixed_case_field_category = models.ForeignKey(MixedCaseFieldCategoryItem, models.CASCADE) mixed_case_db_column_category = models.ForeignKey(MixedCaseDbColumnCategoryItem, models.CASCADE) class NullableName(models.Model): name = models.CharField(max_length=20, null=True) class Meta: ordering = ['id'] class ModelD(models.Model): name = models.TextField() class ModelC(models.Model): name = models.TextField() class ModelB(models.Model): name = models.TextField() c = models.ForeignKey(ModelC, models.CASCADE) class ModelA(models.Model): name = models.TextField() b = models.ForeignKey(ModelB, models.SET_NULL, null=True) d = models.ForeignKey(ModelD, models.CASCADE) class Job(models.Model): name = models.CharField(max_length=20, unique=True) def __str__(self): return self.name class JobResponsibilities(models.Model): job = models.ForeignKey(Job, models.CASCADE, to_field='name') responsibility = models.ForeignKey('Responsibility', models.CASCADE, to_field='description') class Responsibility(models.Model): description = models.CharField(max_length=20, unique=True) jobs = models.ManyToManyField(Job, through=JobResponsibilities, related_name='responsibilities') def __str__(self): return self.description # Models for disjunction join promotion low level testing. class FK1(models.Model): f1 = models.TextField() f2 = models.TextField() class FK2(models.Model): f1 = models.TextField() f2 = models.TextField() class FK3(models.Model): f1 = models.TextField() f2 = models.TextField() class BaseA(models.Model): a = models.ForeignKey(FK1, models.SET_NULL, null=True) b = models.ForeignKey(FK2, models.SET_NULL, null=True) c = models.ForeignKey(FK3, models.SET_NULL, null=True) class Identifier(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Program(models.Model): identifier = models.OneToOneField(Identifier, models.CASCADE) class Channel(models.Model): programs = models.ManyToManyField(Program) identifier = models.OneToOneField(Identifier, models.CASCADE) class Book(models.Model): title = models.TextField() chapter = models.ForeignKey('Chapter', models.CASCADE) class Chapter(models.Model): title = models.TextField() paragraph = models.ForeignKey('Paragraph', models.CASCADE) class Paragraph(models.Model): text = models.TextField() page = models.ManyToManyField('Page') class Page(models.Model): text = models.TextField() class MyObject(models.Model): parent = models.ForeignKey('self', models.SET_NULL, null=True, blank=True, related_name='children') data = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) # Models for #17600 regressions class Order(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=12, null=True, default='') class Meta: ordering = ('pk',) def __str__(self): return '%s' % self.pk class OrderItem(models.Model): order = models.ForeignKey(Order, models.CASCADE, related_name='items') status = models.IntegerField() class Meta: ordering = ('pk',) def __str__(self): return '%s' % self.pk class BaseUser(models.Model): pass class Task(models.Model): title = models.CharField(max_length=10) owner = models.ForeignKey(BaseUser, models.CASCADE, related_name='owner') creator = models.ForeignKey(BaseUser, models.CASCADE, related_name='creator') def __str__(self): return self.title class Staff(models.Model): name = models.CharField(max_length=10) def __str__(self): return self.name class StaffUser(BaseUser): staff = models.OneToOneField(Staff, models.CASCADE, related_name='user') def __str__(self): return self.staff class Ticket21203Parent(models.Model): parentid = models.AutoField(primary_key=True) parent_bool = models.BooleanField(default=True) created = models.DateTimeField(auto_now=True) class Ticket21203Child(models.Model): childid = models.AutoField(primary_key=True) parent = models.ForeignKey(Ticket21203Parent, models.CASCADE) class Person(models.Model): name = models.CharField(max_length=128) class Company(models.Model): name = models.CharField(max_length=128) employees = models.ManyToManyField(Person, related_name='employers', through='Employment') def __str__(self): return self.name class Employment(models.Model): employer = models.ForeignKey(Company, models.CASCADE) employee = models.ForeignKey(Person, models.CASCADE) title = models.CharField(max_length=128) class School(models.Model): pass class Student(models.Model): school = models.ForeignKey(School, models.CASCADE) class Classroom(models.Model): name = models.CharField(max_length=20) has_blackboard = models.BooleanField(null=True) school = models.ForeignKey(School, models.CASCADE) students = models.ManyToManyField(Student, related_name='classroom') class Teacher(models.Model): schools = models.ManyToManyField(School) friends = models.ManyToManyField('self') class Ticket23605AParent(models.Model): pass class Ticket23605A(Ticket23605AParent): pass class Ticket23605B(models.Model): modela_fk = models.ForeignKey(Ticket23605A, models.CASCADE) modelc_fk = models.ForeignKey("Ticket23605C", models.CASCADE) field_b0 = models.IntegerField(null=True) field_b1 = models.BooleanField(default=False) class Ticket23605C(models.Model): field_c0 = models.FloatField() # db_table names have capital letters to ensure they are quoted in queries. class Individual(models.Model): alive = models.BooleanField() class Meta: db_table = 'Individual' class RelatedIndividual(models.Model): related = models.ForeignKey(Individual, models.CASCADE, related_name='related_individual') class Meta: db_table = 'RelatedIndividual' class CustomDbColumn(models.Model): custom_column = models.IntegerField(db_column='custom_name', null=True) ip_address = models.GenericIPAddressField(null=True)
6e44b22be1263f3711fd190714c967bfe811d1cdeb8c7da89cee33ff69e8a565
from django.db.models import Exists, F, IntegerField, OuterRef, Value from django.db.utils import DatabaseError, NotSupportedError from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from .models import Number, ReservedName @skipUnlessDBFeature('supports_select_union') class QuerySetSetOperationTests(TestCase): @classmethod def setUpTestData(cls): Number.objects.bulk_create(Number(num=i) for i in range(10)) def number_transform(self, value): return value.num def assertNumbersEqual(self, queryset, expected_numbers, ordered=True): self.assertQuerysetEqual(queryset, expected_numbers, self.number_transform, ordered) def test_simple_union(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=8) qs3 = Number.objects.filter(num=5) self.assertNumbersEqual(qs1.union(qs2, qs3), [0, 1, 5, 8, 9], ordered=False) @skipUnlessDBFeature('supports_select_intersection') def test_simple_intersection(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__gte=5) qs3 = Number.objects.filter(num__gte=4, num__lte=6) self.assertNumbersEqual(qs1.intersection(qs2, qs3), [5], ordered=False) @skipUnlessDBFeature('supports_select_intersection') def test_intersection_with_values(self): ReservedName.objects.create(name='a', order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.intersection(qs1).values('name', 'order', 'id').get() self.assertEqual(reserved_name['name'], 'a') self.assertEqual(reserved_name['order'], 2) reserved_name = qs1.intersection(qs1).values_list('name', 'order', 'id').get() self.assertEqual(reserved_name[:2], ('a', 2)) @skipUnlessDBFeature('supports_select_difference') def test_simple_difference(self): qs1 = Number.objects.filter(num__lte=5) qs2 = Number.objects.filter(num__lte=4) self.assertNumbersEqual(qs1.difference(qs2), [5], ordered=False) def test_union_distinct(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2, all=True))), 20) self.assertEqual(len(list(qs1.union(qs2))), 10) @skipUnlessDBFeature('supports_select_intersection') def test_intersection_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.intersection(qs2)), 0) self.assertEqual(len(qs1.intersection(qs3)), 0) self.assertEqual(len(qs2.intersection(qs1)), 0) self.assertEqual(len(qs3.intersection(qs1)), 0) self.assertEqual(len(qs2.intersection(qs2)), 0) self.assertEqual(len(qs3.intersection(qs3)), 0) @skipUnlessDBFeature('supports_select_difference') def test_difference_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.difference(qs2)), 10) self.assertEqual(len(qs1.difference(qs3)), 10) self.assertEqual(len(qs2.difference(qs1)), 0) self.assertEqual(len(qs3.difference(qs1)), 0) self.assertEqual(len(qs2.difference(qs2)), 0) self.assertEqual(len(qs3.difference(qs3)), 0) @skipUnlessDBFeature('supports_select_difference') def test_difference_with_values(self): ReservedName.objects.create(name='a', order=2) qs1 = ReservedName.objects.all() qs2 = ReservedName.objects.none() reserved_name = qs1.difference(qs2).values('name', 'order', 'id').get() self.assertEqual(reserved_name['name'], 'a') self.assertEqual(reserved_name['order'], 2) reserved_name = qs1.difference(qs2).values_list('name', 'order', 'id').get() self.assertEqual(reserved_name[:2], ('a', 2)) def test_union_with_empty_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.none() qs3 = Number.objects.filter(pk__in=[]) self.assertEqual(len(qs1.union(qs2)), 10) self.assertEqual(len(qs2.union(qs1)), 10) self.assertEqual(len(qs1.union(qs3)), 10) self.assertEqual(len(qs3.union(qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, qs1)), 10) self.assertEqual(len(qs2.union(qs1, qs1, all=True)), 20) self.assertEqual(len(qs2.union(qs2)), 0) self.assertEqual(len(qs3.union(qs3)), 0) def test_limits(self): qs1 = Number.objects.all() qs2 = Number.objects.all() self.assertEqual(len(list(qs1.union(qs2)[:2])), 2) def test_ordering(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by('-num'), [3, 2, 1, 0]) def test_ordering_by_f_expression(self): qs1 = Number.objects.filter(num__lte=1) qs2 = Number.objects.filter(num__gte=2, num__lte=3) self.assertNumbersEqual(qs1.union(qs2).order_by(F('num').desc()), [3, 2, 1, 0]) def test_union_with_values(self): ReservedName.objects.create(name='a', order=2) qs1 = ReservedName.objects.all() reserved_name = qs1.union(qs1).values('name', 'order', 'id').get() self.assertEqual(reserved_name['name'], 'a') self.assertEqual(reserved_name['order'], 2) reserved_name = qs1.union(qs1).values_list('name', 'order', 'id').get() self.assertEqual(reserved_name[:2], ('a', 2)) # List of columns can be changed. reserved_name = qs1.union(qs1).values_list('order').get() self.assertEqual(reserved_name, (2,)) def test_union_with_two_annotated_values_list(self): qs1 = Number.objects.filter(num=1).annotate( count=Value(0, IntegerField()), ).values_list('num', 'count') qs2 = Number.objects.filter(num=2).values('pk').annotate( count=F('num'), ).annotate( num=Value(1, IntegerField()), ).values_list('num', 'count') self.assertCountEqual(qs1.union(qs2), [(1, 0), (2, 1)]) def test_union_with_extra_and_values_list(self): qs1 = Number.objects.filter(num=1).extra( select={'count': 0}, ).values_list('num', 'count') qs2 = Number.objects.filter(num=2).extra(select={'count': 1}) self.assertCountEqual(qs1.union(qs2), [(1, 0), (2, 1)]) def test_union_with_values_list_on_annotated_and_unannotated(self): ReservedName.objects.create(name='rn1', order=1) qs1 = Number.objects.annotate( has_reserved_name=Exists(ReservedName.objects.filter(order=OuterRef('num'))) ).filter(has_reserved_name=True) qs2 = Number.objects.filter(num=9) self.assertCountEqual(qs1.union(qs2).values_list('num', flat=True), [1, 9]) def test_count_union(self): qs1 = Number.objects.filter(num__lte=1).values('num') qs2 = Number.objects.filter(num__gte=2, num__lte=3).values('num') self.assertEqual(qs1.union(qs2).count(), 4) def test_count_union_empty_result(self): qs = Number.objects.filter(pk__in=[]) self.assertEqual(qs.union(qs).count(), 0) @skipUnlessDBFeature('supports_select_difference') def test_count_difference(self): qs1 = Number.objects.filter(num__lt=10) qs2 = Number.objects.filter(num__lt=9) self.assertEqual(qs1.difference(qs2).count(), 1) @skipUnlessDBFeature('supports_select_intersection') def test_count_intersection(self): qs1 = Number.objects.filter(num__gte=5) qs2 = Number.objects.filter(num__lte=5) self.assertEqual(qs1.intersection(qs2).count(), 1) @skipUnlessDBFeature('supports_slicing_ordering_in_compound') def test_ordering_subqueries(self): qs1 = Number.objects.order_by('num')[:2] qs2 = Number.objects.order_by('-num')[:2] self.assertNumbersEqual(qs1.union(qs2).order_by('-num')[:4], [9, 8, 1, 0]) @skipIfDBFeature('supports_slicing_ordering_in_compound') def test_unsupported_ordering_slicing_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() msg = 'LIMIT/OFFSET not allowed in subqueries of compound statements' with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2[:10])) msg = 'ORDER BY not allowed in subqueries of compound statements' with self.assertRaisesMessage(DatabaseError, msg): list(qs1.order_by('id').union(qs2)) @skipIfDBFeature('supports_select_intersection') def test_unsupported_intersection_raises_db_error(self): qs1 = Number.objects.all() qs2 = Number.objects.all() msg = 'intersection is not supported on this database backend' with self.assertRaisesMessage(NotSupportedError, msg): list(qs1.intersection(qs2)) def test_combining_multiple_models(self): ReservedName.objects.create(name='99 little bugs', order=99) qs1 = Number.objects.filter(num=1).values_list('num', flat=True) qs2 = ReservedName.objects.values_list('order') self.assertEqual(list(qs1.union(qs2).order_by('num')), [1, 99]) def test_order_raises_on_non_selected_column(self): qs1 = Number.objects.filter().annotate( annotation=Value(1, IntegerField()), ).values('annotation', num2=F('num')) qs2 = Number.objects.filter().values('id', 'num') # Should not raise list(qs1.union(qs2).order_by('annotation')) list(qs1.union(qs2).order_by('num2')) msg = 'ORDER BY term does not match any column in the result set' # 'id' is not part of the select with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by('id')) # 'num' got realiased to num2 with self.assertRaisesMessage(DatabaseError, msg): list(qs1.union(qs2).order_by('num')) # switched order, now 'exists' again: list(qs2.union(qs1).order_by('num')) @skipUnlessDBFeature('supports_select_difference', 'supports_select_intersection') def test_qs_with_subcompound_qs(self): qs1 = Number.objects.all() qs2 = Number.objects.intersection(Number.objects.filter(num__gt=1)) self.assertEqual(qs1.difference(qs2).count(), 2)
3e1e31b163d1e6071d7abb225a6c2f085f0c4a299c8c2152f83e30a8c715fa01
import unittest from django.db import NotSupportedError, connection, transaction from django.db.models import Count from django.test import ( TestCase, ignore_warnings, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import CaptureQueriesContext from django.utils.deprecation import RemovedInDjango31Warning from .models import Tag @skipUnlessDBFeature('supports_explaining_query_execution') class ExplainTests(TestCase): @ignore_warnings(category=RemovedInDjango31Warning) def test_basic(self): querysets = [ Tag.objects.filter(name='test'), Tag.objects.filter(name='test').select_related('parent'), Tag.objects.filter(name='test').prefetch_related('children'), Tag.objects.filter(name='test').annotate(Count('children')), Tag.objects.filter(name='test').values_list('name'), Tag.objects.order_by().union(Tag.objects.order_by().filter(name='test')), Tag.objects.all().select_for_update().filter(name='test'), ] supported_formats = connection.features.supported_explain_formats all_formats = (None,) + tuple(supported_formats) + tuple(f.lower() for f in supported_formats) for idx, queryset in enumerate(querysets): for format in all_formats: with self.subTest(format=format, queryset=idx): if connection.vendor == 'mysql': # This does a query and caches the result. connection.features.needs_explain_extended with self.assertNumQueries(1), CaptureQueriesContext(connection) as captured_queries: result = queryset.explain(format=format) self.assertTrue(captured_queries[0]['sql'].startswith(connection.ops.explain_prefix)) self.assertIsInstance(result, str) self.assertTrue(result) @skipUnlessDBFeature('validates_explain_options') def test_unknown_options(self): with self.assertRaisesMessage(ValueError, 'Unknown options: test, test2'): Tag.objects.all().explain(test=1, test2=1) def test_unknown_format(self): msg = 'DOES NOT EXIST is not a recognized format.' if connection.features.supported_explain_formats: msg += ' Allowed formats: %s' % ', '.join(sorted(connection.features.supported_explain_formats)) with self.assertRaisesMessage(ValueError, msg): Tag.objects.all().explain(format='does not exist') @unittest.skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific') def test_postgres_options(self): qs = Tag.objects.filter(name='test') test_options = [ {'COSTS': False, 'BUFFERS': True, 'ANALYZE': True}, {'costs': False, 'buffers': True, 'analyze': True}, {'verbose': True, 'timing': True, 'analyze': True}, {'verbose': False, 'timing': False, 'analyze': True}, ] if connection.pg_version >= 100000: test_options.append({'summary': True}) for options in test_options: with self.subTest(**options), transaction.atomic(): with CaptureQueriesContext(connection) as captured_queries: qs.explain(format='text', **options) self.assertEqual(len(captured_queries), 1) for name, value in options.items(): option = '{} {}'.format(name.upper(), 'true' if value else 'false') self.assertIn(option, captured_queries[0]['sql']) @unittest.skipUnless(connection.vendor == 'mysql', 'MySQL specific') def test_mysql_text_to_traditional(self): # Initialize the cached property, if needed, to prevent a query for # the MySQL version during the QuerySet evaluation. connection.features.needs_explain_extended with CaptureQueriesContext(connection) as captured_queries: Tag.objects.filter(name='test').explain(format='text') self.assertEqual(len(captured_queries), 1) self.assertIn('FORMAT=TRADITIONAL', captured_queries[0]['sql']) @unittest.skipUnless(connection.vendor == 'mysql', 'MySQL < 5.7 specific') def test_mysql_extended(self): # Inner skip to avoid module level query for MySQL version. if not connection.features.needs_explain_extended: raise unittest.SkipTest('MySQL < 5.7 specific') qs = Tag.objects.filter(name='test') with CaptureQueriesContext(connection) as captured_queries: qs.explain(format='json') self.assertEqual(len(captured_queries), 1) self.assertNotIn('EXTENDED', captured_queries[0]['sql']) with CaptureQueriesContext(connection) as captured_queries: qs.explain(format='text') self.assertEqual(len(captured_queries), 1) self.assertNotIn('EXTENDED', captured_queries[0]['sql']) @skipIfDBFeature('supports_explaining_query_execution') class ExplainUnsupportedTests(TestCase): def test_message(self): msg = 'This backend does not support explaining query execution.' with self.assertRaisesMessage(NotSupportedError, msg): Tag.objects.filter(name='test').explain()
de3dc7a10dc33b8a0348a850cb0c4a4dfa2f1c6e3a2647a3a67981eb98f65cc0
from datetime import datetime from django.core.exceptions import FieldError from django.db.models import CharField, F, Q from django.db.models.expressions import SimpleCol from django.db.models.fields.related_lookups import RelatedIsNull from django.db.models.functions import Lower from django.db.models.lookups import Exact, GreaterThan, IsNull, LessThan from django.db.models.sql.query import Query from django.db.models.sql.where import OR from django.test import SimpleTestCase from django.test.utils import register_lookup from .models import Author, Item, ObjectC, Ranking class TestQuery(SimpleTestCase): def test_simple_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2)) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_simplecol_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2, name__isnull=False) | Q(num__lt=F('id'))) name_isnull_lookup, num_gt_lookup = where.children[0].children self.assertIsInstance(num_gt_lookup, GreaterThan) self.assertIsInstance(num_gt_lookup.lhs, SimpleCol) self.assertIsInstance(name_isnull_lookup, IsNull) self.assertIsInstance(name_isnull_lookup.lhs, SimpleCol) num_lt_lookup = where.children[1] self.assertIsInstance(num_lt_lookup, LessThan) self.assertIsInstance(num_lt_lookup.rhs, SimpleCol) self.assertIsInstance(num_lt_lookup.lhs, SimpleCol) def test_complex_query(self): query = Query(Author) where = query.build_where(Q(num__gt=2) | Q(num__lt=0)) self.assertEqual(where.connector, OR) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertEqual(lookup.rhs, 2) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) lookup = where.children[1] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.rhs, 0) self.assertEqual(lookup.lhs.target, Author._meta.get_field('num')) def test_multiple_fields(self): query = Query(Item) where = query.build_where(Q(modified__gt=F('created'))) lookup = where.children[0] self.assertIsInstance(lookup, GreaterThan) self.assertIsInstance(lookup.rhs, SimpleCol) self.assertIsInstance(lookup.lhs, SimpleCol) self.assertEqual(lookup.rhs.target, Item._meta.get_field('created')) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_transform(self): query = Query(Author) with register_lookup(CharField, Lower): where = query.build_where(~Q(name__lower='foo')) lookup = where.children[0] self.assertIsInstance(lookup, Exact) self.assertIsInstance(lookup.lhs, Lower) self.assertIsInstance(lookup.lhs.lhs, SimpleCol) self.assertEqual(lookup.lhs.lhs.target, Author._meta.get_field('name')) def test_negated_nullable(self): query = Query(Item) where = query.build_where(~Q(modified__lt=datetime(2017, 1, 1))) self.assertTrue(where.negated) lookup = where.children[0] self.assertIsInstance(lookup, LessThan) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) lookup = where.children[1] self.assertIsInstance(lookup, IsNull) self.assertEqual(lookup.lhs.target, Item._meta.get_field('modified')) def test_foreign_key(self): query = Query(Item) msg = 'Joined field references are not permitted in this query' with self.assertRaisesMessage(FieldError, msg): query.build_where(Q(creator__num__gt=2)) def test_foreign_key_f(self): query = Query(Ranking) with self.assertRaises(FieldError): query.build_where(Q(rank__gt=F('author__num'))) def test_foreign_key_exclusive(self): query = Query(ObjectC) where = query.build_where(Q(objecta=None) | Q(objectb=None)) a_isnull = where.children[0] self.assertIsInstance(a_isnull, RelatedIsNull) self.assertIsInstance(a_isnull.lhs, SimpleCol) self.assertEqual(a_isnull.lhs.target, ObjectC._meta.get_field('objecta')) b_isnull = where.children[1] self.assertIsInstance(b_isnull, RelatedIsNull) self.assertIsInstance(b_isnull.lhs, SimpleCol) self.assertEqual(b_isnull.lhs.target, ObjectC._meta.get_field('objectb'))
e17e11c7b853d41bea3b53211e164da4883559231dd7b4b1ac45912a3a6633d0
import datetime from django.core.exceptions import FieldDoesNotExist from django.db.models import F from django.db.models.functions import Lower from django.test import TestCase from .models import ( Article, CustomDbColumn, CustomPk, Detail, Individual, Member, Note, Number, Order, Paragraph, SpecialCategory, Tag, Valid, ) class BulkUpdateNoteTests(TestCase): def setUp(self): self.notes = [ Note.objects.create(note=str(i), misc=str(i)) for i in range(10) ] def create_tags(self): self.tags = [ Tag.objects.create(name=str(i)) for i in range(10) ] def test_simple(self): for note in self.notes: note.note = 'test-%s' % note.id with self.assertNumQueries(1): Note.objects.bulk_update(self.notes, ['note']) self.assertCountEqual( Note.objects.values_list('note', flat=True), [cat.note for cat in self.notes] ) def test_multiple_fields(self): for note in self.notes: note.note = 'test-%s' % note.id note.misc = 'misc-%s' % note.id with self.assertNumQueries(1): Note.objects.bulk_update(self.notes, ['note', 'misc']) self.assertCountEqual( Note.objects.values_list('note', flat=True), [cat.note for cat in self.notes] ) self.assertCountEqual( Note.objects.values_list('misc', flat=True), [cat.misc for cat in self.notes] ) def test_batch_size(self): with self.assertNumQueries(len(self.notes)): Note.objects.bulk_update(self.notes, fields=['note'], batch_size=1) def test_unsaved_models(self): objs = self.notes + [Note(note='test', misc='test')] msg = 'All bulk_update() objects must have a primary key set.' with self.assertRaisesMessage(ValueError, msg): Note.objects.bulk_update(objs, fields=['note']) def test_foreign_keys_do_not_lookup(self): self.create_tags() for note, tag in zip(self.notes, self.tags): note.tag = tag with self.assertNumQueries(1): Note.objects.bulk_update(self.notes, ['tag']) self.assertSequenceEqual(Note.objects.filter(tag__isnull=False), self.notes) def test_set_field_to_null(self): self.create_tags() Note.objects.update(tag=self.tags[0]) for note in self.notes: note.tag = None Note.objects.bulk_update(self.notes, ['tag']) self.assertCountEqual(Note.objects.filter(tag__isnull=True), self.notes) def test_set_mixed_fields_to_null(self): self.create_tags() midpoint = len(self.notes) // 2 top, bottom = self.notes[:midpoint], self.notes[midpoint:] for note in top: note.tag = None for note in bottom: note.tag = self.tags[0] Note.objects.bulk_update(self.notes, ['tag']) self.assertCountEqual(Note.objects.filter(tag__isnull=True), top) self.assertCountEqual(Note.objects.filter(tag__isnull=False), bottom) def test_functions(self): Note.objects.update(note='TEST') for note in self.notes: note.note = Lower('note') Note.objects.bulk_update(self.notes, ['note']) self.assertEqual(set(Note.objects.values_list('note', flat=True)), {'test'}) # Tests that use self.notes go here, otherwise put them in another class. class BulkUpdateTests(TestCase): def test_no_fields(self): msg = 'Field names must be given to bulk_update().' with self.assertRaisesMessage(ValueError, msg): Note.objects.bulk_update([], fields=[]) def test_invalid_batch_size(self): msg = 'Batch size must be a positive integer.' with self.assertRaisesMessage(ValueError, msg): Note.objects.bulk_update([], fields=['note'], batch_size=-1) def test_nonexistent_field(self): with self.assertRaisesMessage(FieldDoesNotExist, "Note has no field named 'nonexistent'"): Note.objects.bulk_update([], ['nonexistent']) pk_fields_error = 'bulk_update() cannot be used with primary key fields.' def test_update_primary_key(self): with self.assertRaisesMessage(ValueError, self.pk_fields_error): Note.objects.bulk_update([], ['id']) def test_update_custom_primary_key(self): with self.assertRaisesMessage(ValueError, self.pk_fields_error): CustomPk.objects.bulk_update([], ['name']) def test_empty_objects(self): with self.assertNumQueries(0): Note.objects.bulk_update([], ['note']) def test_large_batch(self): Note.objects.bulk_create([ Note(note=str(i), misc=str(i)) for i in range(0, 2000) ]) notes = list(Note.objects.all()) Note.objects.bulk_update(notes, ['note']) def test_only_concrete_fields_allowed(self): obj = Valid.objects.create(valid='test') detail = Detail.objects.create(data='test') paragraph = Paragraph.objects.create(text='test') Member.objects.create(name='test', details=detail) msg = 'bulk_update() can only be used with concrete fields.' with self.assertRaisesMessage(ValueError, msg): Detail.objects.bulk_update([detail], fields=['member']) with self.assertRaisesMessage(ValueError, msg): Paragraph.objects.bulk_update([paragraph], fields=['page']) with self.assertRaisesMessage(ValueError, msg): Valid.objects.bulk_update([obj], fields=['parent']) def test_custom_db_columns(self): model = CustomDbColumn.objects.create(custom_column=1) model.custom_column = 2 CustomDbColumn.objects.bulk_update([model], fields=['custom_column']) model.refresh_from_db() self.assertEqual(model.custom_column, 2) def test_custom_pk(self): custom_pks = [ CustomPk.objects.create(name='pk-%s' % i, extra='') for i in range(10) ] for model in custom_pks: model.extra = 'extra-%s' % model.pk CustomPk.objects.bulk_update(custom_pks, ['extra']) self.assertCountEqual( CustomPk.objects.values_list('extra', flat=True), [cat.extra for cat in custom_pks] ) def test_falsey_pk_value(self): order = Order.objects.create(pk=0, name='test') order.name = 'updated' Order.objects.bulk_update([order], ['name']) order.refresh_from_db() self.assertEqual(order.name, 'updated') def test_inherited_fields(self): special_categories = [ SpecialCategory.objects.create(name=str(i), special_name=str(i)) for i in range(10) ] for category in special_categories: category.name = 'test-%s' % category.id category.special_name = 'special-test-%s' % category.special_name SpecialCategory.objects.bulk_update(special_categories, ['name', 'special_name']) self.assertCountEqual( SpecialCategory.objects.values_list('name', flat=True), [cat.name for cat in special_categories] ) self.assertCountEqual( SpecialCategory.objects.values_list('special_name', flat=True), [cat.special_name for cat in special_categories] ) def test_field_references(self): numbers = [Number.objects.create(num=0) for _ in range(10)] for number in numbers: number.num = F('num') + 1 Number.objects.bulk_update(numbers, ['num']) self.assertCountEqual(Number.objects.filter(num=1), numbers) def test_booleanfield(self): individuals = [Individual.objects.create(alive=False) for _ in range(10)] for individual in individuals: individual.alive = True Individual.objects.bulk_update(individuals, ['alive']) self.assertCountEqual(Individual.objects.filter(alive=True), individuals) def test_ipaddressfield(self): for ip in ('2001::1', '1.2.3.4'): with self.subTest(ip=ip): models = [ CustomDbColumn.objects.create(ip_address='0.0.0.0') for _ in range(10) ] for model in models: model.ip_address = ip CustomDbColumn.objects.bulk_update(models, ['ip_address']) self.assertCountEqual(CustomDbColumn.objects.filter(ip_address=ip), models) def test_datetime_field(self): articles = [ Article.objects.create(name=str(i), created=datetime.datetime.today()) for i in range(10) ] point_in_time = datetime.datetime(1991, 10, 31) for article in articles: article.created = point_in_time Article.objects.bulk_update(articles, ['created']) self.assertCountEqual(Article.objects.filter(created=point_in_time), articles)
1600c01c2446f5fc5b9d07ff9fa734a878b3ac87aa3fb9c03449968d33486d8b
from django.http import HttpRequest from django.template import ( Context, Engine, RequestContext, Template, Variable, VariableDoesNotExist, ) from django.template.context import RenderContext from django.test import RequestFactory, SimpleTestCase class ContextTests(SimpleTestCase): def test_context(self): c = Context({"a": 1, "b": "xyzzy"}) self.assertEqual(c["a"], 1) self.assertEqual(c.push(), {}) c["a"] = 2 self.assertEqual(c["a"], 2) self.assertEqual(c.get("a"), 2) self.assertEqual(c.pop(), {"a": 2}) self.assertEqual(c["a"], 1) self.assertEqual(c.get("foo", 42), 42) def test_push_context_manager(self): c = Context({"a": 1}) with c.push(): c['a'] = 2 self.assertEqual(c['a'], 2) self.assertEqual(c['a'], 1) with c.push(a=3): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_update_context_manager(self): c = Context({"a": 1}) with c.update({}): c['a'] = 2 self.assertEqual(c['a'], 2) self.assertEqual(c['a'], 1) with c.update({'a': 3}): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_push_context_manager_with_context_object(self): c = Context({'a': 1}) with c.push(Context({'a': 3})): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_update_context_manager_with_context_object(self): c = Context({'a': 1}) with c.update(Context({'a': 3})): self.assertEqual(c['a'], 3) self.assertEqual(c['a'], 1) def test_push_proper_layering(self): c = Context({'a': 1}) c.push(Context({'b': 2})) c.push(Context({'c': 3, 'd': {'z': '26'}})) self.assertEqual( c.dicts, [ {'False': False, 'None': None, 'True': True}, {'a': 1}, {'b': 2}, {'c': 3, 'd': {'z': '26'}}, ] ) def test_update_proper_layering(self): c = Context({'a': 1}) c.update(Context({'b': 2})) c.update(Context({'c': 3, 'd': {'z': '26'}})) self.assertEqual( c.dicts, [ {'False': False, 'None': None, 'True': True}, {'a': 1}, {'b': 2}, {'c': 3, 'd': {'z': '26'}}, ] ) def test_setdefault(self): c = Context() x = c.setdefault('x', 42) self.assertEqual(x, 42) self.assertEqual(c['x'], 42) x = c.setdefault('x', 100) self.assertEqual(x, 42) self.assertEqual(c['x'], 42) def test_resolve_on_context_method(self): """ #17778 -- Variable shouldn't resolve RequestContext methods """ empty_context = Context() with self.assertRaises(VariableDoesNotExist): Variable('no_such_variable').resolve(empty_context) with self.assertRaises(VariableDoesNotExist): Variable('new').resolve(empty_context) self.assertEqual( Variable('new').resolve(Context({'new': 'foo'})), 'foo', ) def test_render_context(self): test_context = RenderContext({'fruit': 'papaya'}) # push() limits access to the topmost dict test_context.push() test_context['vegetable'] = 'artichoke' self.assertEqual(list(test_context), ['vegetable']) self.assertNotIn('fruit', test_context) with self.assertRaises(KeyError): test_context['fruit'] self.assertIsNone(test_context.get('fruit')) def test_flatten_context(self): a = Context() a.update({'a': 2}) a.update({'b': 4}) a.update({'c': 8}) self.assertEqual(a.flatten(), { 'False': False, 'None': None, 'True': True, 'a': 2, 'b': 4, 'c': 8 }) def test_flatten_context_with_context(self): """ Context.push() with a Context argument should work. """ a = Context({'a': 2}) a.push(Context({'z': '8'})) self.assertEqual(a.flatten(), { 'False': False, 'None': None, 'True': True, 'a': 2, 'z': '8', }) def test_context_comparable(self): """ #21765 -- equality comparison should work """ test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} self.assertEqual(Context(test_data), Context(test_data)) a = Context() b = Context() self.assertEqual(a, b) # update only a a.update({'a': 1}) self.assertNotEqual(a, b) # update both to check regression a.update({'c': 3}) b.update({'c': 3}) self.assertNotEqual(a, b) # make contexts equals again b.update({'a': 1}) self.assertEqual(a, b) def test_copy_request_context_twice(self): """ #24273 -- Copy twice shouldn't raise an exception """ RequestContext(HttpRequest()).new().new() def test_set_upward(self): c = Context({'a': 1}) c.set_upward('a', 2) self.assertEqual(c.get('a'), 2) def test_set_upward_empty_context(self): empty_context = Context() empty_context.set_upward('a', 1) self.assertEqual(empty_context.get('a'), 1) def test_set_upward_with_push(self): """ The highest context which has the given key is used. """ c = Context({'a': 1}) c.push({'a': 2}) c.set_upward('a', 3) self.assertEqual(c.get('a'), 3) c.pop() self.assertEqual(c.get('a'), 1) def test_set_upward_with_push_no_match(self): """ The highest context is used if the given key isn't found. """ c = Context({'b': 1}) c.push({'b': 2}) c.set_upward('a', 2) self.assertEqual(len(c.dicts), 3) self.assertEqual(c.dicts[-1]['a'], 2) class RequestContextTests(SimpleTestCase): request_factory = RequestFactory() def test_include_only(self): """ #15721 -- ``{% include %}`` and ``RequestContext`` should work together. """ engine = Engine(loaders=[ ('django.template.loaders.locmem.Loader', { 'child': '{{ var|default:"none" }}', }), ]) request = self.request_factory.get('/') ctx = RequestContext(request, {'var': 'parent'}) self.assertEqual(engine.from_string('{% include "child" %}').render(ctx), 'parent') self.assertEqual(engine.from_string('{% include "child" only %}').render(ctx), 'none') def test_stack_size(self): """Optimized RequestContext construction (#7116).""" request = self.request_factory.get('/') ctx = RequestContext(request, {}) # The stack contains 4 items: # [builtins, supplied context, context processor, empty dict] self.assertEqual(len(ctx.dicts), 4) def test_context_comparable(self): # Create an engine without any context processors. test_data = {'x': 'y', 'v': 'z', 'd': {'o': object, 'a': 'b'}} # test comparing RequestContext to prevent problems if somebody # adds __eq__ in the future request = self.request_factory.get('/') self.assertEqual( RequestContext(request, dict_=test_data), RequestContext(request, dict_=test_data), ) def test_modify_context_and_render(self): template = Template('{{ foo }}') request = self.request_factory.get('/') context = RequestContext(request, {}) context['foo'] = 'foo' self.assertEqual(template.render(context), 'foo')
691a0e2363bca930f6edbe7303ff48de3ebc721272e6b08d209b8fd929990819
import logging from django.template import Engine, Variable, VariableDoesNotExist from django.test import SimpleTestCase class VariableResolveLoggingTests(SimpleTestCase): loglevel = logging.DEBUG def test_log_on_variable_does_not_exist_silent(self): class TestObject: class SilentDoesNotExist(Exception): silent_variable_failure = True @property def template_name(self): return "template_name" @property def template(self): return Engine().from_string('') @property def article(self): raise TestObject.SilentDoesNotExist("Attribute does not exist.") def __iter__(self): return (attr for attr in dir(TestObject) if attr[:2] != "__") def __getitem__(self, item): return self.__dict__[item] with self.assertLogs('django.template', self.loglevel) as cm: Variable('article').resolve(TestObject()) self.assertEqual(len(cm.records), 1) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), "Exception while resolving variable 'article' in template 'template_name'." ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] self.assertEqual(str(raised_exception), 'Attribute does not exist.') def test_log_on_variable_does_not_exist_not_silent(self): with self.assertLogs('django.template', self.loglevel) as cm: with self.assertRaises(VariableDoesNotExist): Variable('article.author').resolve({'article': {'section': 'News'}}) self.assertEqual(len(cm.records), 1) log_record = cm.records[0] self.assertEqual( log_record.getMessage(), "Exception while resolving variable 'author' in template 'unknown'." ) self.assertIsNotNone(log_record.exc_info) raised_exception = log_record.exc_info[1] self.assertEqual( str(raised_exception), "Failed lookup for key [author] in {'section': 'News'}" ) def test_no_log_when_variable_exists(self): with self.assertRaisesMessage(AssertionError, 'no logs'): with self.assertLogs('django.template', self.loglevel): Variable('article.section').resolve({'article': {'section': 'News'}})
555f5565add571006cd9106dbabca5344e9552879df5912e07b1067afe6cde42
import functools from django.template import Library from django.template.base import Node from django.test import SimpleTestCase class FilterRegistrationTests(SimpleTestCase): def setUp(self): self.library = Library() def test_filter(self): @self.library.filter def func(): return '' self.assertEqual(self.library.filters['func'], func) def test_filter_parens(self): @self.library.filter() def func(): return '' self.assertEqual(self.library.filters['func'], func) def test_filter_name_arg(self): @self.library.filter('name') def func(): return '' self.assertEqual(self.library.filters['name'], func) def test_filter_name_kwarg(self): @self.library.filter(name='name') def func(): return '' self.assertEqual(self.library.filters['name'], func) def test_filter_call(self): def func(): return '' self.library.filter('name', func) self.assertEqual(self.library.filters['name'], func) def test_filter_invalid(self): msg = "Unsupported arguments to Library.filter: (None, '')" with self.assertRaisesMessage(ValueError, msg): self.library.filter(None, '') class InclusionTagRegistrationTests(SimpleTestCase): def setUp(self): self.library = Library() def test_inclusion_tag(self): @self.library.inclusion_tag('template.html') def func(): return '' self.assertIn('func', self.library.tags) def test_inclusion_tag_name(self): @self.library.inclusion_tag('template.html', name='name') def func(): return '' self.assertIn('name', self.library.tags) def test_inclusion_tag_wrapped(self): @self.library.inclusion_tag('template.html') @functools.lru_cache(maxsize=32) def func(): return '' func_wrapped = self.library.tags['func'].__wrapped__ self.assertIs(func_wrapped, func) self.assertTrue(hasattr(func_wrapped, 'cache_info')) class SimpleTagRegistrationTests(SimpleTestCase): def setUp(self): self.library = Library() def test_simple_tag(self): @self.library.simple_tag def func(): return '' self.assertIn('func', self.library.tags) def test_simple_tag_parens(self): @self.library.simple_tag() def func(): return '' self.assertIn('func', self.library.tags) def test_simple_tag_name_kwarg(self): @self.library.simple_tag(name='name') def func(): return '' self.assertIn('name', self.library.tags) def test_simple_tag_invalid(self): msg = "Invalid arguments provided to simple_tag" with self.assertRaisesMessage(ValueError, msg): self.library.simple_tag('invalid') def test_simple_tag_wrapped(self): @self.library.simple_tag @functools.lru_cache(maxsize=32) def func(): return '' func_wrapped = self.library.tags['func'].__wrapped__ self.assertIs(func_wrapped, func) self.assertTrue(hasattr(func_wrapped, 'cache_info')) class TagRegistrationTests(SimpleTestCase): def setUp(self): self.library = Library() def test_tag(self): @self.library.tag def func(parser, token): return Node() self.assertEqual(self.library.tags['func'], func) def test_tag_parens(self): @self.library.tag() def func(parser, token): return Node() self.assertEqual(self.library.tags['func'], func) def test_tag_name_arg(self): @self.library.tag('name') def func(parser, token): return Node() self.assertEqual(self.library.tags['name'], func) def test_tag_name_kwarg(self): @self.library.tag(name='name') def func(parser, token): return Node() self.assertEqual(self.library.tags['name'], func) def test_tag_call(self): def func(parser, token): return Node() self.library.tag('name', func) self.assertEqual(self.library.tags['name'], func) def test_tag_invalid(self): msg = "Unsupported arguments to Library.tag: (None, '')" with self.assertRaisesMessage(ValueError, msg): self.library.tag(None, '')
c516a83c7f3bd84322f6d84e10012ae83636f1ced9afcc4a0fc9dc584037ac58
import os.path import sys import tempfile import unittest from contextlib import contextmanager from django.template import TemplateDoesNotExist from django.template.engine import Engine from django.test import SimpleTestCase, override_settings from django.utils.functional import lazystr from .utils import TEMPLATE_DIR class CachedLoaderTests(SimpleTestCase): def setUp(self): self.engine = Engine( dirs=[TEMPLATE_DIR], loaders=[ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', ]), ], ) def test_get_template(self): template = self.engine.get_template('index.html') self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) self.assertEqual(template.origin.template_name, 'index.html') self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0]) cache = self.engine.template_loaders[0].get_template_cache self.assertEqual(cache['index.html'], template) # Run a second time from cache template = self.engine.get_template('index.html') self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) self.assertEqual(template.origin.template_name, 'index.html') self.assertEqual(template.origin.loader, self.engine.template_loaders[0].loaders[0]) def test_get_template_missing_debug_off(self): """ With template debugging disabled, the raw TemplateDoesNotExist class should be cached when a template is missing. See ticket #26306 and docstrings in the cached loader for details. """ self.engine.debug = False with self.assertRaises(TemplateDoesNotExist): self.engine.get_template('prod-template-missing.html') e = self.engine.template_loaders[0].get_template_cache['prod-template-missing.html'] self.assertEqual(e, TemplateDoesNotExist) def test_get_template_missing_debug_on(self): """ With template debugging enabled, a TemplateDoesNotExist instance should be cached when a template is missing. """ self.engine.debug = True with self.assertRaises(TemplateDoesNotExist): self.engine.get_template('debug-template-missing.html') e = self.engine.template_loaders[0].get_template_cache['debug-template-missing.html'] self.assertIsInstance(e, TemplateDoesNotExist) self.assertEqual(e.args[0], 'debug-template-missing.html') def test_cached_exception_no_traceback(self): """ When a TemplateDoesNotExist instance is cached, the cached instance should not contain the __traceback__, __context__, or __cause__ attributes that Python sets when raising exceptions. """ self.engine.debug = True with self.assertRaises(TemplateDoesNotExist): self.engine.get_template('no-traceback-in-cache.html') e = self.engine.template_loaders[0].get_template_cache['no-traceback-in-cache.html'] error_msg = "Cached TemplateDoesNotExist must not have been thrown." self.assertIsNone(e.__traceback__, error_msg) self.assertIsNone(e.__context__, error_msg) self.assertIsNone(e.__cause__, error_msg) def test_template_name_leading_dash_caching(self): """ #26536 -- A leading dash in a template name shouldn't be stripped from its cache key. """ self.assertEqual(self.engine.template_loaders[0].cache_key('-template.html', []), '-template.html') def test_template_name_lazy_string(self): """ #26603 -- A template name specified as a lazy string should be forced to text before computing its cache key. """ self.assertEqual(self.engine.template_loaders[0].cache_key(lazystr('template.html'), []), 'template.html') class FileSystemLoaderTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine(dirs=[TEMPLATE_DIR], loaders=['django.template.loaders.filesystem.Loader']) super().setUpClass() @contextmanager def set_dirs(self, dirs): original_dirs = self.engine.dirs self.engine.dirs = dirs try: yield finally: self.engine.dirs = original_dirs @contextmanager def source_checker(self, dirs): loader = self.engine.template_loaders[0] def check_sources(path, expected_sources): expected_sources = [os.path.abspath(s) for s in expected_sources] self.assertEqual( [origin.name for origin in loader.get_template_sources(path)], expected_sources, ) with self.set_dirs(dirs): yield check_sources def test_get_template(self): template = self.engine.get_template('index.html') self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) self.assertEqual(template.origin.template_name, 'index.html') self.assertEqual(template.origin.loader, self.engine.template_loaders[0]) self.assertEqual(template.origin.loader_name, 'django.template.loaders.filesystem.Loader') def test_loaders_dirs(self): engine = Engine(loaders=[('django.template.loaders.filesystem.Loader', [TEMPLATE_DIR])]) template = engine.get_template('index.html') self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) def test_loaders_dirs_empty(self): """An empty dirs list in loaders overrides top level dirs.""" engine = Engine(dirs=[TEMPLATE_DIR], loaders=[('django.template.loaders.filesystem.Loader', [])]) with self.assertRaises(TemplateDoesNotExist): engine.get_template('index.html') def test_directory_security(self): with self.source_checker(['/dir1', '/dir2']) as check_sources: check_sources('index.html', ['/dir1/index.html', '/dir2/index.html']) check_sources('/etc/passwd', []) check_sources('etc/passwd', ['/dir1/etc/passwd', '/dir2/etc/passwd']) check_sources('../etc/passwd', []) check_sources('../../../etc/passwd', []) check_sources('/dir1/index.html', ['/dir1/index.html']) check_sources('../dir2/index.html', ['/dir2/index.html']) check_sources('/dir1blah', []) check_sources('../dir1blah', []) def test_unicode_template_name(self): with self.source_checker(['/dir1', '/dir2']) as check_sources: check_sources('Ångström', ['/dir1/Ångström', '/dir2/Ångström']) def test_bytestring(self): loader = self.engine.template_loaders[0] msg = "Can't mix strings and bytes in path components" with self.assertRaisesMessage(TypeError, msg): list(loader.get_template_sources(b'\xc3\x85ngstr\xc3\xb6m')) def test_unicode_dir_name(self): with self.source_checker(['/Straße']) as check_sources: check_sources('Ångström', ['/Straße/Ångström']) @unittest.skipUnless( os.path.normcase('/TEST') == os.path.normpath('/test'), "This test only runs on case-sensitive file systems.", ) def test_case_sensitivity(self): with self.source_checker(['/dir1', '/DIR2']) as check_sources: check_sources('index.html', ['/dir1/index.html', '/DIR2/index.html']) check_sources('/DIR1/index.HTML', ['/DIR1/index.HTML']) def test_file_does_not_exist(self): with self.assertRaises(TemplateDoesNotExist): self.engine.get_template('doesnotexist.html') @unittest.skipIf( sys.platform == 'win32', "Python on Windows doesn't have working os.chmod().", ) def test_permissions_error(self): with tempfile.NamedTemporaryFile() as tmpfile: tmpdir = os.path.dirname(tmpfile.name) tmppath = os.path.join(tmpdir, tmpfile.name) os.chmod(tmppath, 0o0222) with self.set_dirs([tmpdir]): with self.assertRaisesMessage(PermissionError, 'Permission denied'): self.engine.get_template(tmpfile.name) def test_notafile_error(self): # Windows raises PermissionError when trying to open a directory. with self.assertRaises(PermissionError if sys.platform.startswith('win') else IsADirectoryError): self.engine.get_template('first') class AppDirectoriesLoaderTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine( loaders=['django.template.loaders.app_directories.Loader'], ) super().setUpClass() @override_settings(INSTALLED_APPS=['template_tests']) def test_get_template(self): template = self.engine.get_template('index.html') self.assertEqual(template.origin.name, os.path.join(TEMPLATE_DIR, 'index.html')) self.assertEqual(template.origin.template_name, 'index.html') self.assertEqual(template.origin.loader, self.engine.template_loaders[0]) @override_settings(INSTALLED_APPS=[]) def test_not_installed(self): with self.assertRaises(TemplateDoesNotExist): self.engine.get_template('index.html') class LocmemLoaderTests(SimpleTestCase): @classmethod def setUpClass(cls): cls.engine = Engine( loaders=[('django.template.loaders.locmem.Loader', { 'index.html': 'index', })], ) super().setUpClass() def test_get_template(self): template = self.engine.get_template('index.html') self.assertEqual(template.origin.name, 'index.html') self.assertEqual(template.origin.template_name, 'index.html') self.assertEqual(template.origin.loader, self.engine.template_loaders[0])
da37c24e16cdd8b6a5b8f6bfa8928723b2f997ce6461b5183a88fd7705eacb0e
from django.template import Context, Template, Variable, VariableDoesNotExist from django.test import SimpleTestCase from django.utils.translation import gettext_lazy class TemplateTests(SimpleTestCase): def test_lazy_template_string(self): template_string = gettext_lazy('lazy string') self.assertEqual(Template(template_string).render(Context()), template_string) class VariableDoesNotExistTests(SimpleTestCase): def test_str(self): exc = VariableDoesNotExist(msg='Failed lookup in %r', params=({'foo': 'bar'},)) self.assertEqual(str(exc), "Failed lookup in {'foo': 'bar'}") class VariableTests(SimpleTestCase): def test_integer_literals(self): self.assertEqual(Variable('999999999999999999999999999').literal, 999999999999999999999999999) def test_nonliterals(self): """Variable names that aren't resolved as literals.""" var_names = [] for var in ('inf', 'infinity', 'iNFiniTy', 'nan'): var_names.extend((var, '-' + var, '+' + var)) for var in var_names: with self.subTest(var=var): self.assertIsNone(Variable(var).literal)
ba6e6cb28d0e1655d9104dfa42140247df9a86905f245433e9cb96f35ca2e132
import pickle import time from datetime import datetime from django.template import engines from django.template.response import ( ContentNotRenderedError, SimpleTemplateResponse, TemplateResponse, ) from django.test import ( RequestFactory, SimpleTestCase, modify_settings, override_settings, ) from django.test.utils import require_jinja2 from django.utils.deprecation import MiddlewareMixin from .utils import TEMPLATE_DIR def test_processor(request): return {'processors': 'yes'} test_processor_name = 'template_tests.test_response.test_processor' # A test middleware that installs a temporary URLConf class CustomURLConfMiddleware(MiddlewareMixin): def process_request(self, request): request.urlconf = 'template_tests.alternate_urls' class SimpleTemplateResponseTest(SimpleTestCase): def _response(self, template='foo', *args, **kwargs): template = engines['django'].from_string(template) return SimpleTemplateResponse(template, *args, **kwargs) def test_template_resolving(self): response = SimpleTemplateResponse('first/test.html') response.render() self.assertEqual(response.content, b'First template\n') templates = ['foo.html', 'second/test.html', 'first/test.html'] response = SimpleTemplateResponse(templates) response.render() self.assertEqual(response.content, b'Second template\n') response = self._response() response.render() self.assertEqual(response.content, b'foo') def test_explicit_baking(self): # explicit baking response = self._response() self.assertFalse(response.is_rendered) response.render() self.assertTrue(response.is_rendered) def test_render(self): # response is not re-rendered without the render call response = self._response().render() self.assertEqual(response.content, b'foo') # rebaking doesn't change the rendered content template = engines['django'].from_string('bar{{ baz }}') response.template_name = template response.render() self.assertEqual(response.content, b'foo') # but rendered content can be overridden by manually # setting content response.content = 'bar' self.assertEqual(response.content, b'bar') def test_iteration_unrendered(self): # unrendered response raises an exception on iteration response = self._response() self.assertFalse(response.is_rendered) def iteration(): list(response) msg = 'The response content must be rendered before it can be iterated over.' with self.assertRaisesMessage(ContentNotRenderedError, msg): iteration() self.assertFalse(response.is_rendered) def test_iteration_rendered(self): # iteration works for rendered responses response = self._response().render() self.assertEqual(list(response), [b'foo']) def test_content_access_unrendered(self): # unrendered response raises an exception when content is accessed response = self._response() self.assertFalse(response.is_rendered) with self.assertRaises(ContentNotRenderedError): response.content self.assertFalse(response.is_rendered) def test_content_access_rendered(self): # rendered response content can be accessed response = self._response().render() self.assertEqual(response.content, b'foo') def test_set_content(self): # content can be overridden response = self._response() self.assertFalse(response.is_rendered) response.content = 'spam' self.assertTrue(response.is_rendered) self.assertEqual(response.content, b'spam') response.content = 'baz' self.assertEqual(response.content, b'baz') def test_dict_context(self): response = self._response('{{ foo }}{{ processors }}', {'foo': 'bar'}) self.assertEqual(response.context_data, {'foo': 'bar'}) response.render() self.assertEqual(response.content, b'bar') def test_kwargs(self): response = self._response(content_type='application/json', status=504, charset='ascii') self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 504) self.assertEqual(response.charset, 'ascii') def test_args(self): response = SimpleTemplateResponse('', {}, 'application/json', 504) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 504) @require_jinja2 def test_using(self): response = SimpleTemplateResponse('template_tests/using.html').render() self.assertEqual(response.content, b'DTL\n') response = SimpleTemplateResponse('template_tests/using.html', using='django').render() self.assertEqual(response.content, b'DTL\n') response = SimpleTemplateResponse('template_tests/using.html', using='jinja2').render() self.assertEqual(response.content, b'Jinja2\n') def test_post_callbacks(self): "Rendering a template response triggers the post-render callbacks" 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) # When the content is rendered, all the callbacks are invoked, too. response.render() self.assertEqual(response.content, b'First template\n') self.assertEqual(post, ['post1', 'post2']) def test_pickling(self): # Create a template response. The context is # known to be unpicklable (e.g., a function). response = SimpleTemplateResponse('first/test.html', { 'value': 123, 'fn': datetime.now, }) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) # But if we render the response, we can pickle it. response.render() pickled_response = pickle.dumps(response) unpickled_response = pickle.loads(pickled_response) self.assertEqual(unpickled_response.content, response.content) self.assertEqual(unpickled_response['content-type'], response['content-type']) self.assertEqual(unpickled_response.status_code, response.status_code) # ...and the unpickled response doesn't have the # template-related attributes, so it can't be re-rendered template_attrs = ('template_name', 'context_data', '_post_render_callbacks') for attr in template_attrs: self.assertFalse(hasattr(unpickled_response, attr)) # ...and requesting any of those attributes raises an exception for attr in template_attrs: with self.assertRaises(AttributeError): getattr(unpickled_response, attr) def test_repickling(self): response = SimpleTemplateResponse('first/test.html', { 'value': 123, 'fn': datetime.now, }) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) response.render() pickled_response = pickle.dumps(response) unpickled_response = pickle.loads(pickled_response) pickle.dumps(unpickled_response) def test_pickling_cookie(self): response = SimpleTemplateResponse('first/test.html', { 'value': 123, 'fn': datetime.now, }) response.cookies['key'] = 'value' response.render() pickled_response = pickle.dumps(response, pickle.HIGHEST_PROTOCOL) unpickled_response = pickle.loads(pickled_response) self.assertEqual(unpickled_response.cookies['key'].value, 'value') @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'OPTIONS': { 'context_processors': [test_processor_name], }, }]) class TemplateResponseTest(SimpleTestCase): factory = RequestFactory() def _response(self, template='foo', *args, **kwargs): self._request = self.factory.get('/') template = engines['django'].from_string(template) return TemplateResponse(self._request, template, *args, **kwargs) def test_render(self): response = self._response('{{ foo }}{{ processors }}').render() self.assertEqual(response.content, b'yes') def test_render_with_requestcontext(self): response = self._response('{{ foo }}{{ processors }}', {'foo': 'bar'}).render() self.assertEqual(response.content, b'baryes') def test_context_processor_priority(self): # context processors should be overridden by passed-in context response = self._response('{{ foo }}{{ processors }}', {'processors': 'no'}).render() self.assertEqual(response.content, b'no') def test_kwargs(self): response = self._response(content_type='application/json', status=504) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 504) def test_args(self): response = TemplateResponse(self.factory.get('/'), '', {}, 'application/json', 504) self.assertEqual(response['content-type'], 'application/json') self.assertEqual(response.status_code, 504) @require_jinja2 def test_using(self): request = self.factory.get('/') response = TemplateResponse(request, 'template_tests/using.html').render() self.assertEqual(response.content, b'DTL\n') response = TemplateResponse(request, 'template_tests/using.html', using='django').render() self.assertEqual(response.content, b'DTL\n') response = TemplateResponse(request, 'template_tests/using.html', using='jinja2').render() self.assertEqual(response.content, b'Jinja2\n') def test_pickling(self): # Create a template response. The context is # known to be unpicklable (e.g., a function). response = TemplateResponse( self.factory.get('/'), 'first/test.html', { 'value': 123, 'fn': datetime.now, } ) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) # But if we render the response, we can pickle it. response.render() pickled_response = pickle.dumps(response) unpickled_response = pickle.loads(pickled_response) self.assertEqual(unpickled_response.content, response.content) self.assertEqual(unpickled_response['content-type'], response['content-type']) self.assertEqual(unpickled_response.status_code, response.status_code) # ...and the unpickled response doesn't have the # template-related attributes, so it can't be re-rendered template_attrs = ( 'template_name', 'context_data', '_post_render_callbacks', '_request', ) for attr in template_attrs: self.assertFalse(hasattr(unpickled_response, attr)) # ...and requesting any of those attributes raises an exception for attr in template_attrs: with self.assertRaises(AttributeError): getattr(unpickled_response, attr) def test_repickling(self): response = SimpleTemplateResponse('first/test.html', { 'value': 123, 'fn': datetime.now, }) with self.assertRaises(ContentNotRenderedError): pickle.dumps(response) response.render() pickled_response = pickle.dumps(response) unpickled_response = pickle.loads(pickled_response) pickle.dumps(unpickled_response) @modify_settings(MIDDLEWARE={'append': ['template_tests.test_response.CustomURLConfMiddleware']}) @override_settings(ROOT_URLCONF='template_tests.urls') class CustomURLConfTest(SimpleTestCase): def test_custom_urlconf(self): response = self.client.get('/template_response_view/') self.assertContains(response, 'This is where you can find the snark: /snark/') @modify_settings( MIDDLEWARE={ 'append': [ 'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', ], }, ) @override_settings(CACHE_MIDDLEWARE_SECONDS=2.0, ROOT_URLCONF='template_tests.alternate_urls') class CacheMiddlewareTest(SimpleTestCase): def test_middleware_caching(self): response = self.client.get('/template_response_view/') self.assertEqual(response.status_code, 200) time.sleep(1.0) response2 = self.client.get('/template_response_view/') self.assertEqual(response2.status_code, 200) self.assertEqual(response.content, response2.content) time.sleep(2.0) # Let the cache expire and test again response2 = self.client.get('/template_response_view/') self.assertEqual(response2.status_code, 200) self.assertNotEqual(response.content, response2.content)
5ddaf8c90857262c0946e7166a654808c0df4ea6ceca027db31d477915f68d5b
from django.urls import path from . import views urlpatterns = [ # View returning a template response path('template_response_view/', views.template_response_view), # A view that can be hard to find... path('snark/', views.snark, name='snark'), ]
7f6439a48f8c7961012d279fd4e6f72041ae8c0b90b04114a321d4f7d6ecfba9
from django.urls import include, path, re_path from . import views ns_patterns = [ # Test urls for testing reverse lookups path('', views.index, name='index'), re_path(r'^client/([0-9,]+)/$', views.client, name='client'), re_path(r'^client/(?P<id>[0-9]+)/(?P<action>[^/]+)/$', views.client_action, name='client_action'), re_path(r'^client/(?P<client_id>[0-9]+)/(?P<action>[^/]+)/$', views.client_action, name='client_action'), re_path(r'^named-client/([0-9]+)/$', views.client2, name="named.client"), ] urlpatterns = ns_patterns + [ # Unicode strings are permitted everywhere. re_path(r'^Юникод/(\w+)/$', views.client2, name="метка_оператора"), re_path(r'^Юникод/(?P<tag>\S+)/$', views.client2, name="метка_оператора_2"), # Test urls for namespaces and current_app path('ns1/', include((ns_patterns, 'app'), 'ns1')), path('ns2/', include((ns_patterns, 'app'))), ]
5f2c400493bdeeaf6a316066038f082199f0b3a6fa8f481edb154edafe8e923a
import os from django.core.exceptions import ImproperlyConfigured from django.template import Context from django.template.engine import Engine from django.test import SimpleTestCase, override_settings from .utils import ROOT, TEMPLATE_DIR OTHER_DIR = os.path.join(ROOT, 'other_templates') class RenderToStringTest(SimpleTestCase): def setUp(self): self.engine = Engine(dirs=[TEMPLATE_DIR]) def test_basic_context(self): self.assertEqual( self.engine.render_to_string('test_context.html', {'obj': 'test'}), 'obj:test\n', ) def test_autoescape_off(self): engine = Engine(dirs=[TEMPLATE_DIR], autoescape=False) self.assertEqual( engine.render_to_string('test_context.html', {'obj': '<script>'}), 'obj:<script>\n', ) class GetDefaultTests(SimpleTestCase): @override_settings(TEMPLATES=[]) def test_no_engines_configured(self): msg = 'No DjangoTemplates backend is configured.' with self.assertRaisesMessage(ImproperlyConfigured, msg): Engine.get_default() @override_settings(TEMPLATES=[{ 'NAME': 'default', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': {'file_charset': 'abc'}, }]) def test_single_engine_configured(self): self.assertEqual(Engine.get_default().file_charset, 'abc') @override_settings(TEMPLATES=[{ 'NAME': 'default', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': {'file_charset': 'abc'}, }, { 'NAME': 'other', 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': {'file_charset': 'def'}, }]) def test_multiple_engines_configured(self): self.assertEqual(Engine.get_default().file_charset, 'abc') class LoaderTests(SimpleTestCase): def test_origin(self): engine = Engine(dirs=[TEMPLATE_DIR], debug=True) template = engine.get_template('index.html') self.assertEqual(template.origin.template_name, 'index.html') def test_loader_priority(self): """ #21460 -- The order of template loader works. """ loaders = [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') def test_cached_loader_priority(self): """ The order of template loader works. Refs #21460. """ loaders = [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]), ] engine = Engine(dirs=[OTHER_DIR, TEMPLATE_DIR], loaders=loaders) template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n') template = engine.get_template('priority/foo.html') self.assertEqual(template.render(Context()), 'priority\n')
d9cdbfa0720f8445e76867d775f3d458f36e1949267b80c78cfeffd033728b0e
import datetime from unittest import skipIf, skipUnless from django.db import connection from django.db.models import Index from django.db.models.deletion import CASCADE from django.db.models.fields.related import ForeignKey from django.db.models.query_utils import Q from django.test import ( TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import override_settings from django.utils import timezone from .models import ( Article, ArticleTranslation, IndexedArticle2, IndexTogetherSingleList, ) class SchemaIndexesTests(TestCase): """ Test index handling by the db.backends.schema infrastructure. """ def test_index_name_hash(self): """ Index names should be deterministic. """ editor = connection.schema_editor() index_name = editor._create_index_name( table_name=Article._meta.db_table, column_names=("c1",), suffix="123", ) self.assertEqual(index_name, "indexes_article_c1_a52bd80b123") def test_index_name(self): """ Index names on the built-in database backends:: * Are truncated as needed. * Include all the column names. * Include a deterministic hash. """ long_name = 'l%sng' % ('o' * 100) editor = connection.schema_editor() index_name = editor._create_index_name( table_name=Article._meta.db_table, column_names=('c1', 'c2', long_name), suffix='ix', ) expected = { 'mysql': 'indexes_article_c1_c2_looooooooooooooooooo_255179b2ix', 'oracle': 'indexes_a_c1_c2_loo_255179b2ix', 'postgresql': 'indexes_article_c1_c2_loooooooooooooooooo_255179b2ix', 'sqlite': 'indexes_article_c1_c2_l%sng_255179b2ix' % ('o' * 100), } if connection.vendor not in expected: self.skipTest('This test is only supported on the built-in database backends.') self.assertEqual(index_name, expected[connection.vendor]) def test_index_together(self): editor = connection.schema_editor() index_sql = [str(statement) for statement in editor._model_indexes_sql(Article)] self.assertEqual(len(index_sql), 1) # Ensure the index name is properly quoted self.assertIn( connection.ops.quote_name( editor._create_index_name(Article._meta.db_table, ['headline', 'pub_date'], suffix='_idx') ), index_sql[0] ) def test_index_together_single_list(self): # Test for using index_together with a single list (#22172) index_sql = connection.schema_editor()._model_indexes_sql(IndexTogetherSingleList) self.assertEqual(len(index_sql), 1) @skipIf(connection.vendor == 'postgresql', 'opclasses are PostgreSQL only') class SchemaIndexesNotPostgreSQLTests(TransactionTestCase): available_apps = ['indexes'] def test_create_index_ignores_opclasses(self): index = Index( name='test_ops_class', fields=['headline'], opclasses=['varchar_pattern_ops'], ) with connection.schema_editor() as editor: # This would error if opclasses weren't ignored. editor.add_index(IndexedArticle2, index) # The `condition` parameter is ignored by databases that don't support partial # indexes. @skipIfDBFeature('supports_partial_indexes') class PartialIndexConditionIgnoredTests(TransactionTestCase): available_apps = ['indexes'] def test_condition_ignored(self): index = Index( name='test_condition_ignored', fields=['published'], condition=Q(published=True), ) with connection.schema_editor() as editor: # This would error if condition weren't ignored. editor.add_index(Article, index) self.assertNotIn( 'WHERE %s.%s' % (editor.quote_name(Article._meta.db_table), 'published'), str(index.create_sql(Article, editor)) ) @skipUnless(connection.vendor == 'postgresql', 'PostgreSQL tests') class SchemaIndexesPostgreSQLTests(TransactionTestCase): available_apps = ['indexes'] get_opclass_query = ''' SELECT opcname, c.relname FROM pg_opclass AS oc JOIN pg_index as i on oc.oid = ANY(i.indclass) JOIN pg_class as c on c.oid = i.indexrelid WHERE c.relname = '%s' ''' def test_text_indexes(self): """Test creation of PostgreSQL-specific text indexes (#12234)""" from .models import IndexedArticle index_sql = [str(statement) for statement in connection.schema_editor()._model_indexes_sql(IndexedArticle)] self.assertEqual(len(index_sql), 5) self.assertIn('("headline" varchar_pattern_ops)', index_sql[1]) self.assertIn('("body" text_pattern_ops)', index_sql[3]) # unique=True and db_index=True should only create the varchar-specific # index (#19441). self.assertIn('("slug" varchar_pattern_ops)', index_sql[4]) def test_virtual_relation_indexes(self): """Test indexes are not created for related objects""" index_sql = connection.schema_editor()._model_indexes_sql(Article) self.assertEqual(len(index_sql), 1) def test_ops_class(self): index = Index( name='test_ops_class', fields=['headline'], opclasses=['varchar_pattern_ops'], ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % 'test_ops_class') self.assertEqual(cursor.fetchall(), [('varchar_pattern_ops', 'test_ops_class')]) def test_ops_class_multiple_columns(self): index = Index( name='test_ops_class_multiple', fields=['headline', 'body'], opclasses=['varchar_pattern_ops', 'text_pattern_ops'], ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % 'test_ops_class_multiple') expected_ops_classes = ( ('varchar_pattern_ops', 'test_ops_class_multiple'), ('text_pattern_ops', 'test_ops_class_multiple'), ) self.assertCountEqual(cursor.fetchall(), expected_ops_classes) def test_ops_class_partial(self): index = Index( name='test_ops_class_partial', fields=['body'], opclasses=['text_pattern_ops'], condition=Q(headline__contains='China'), ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % 'test_ops_class_partial') self.assertCountEqual(cursor.fetchall(), [('text_pattern_ops', 'test_ops_class_partial')]) def test_ops_class_partial_tablespace(self): indexname = 'test_ops_class_tblspace' index = Index( name=indexname, fields=['body'], opclasses=['text_pattern_ops'], condition=Q(headline__contains='China'), db_tablespace='pg_default', ) with connection.schema_editor() as editor: editor.add_index(IndexedArticle2, index) self.assertIn('TABLESPACE "pg_default" ', str(index.create_sql(IndexedArticle2, editor))) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query % indexname) self.assertCountEqual(cursor.fetchall(), [('text_pattern_ops', indexname)]) @skipUnless(connection.vendor == 'mysql', 'MySQL tests') class SchemaIndexesMySQLTests(TransactionTestCase): available_apps = ['indexes'] def test_no_index_for_foreignkey(self): """ MySQL on InnoDB already creates indexes automatically for foreign keys. (#14180). An index should be created if db_constraint=False (#26171). """ storage = connection.introspection.get_storage_engine( connection.cursor(), ArticleTranslation._meta.db_table ) if storage != "InnoDB": self.skip("This test only applies to the InnoDB storage engine") index_sql = [str(statement) for statement in connection.schema_editor()._model_indexes_sql(ArticleTranslation)] self.assertEqual(index_sql, [ 'CREATE INDEX `indexes_articletranslation_article_no_constraint_id_d6c0806b` ' 'ON `indexes_articletranslation` (`article_no_constraint_id`)' ]) # The index also shouldn't be created if the ForeignKey is added after # the model was created. field_created = False try: with connection.schema_editor() as editor: new_field = ForeignKey(Article, CASCADE) new_field.set_attributes_from_name('new_foreign_key') editor.add_field(ArticleTranslation, new_field) field_created = True # No deferred SQL. The FK constraint is included in the # statement to add the field. self.assertFalse(editor.deferred_sql) finally: if field_created: with connection.schema_editor() as editor: editor.remove_field(ArticleTranslation, new_field) @skipUnlessDBFeature('supports_partial_indexes') # SQLite doesn't support timezone-aware datetimes when USE_TZ is False. @override_settings(USE_TZ=True) class PartialIndexTests(TransactionTestCase): # Schema editor is used to create the index to test that it works. available_apps = ['indexes'] def test_partial_index(self): with connection.schema_editor() as editor: index = Index( name='recent_article_idx', fields=['pub_date'], condition=Q( pub_date__gt=datetime.datetime( year=2015, month=1, day=1, # PostgreSQL would otherwise complain about the lookup # being converted to a mutable function (by removing # the timezone in the cast) which is forbidden. tzinfo=timezone.get_current_timezone(), ), ) ) self.assertIn( 'WHERE %s.%s' % (editor.quote_name(Article._meta.db_table), editor.quote_name("pub_date")), str(index.create_sql(Article, schema_editor=editor)) ) editor.add_index(index=index, model=Article) self.assertIn(index.name, connection.introspection.get_constraints( cursor=connection.cursor(), table_name=Article._meta.db_table, )) editor.remove_index(index=index, model=Article) def test_integer_restriction_partial(self): with connection.schema_editor() as editor: index = Index( name='recent_article_idx', fields=['id'], condition=Q(pk__gt=1), ) self.assertIn( 'WHERE %s.%s' % (editor.quote_name(Article._meta.db_table), editor.quote_name('id')), str(index.create_sql(Article, schema_editor=editor)) ) editor.add_index(index=index, model=Article) self.assertIn(index.name, connection.introspection.get_constraints( cursor=connection.cursor(), table_name=Article._meta.db_table, )) editor.remove_index(index=index, model=Article) def test_boolean_restriction_partial(self): with connection.schema_editor() as editor: index = Index( name='published_index', fields=['published'], condition=Q(published=True), ) self.assertIn( 'WHERE %s.%s' % (editor.quote_name(Article._meta.db_table), editor.quote_name('published')), str(index.create_sql(Article, schema_editor=editor)) ) editor.add_index(index=index, model=Article) self.assertIn(index.name, connection.introspection.get_constraints( cursor=connection.cursor(), table_name=Article._meta.db_table, )) editor.remove_index(index=index, model=Article) @skipUnlessDBFeature('supports_functions_in_partial_indexes') def test_multiple_conditions(self): with connection.schema_editor() as editor: index = Index( name='recent_article_idx', fields=['pub_date', 'headline'], condition=( Q(pub_date__gt=datetime.datetime( year=2015, month=1, day=1, tzinfo=timezone.get_current_timezone(), )) & Q(headline__contains='China') ), ) sql = str(index.create_sql(Article, schema_editor=editor)) where = sql.find('WHERE') self.assertIn( 'WHERE (%s.%s' % (editor.quote_name(Article._meta.db_table), editor.quote_name("pub_date")), sql ) # Because each backend has different syntax for the operators, # check ONLY the occurrence of headline in the SQL. self.assertGreater(sql.rfind('headline'), where) editor.add_index(index=index, model=Article) self.assertIn(index.name, connection.introspection.get_constraints( cursor=connection.cursor(), table_name=Article._meta.db_table, )) editor.remove_index(index=index, model=Article) def test_is_null_condition(self): with connection.schema_editor() as editor: index = Index( name='recent_article_idx', fields=['pub_date'], condition=Q(pub_date__isnull=False), ) self.assertIn( 'WHERE %s.%s IS NOT NULL' % (editor.quote_name(Article._meta.db_table), editor.quote_name("pub_date")), str(index.create_sql(Article, schema_editor=editor)) ) editor.add_index(index=index, model=Article) self.assertIn(index.name, connection.introspection.get_constraints( cursor=connection.cursor(), table_name=Article._meta.db_table, )) editor.remove_index(index=index, model=Article)
b5733c4381fcdc7402fa454de8a47f946dc411efe124158ce2a5a7c816a1a80e
from django.db import connection, models class CurrentTranslation(models.ForeignObject): """ Creates virtual relation to the translation with model cache enabled. """ # Avoid validation requires_unique_target = False def __init__(self, to, on_delete, from_fields, to_fields, **kwargs): # Disable reverse relation kwargs['related_name'] = '+' # Set unique to enable model cache. kwargs['unique'] = True super().__init__(to, on_delete, from_fields, to_fields, **kwargs) class ArticleTranslation(models.Model): article = models.ForeignKey('indexes.Article', models.CASCADE) article_no_constraint = models.ForeignKey('indexes.Article', models.CASCADE, db_constraint=False, related_name='+') language = models.CharField(max_length=10, unique=True) content = models.TextField() class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() published = models.BooleanField(default=False) # Add virtual relation to the ArticleTranslation model. translation = CurrentTranslation(ArticleTranslation, models.CASCADE, ['id'], ['article']) class Meta: index_together = [ ["headline", "pub_date"], ] # Model for index_together being used only with single list class IndexTogetherSingleList(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() class Meta: index_together = ["headline", "pub_date"] # Indexing a TextField on Oracle or MySQL results in index creation error. if connection.vendor == 'postgresql': class IndexedArticle(models.Model): headline = models.CharField(max_length=100, db_index=True) body = models.TextField(db_index=True) slug = models.CharField(max_length=40, unique=True) class IndexedArticle2(models.Model): headline = models.CharField(max_length=100) body = models.TextField()
000a050cd41cc25ba44e956b999ad5b7ba5bd69003f6c0ab3864a9404c9aa029
""" Tests for Django's bundled context processors. """ from django.test import SimpleTestCase, TestCase, override_settings @override_settings( ROOT_URLCONF='context_processors.urls', TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.request', ], }, }], ) class RequestContextProcessorTests(SimpleTestCase): """ Tests for the ``django.template.context_processors.request`` processor. """ def test_request_attributes(self): """ The request object is available in the template and that its attributes can't be overridden by GET and POST parameters (#3828). """ url = '/request_attrs/' # We should have the request object in the template. response = self.client.get(url) self.assertContains(response, 'Have request') # Test is_secure. 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') # Test path. 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) @override_settings( DEBUG=True, INTERNAL_IPS=['127.0.0.1'], ROOT_URLCONF='context_processors.urls', TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', ], }, }], ) class DebugContextProcessorTests(TestCase): """ Tests for the ``django.template.context_processors.debug`` processor. """ databases = {'default', 'other'} def test_debug(self): url = '/debug/' # We should have the debug flag in the template. response = self.client.get(url) self.assertContains(response, 'Have debug') # And now we should not with override_settings(DEBUG=False): response = self.client.get(url) self.assertNotContains(response, 'Have debug') def test_sql_queries(self): """ Test whether sql_queries represents the actual amount of queries executed. (#23364) """ url = '/debug/' response = self.client.get(url) self.assertContains(response, 'First query list: 0') self.assertContains(response, 'Second query list: 1') # Check we have not actually memoized connection.queries self.assertContains(response, 'Third query list: 2') # Check queries for DB connection 'other' self.assertContains(response, 'Fourth query list: 3')
6aff79751ec14568fb80ef7ae9fa97ed3ab48c2f67dc95ac5830cca1ba85077a
from django.urls import path from . import views urlpatterns = [ path('request_attrs/', views.request_processor), path('debug/', views.debug_processor), ]
9e2b897cdb502f1281db3ecb375cf7ad4b68a07367c84125f40b7b355b0d6ada
from datetime import datetime from operator import attrgetter from django.db import IntegrityError from django.test import TestCase from .models import ( CustomMembership, Employee, Event, Friendship, Group, Ingredient, Invitation, Membership, Person, PersonSelfRefM2M, Recipe, RecipeIngredient, Relationship, ) class M2mThroughTests(TestCase): @classmethod def setUpTestData(cls): cls.bob = Person.objects.create(name='Bob') cls.jim = Person.objects.create(name='Jim') cls.jane = Person.objects.create(name='Jane') cls.rock = Group.objects.create(name='Rock') cls.roll = Group.objects.create(name='Roll') def test_retrieve_intermediate_items(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) expected = ['Jane', 'Jim'] self.assertQuerysetEqual( self.rock.members.all(), expected, attrgetter("name") ) def test_get_on_intermediate_model(self): Membership.objects.create(person=self.jane, group=self.rock) queryset = Membership.objects.get(person=self.jane, group=self.rock) self.assertEqual( repr(queryset), '<Membership: Jane is a member of Rock>' ) def test_filter_on_intermediate_model(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) queryset = Membership.objects.filter(group=self.rock) expected = [ '<Membership: Jim is a member of Rock>', '<Membership: Jane is a member of Rock>', ] self.assertQuerysetEqual( queryset, expected ) def test_add_on_m2m_with_intermediate_model(self): self.rock.members.add(self.bob, through_defaults={'invite_reason': 'He is good.'}) self.assertSequenceEqual(self.rock.members.all(), [self.bob]) self.assertEqual(self.rock.membership_set.get().invite_reason, 'He is good.') def test_add_on_m2m_with_intermediate_model_value_required(self): self.rock.nodefaultsnonulls.add(self.jim, through_defaults={'nodefaultnonull': 1}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) def test_add_on_m2m_with_intermediate_model_value_required_fails(self): with self.assertRaises(IntegrityError): self.rock.nodefaultsnonulls.add(self.jim) def test_create_on_m2m_with_intermediate_model(self): annie = self.rock.members.create(name='Annie', through_defaults={'invite_reason': 'She was just awesome.'}) self.assertSequenceEqual(self.rock.members.all(), [annie]) self.assertEqual(self.rock.membership_set.get().invite_reason, 'She was just awesome.') def test_create_on_m2m_with_intermediate_model_value_required(self): self.rock.nodefaultsnonulls.create(name='Test', through_defaults={'nodefaultnonull': 1}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) def test_create_on_m2m_with_intermediate_model_value_required_fails(self): with self.assertRaises(IntegrityError): self.rock.nodefaultsnonulls.create(name='Test') def test_get_or_create_on_m2m_with_intermediate_model_value_required(self): self.rock.nodefaultsnonulls.get_or_create(name='Test', through_defaults={'nodefaultnonull': 1}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) def test_get_or_create_on_m2m_with_intermediate_model_value_required_fails(self): with self.assertRaises(IntegrityError): self.rock.nodefaultsnonulls.get_or_create(name='Test') def test_update_or_create_on_m2m_with_intermediate_model_value_required(self): self.rock.nodefaultsnonulls.update_or_create(name='Test', through_defaults={'nodefaultnonull': 1}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) def test_update_or_create_on_m2m_with_intermediate_model_value_required_fails(self): with self.assertRaises(IntegrityError): self.rock.nodefaultsnonulls.update_or_create(name='Test') def test_remove_on_m2m_with_intermediate_model(self): Membership.objects.create(person=self.jim, group=self.rock) self.rock.members.remove(self.jim) self.assertSequenceEqual(self.rock.members.all(), []) def test_remove_on_m2m_with_intermediate_model_multiple(self): Membership.objects.create(person=self.jim, group=self.rock, invite_reason='1') Membership.objects.create(person=self.jim, group=self.rock, invite_reason='2') self.assertSequenceEqual(self.rock.members.all(), [self.jim, self.jim]) self.rock.members.remove(self.jim) self.assertSequenceEqual(self.rock.members.all(), []) def test_set_on_m2m_with_intermediate_model(self): members = list(Person.objects.filter(name__in=['Bob', 'Jim'])) self.rock.members.set(members) self.assertSequenceEqual(self.rock.members.all(), [self.bob, self.jim]) def test_set_on_m2m_with_intermediate_model_value_required(self): self.rock.nodefaultsnonulls.set([self.jim], through_defaults={'nodefaultnonull': 1}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) self.rock.nodefaultsnonulls.set([self.jim], through_defaults={'nodefaultnonull': 2}) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 1) self.rock.nodefaultsnonulls.set([self.jim], through_defaults={'nodefaultnonull': 2}, clear=True) self.assertEqual(self.rock.testnodefaultsornulls_set.get().nodefaultnonull, 2) def test_set_on_m2m_with_intermediate_model_value_required_fails(self): with self.assertRaises(IntegrityError): self.rock.nodefaultsnonulls.set([self.jim]) def test_clear_removes_all_the_m2m_relationships(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) self.rock.members.clear() self.assertQuerysetEqual( self.rock.members.all(), [] ) def test_retrieve_reverse_intermediate_items(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jim, group=self.roll) expected = ['Rock', 'Roll'] self.assertQuerysetEqual( self.jim.group_set.all(), expected, attrgetter("name") ) def test_add_on_reverse_m2m_with_intermediate_model(self): self.bob.group_set.add(self.rock) self.assertSequenceEqual(self.bob.group_set.all(), [self.rock]) def test_create_on_reverse_m2m_with_intermediate_model(self): funk = self.bob.group_set.create(name='Funk') self.assertSequenceEqual(self.bob.group_set.all(), [funk]) def test_remove_on_reverse_m2m_with_intermediate_model(self): Membership.objects.create(person=self.bob, group=self.rock) self.bob.group_set.remove(self.rock) self.assertSequenceEqual(self.bob.group_set.all(), []) def test_set_on_reverse_m2m_with_intermediate_model(self): members = list(Group.objects.filter(name__in=['Rock', 'Roll'])) self.bob.group_set.set(members) self.assertSequenceEqual(self.bob.group_set.all(), [self.rock, self.roll]) def test_clear_on_reverse_removes_all_the_m2m_relationships(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jim, group=self.roll) self.jim.group_set.clear() self.assertQuerysetEqual( self.jim.group_set.all(), [] ) def test_query_model_by_attribute_name_of_related_model(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) Membership.objects.create(person=self.bob, group=self.roll) Membership.objects.create(person=self.jim, group=self.roll) Membership.objects.create(person=self.jane, group=self.roll) self.assertQuerysetEqual( Group.objects.filter(members__name='Bob'), ['Roll'], attrgetter("name") ) def test_order_by_relational_field_through_model(self): CustomMembership.objects.create(person=self.jim, group=self.rock) CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jane, group=self.roll) CustomMembership.objects.create(person=self.jim, group=self.roll) self.assertSequenceEqual( self.rock.custom_members.order_by('custom_person_related_name'), [self.jim, self.bob] ) self.assertSequenceEqual( self.roll.custom_members.order_by('custom_person_related_name'), [self.jane, self.jim] ) def test_query_first_model_by_intermediate_model_attribute(self): Membership.objects.create( person=self.jane, group=self.roll, invite_reason="She was just awesome." ) Membership.objects.create( person=self.jim, group=self.roll, invite_reason="He is good." ) Membership.objects.create(person=self.bob, group=self.roll) qs = Group.objects.filter( membership__invite_reason="She was just awesome." ) self.assertQuerysetEqual( qs, ['Roll'], attrgetter("name") ) def test_query_second_model_by_intermediate_model_attribute(self): Membership.objects.create( person=self.jane, group=self.roll, invite_reason="She was just awesome." ) Membership.objects.create( person=self.jim, group=self.roll, invite_reason="He is good." ) Membership.objects.create(person=self.bob, group=self.roll) qs = Person.objects.filter( membership__invite_reason="She was just awesome." ) self.assertQuerysetEqual( qs, ['Jane'], attrgetter("name") ) def test_query_model_by_related_model_name(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock) Membership.objects.create(person=self.bob, group=self.roll) Membership.objects.create(person=self.jim, group=self.roll) Membership.objects.create(person=self.jane, group=self.roll) self.assertQuerysetEqual( Person.objects.filter(group__name="Rock"), ['Jane', 'Jim'], attrgetter("name") ) def test_query_model_by_custom_related_name(self): CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jim, group=self.rock) self.assertQuerysetEqual( Person.objects.filter(custom__name="Rock"), ['Bob', 'Jim'], attrgetter("name") ) def test_query_model_by_intermediate_can_return_non_unique_queryset(self): Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create( person=self.jane, group=self.rock, date_joined=datetime(2006, 1, 1) ) Membership.objects.create( person=self.bob, group=self.roll, date_joined=datetime(2004, 1, 1)) Membership.objects.create(person=self.jim, group=self.roll) Membership.objects.create( person=self.jane, group=self.roll, date_joined=datetime(2004, 1, 1)) qs = Person.objects.filter( membership__date_joined__gt=datetime(2004, 1, 1) ) self.assertQuerysetEqual( qs, ['Jane', 'Jim', 'Jim'], attrgetter("name") ) def test_custom_related_name_forward_empty_qs(self): self.assertQuerysetEqual( self.rock.custom_members.all(), [] ) def test_custom_related_name_reverse_empty_qs(self): self.assertQuerysetEqual( self.bob.custom.all(), [] ) def test_custom_related_name_forward_non_empty_qs(self): CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jim, group=self.rock) self.assertQuerysetEqual( self.rock.custom_members.all(), ['Bob', 'Jim'], attrgetter("name") ) def test_custom_related_name_reverse_non_empty_qs(self): CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.jim, group=self.rock) self.assertQuerysetEqual( self.bob.custom.all(), ['Rock'], attrgetter("name") ) def test_custom_related_name_doesnt_conflict_with_fky_related_name(self): CustomMembership.objects.create(person=self.bob, group=self.rock) self.assertQuerysetEqual( self.bob.custom_person_related_name.all(), ['<CustomMembership: Bob is a member of Rock>'] ) def test_through_fields(self): """ Relations with intermediary tables with multiple FKs to the M2M's ``to`` model are possible. """ event = Event.objects.create(title='Rockwhale 2014') Invitation.objects.create(event=event, inviter=self.bob, invitee=self.jim) Invitation.objects.create(event=event, inviter=self.bob, invitee=self.jane) self.assertQuerysetEqual( event.invitees.all(), ['Jane', 'Jim'], attrgetter('name') ) class M2mThroughReferentialTests(TestCase): def test_self_referential_empty_qs(self): tony = PersonSelfRefM2M.objects.create(name="Tony") self.assertQuerysetEqual( tony.friends.all(), [] ) def test_self_referential_non_symmetrical_first_side(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) self.assertQuerysetEqual( tony.friends.all(), ['Chris'], attrgetter("name") ) def test_self_referential_non_symmetrical_second_side(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) self.assertQuerysetEqual( chris.friends.all(), [] ) def test_self_referential_non_symmetrical_clear_first_side(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) chris.friends.clear() self.assertQuerysetEqual( chris.friends.all(), [] ) # Since this isn't a symmetrical relation, Tony's friend link still exists. self.assertQuerysetEqual( tony.friends.all(), ['Chris'], attrgetter("name") ) def test_self_referential_symmetrical(self): tony = PersonSelfRefM2M.objects.create(name="Tony") chris = PersonSelfRefM2M.objects.create(name="Chris") Friendship.objects.create( first=tony, second=chris, date_friended=datetime.now() ) Friendship.objects.create( first=chris, second=tony, date_friended=datetime.now() ) self.assertQuerysetEqual( tony.friends.all(), ['Chris'], attrgetter("name") ) self.assertQuerysetEqual( chris.friends.all(), ['Tony'], attrgetter("name") ) def test_through_fields_self_referential(self): john = Employee.objects.create(name='john') peter = Employee.objects.create(name='peter') mary = Employee.objects.create(name='mary') harry = Employee.objects.create(name='harry') Relationship.objects.create(source=john, target=peter, another=None) Relationship.objects.create(source=john, target=mary, another=None) Relationship.objects.create(source=john, target=harry, another=peter) self.assertQuerysetEqual( john.subordinates.all(), ['peter', 'mary', 'harry'], attrgetter('name') ) class M2mThroughToFieldsTests(TestCase): @classmethod def setUpTestData(cls): cls.pea = Ingredient.objects.create(iname='pea') cls.potato = Ingredient.objects.create(iname='potato') cls.tomato = Ingredient.objects.create(iname='tomato') cls.curry = Recipe.objects.create(rname='curry') RecipeIngredient.objects.create(recipe=cls.curry, ingredient=cls.potato) RecipeIngredient.objects.create(recipe=cls.curry, ingredient=cls.pea) RecipeIngredient.objects.create(recipe=cls.curry, ingredient=cls.tomato) def test_retrieval(self): # Forward retrieval self.assertSequenceEqual(self.curry.ingredients.all(), [self.pea, self.potato, self.tomato]) # Backward retrieval self.assertEqual(self.tomato.recipes.get(), self.curry) def test_choices(self): field = Recipe._meta.get_field('ingredients') self.assertEqual( [choice[0] for choice in field.get_choices(include_blank=False)], ['pea', 'potato', 'tomato'] )
98024282de79fd4196d41b730907be0554f8c0e64bdb1d533fa237e6e0c79451
from datetime import datetime from django.db import models # M2M described on one of the models class Person(models.Model): name = models.CharField(max_length=128) class Meta: ordering = ('name',) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') custom_members = models.ManyToManyField(Person, through='CustomMembership', related_name="custom") nodefaultsnonulls = models.ManyToManyField( Person, through='TestNoDefaultsOrNulls', related_name="testnodefaultsnonulls", ) class Meta: ordering = ('name',) def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, models.CASCADE) group = models.ForeignKey(Group, models.CASCADE) date_joined = models.DateTimeField(default=datetime.now) invite_reason = models.CharField(max_length=64, null=True) class Meta: ordering = ('date_joined', 'invite_reason', 'group') def __str__(self): return "%s is a member of %s" % (self.person.name, self.group.name) class CustomMembership(models.Model): person = models.ForeignKey( Person, models.CASCADE, db_column="custom_person_column", related_name="custom_person_related_name", ) group = models.ForeignKey(Group, models.CASCADE) weird_fk = models.ForeignKey(Membership, models.SET_NULL, null=True) date_joined = models.DateTimeField(default=datetime.now) class Meta: db_table = "test_table" ordering = ["date_joined"] def __str__(self): return "%s is a member of %s" % (self.person.name, self.group.name) class TestNoDefaultsOrNulls(models.Model): person = models.ForeignKey(Person, models.CASCADE) group = models.ForeignKey(Group, models.CASCADE) nodefaultnonull = models.IntegerField() class PersonSelfRefM2M(models.Model): name = models.CharField(max_length=5) friends = models.ManyToManyField('self', through="Friendship", symmetrical=False) def __str__(self): return self.name class Friendship(models.Model): first = models.ForeignKey(PersonSelfRefM2M, models.CASCADE, related_name="rel_from_set") second = models.ForeignKey(PersonSelfRefM2M, models.CASCADE, related_name="rel_to_set") date_friended = models.DateTimeField() # Custom through link fields class Event(models.Model): title = models.CharField(max_length=50) invitees = models.ManyToManyField( Person, through='Invitation', through_fields=('event', 'invitee'), related_name='events_invited', ) def __str__(self): return self.title class Invitation(models.Model): event = models.ForeignKey(Event, models.CASCADE, related_name='invitations') # field order is deliberately inverted. the target field is "invitee". inviter = models.ForeignKey(Person, models.CASCADE, related_name='invitations_sent') invitee = models.ForeignKey(Person, models.CASCADE, related_name='invitations') class Employee(models.Model): name = models.CharField(max_length=5) subordinates = models.ManyToManyField( 'self', through="Relationship", through_fields=('source', 'target'), symmetrical=False, ) class Meta: ordering = ('pk',) def __str__(self): return self.name class Relationship(models.Model): # field order is deliberately inverted. another = models.ForeignKey(Employee, models.SET_NULL, related_name="rel_another_set", null=True) target = models.ForeignKey(Employee, models.CASCADE, related_name="rel_target_set") source = models.ForeignKey(Employee, models.CASCADE, related_name="rel_source_set") class Ingredient(models.Model): iname = models.CharField(max_length=20, unique=True) class Meta: ordering = ('iname',) class Recipe(models.Model): rname = models.CharField(max_length=20, unique=True) ingredients = models.ManyToManyField( Ingredient, through='RecipeIngredient', related_name='recipes', ) class Meta: ordering = ('rname',) class RecipeIngredient(models.Model): ingredient = models.ForeignKey(Ingredient, models.CASCADE, to_field='iname') recipe = models.ForeignKey(Recipe, models.CASCADE, to_field='rname')
36f2ed193102cee7b0ad08859e2eec15fc9d071f00f3ceec2388be0c73e70403
import datetime import re from datetime import date from decimal import Decimal from django import forms from django.core.exceptions import ImproperlyConfigured, ValidationError from django.db import models from django.forms.models import ( BaseModelFormSet, _get_foreign_key, inlineformset_factory, modelformset_factory, ) from django.http import QueryDict from django.test import TestCase, skipUnlessDBFeature from .models import ( AlternateBook, Author, AuthorMeeting, BetterAuthor, Book, BookWithCustomPK, BookWithOptionalAltEditor, ClassyMexicanRestaurant, CustomPrimaryKey, Location, Membership, MexicanRestaurant, Owner, OwnerProfile, Person, Place, Player, Poem, Poet, Post, Price, Product, Repository, Restaurant, Revision, Team, ) class DeletionTests(TestCase): def test_deletion(self): PoetFormSet = modelformset_factory(Poet, fields="__all__", can_delete=True) poet = Poet.objects.create(name='test') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '0', 'form-0-id': str(poet.pk), 'form-0-name': 'test', 'form-0-DELETE': 'on', } formset = PoetFormSet(data, queryset=Poet.objects.all()) formset.save(commit=False) self.assertEqual(Poet.objects.count(), 1) formset.save() self.assertTrue(formset.is_valid()) self.assertEqual(Poet.objects.count(), 0) def test_add_form_deletion_when_invalid(self): """ Make sure that an add form that is filled out, but marked for deletion doesn't cause validation errors. """ PoetFormSet = modelformset_factory(Poet, fields="__all__", can_delete=True) poet = Poet.objects.create(name='test') # One existing untouched and two new unvalid forms data = { 'form-TOTAL_FORMS': '3', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '0', 'form-0-id': str(poet.id), 'form-0-name': 'test', 'form-1-id': '', 'form-1-name': 'x' * 1000, # Too long 'form-2-id': str(poet.id), # Violate unique constraint 'form-2-name': 'test2', } formset = PoetFormSet(data, queryset=Poet.objects.all()) # Make sure this form doesn't pass validation. self.assertIs(formset.is_valid(), False) self.assertEqual(Poet.objects.count(), 1) # Then make sure that it *does* pass validation and delete the object, # even though the data in new forms aren't actually valid. data['form-0-DELETE'] = 'on' data['form-1-DELETE'] = 'on' data['form-2-DELETE'] = 'on' formset = PoetFormSet(data, queryset=Poet.objects.all()) self.assertIs(formset.is_valid(), True) formset.save() self.assertEqual(Poet.objects.count(), 0) def test_change_form_deletion_when_invalid(self): """ Make sure that a change form that is filled out, but marked for deletion doesn't cause validation errors. """ PoetFormSet = modelformset_factory(Poet, fields="__all__", can_delete=True) poet = Poet.objects.create(name='test') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '0', 'form-0-id': str(poet.id), 'form-0-name': 'x' * 1000, } formset = PoetFormSet(data, queryset=Poet.objects.all()) # Make sure this form doesn't pass validation. self.assertIs(formset.is_valid(), False) self.assertEqual(Poet.objects.count(), 1) # Then make sure that it *does* pass validation and delete the object, # even though the data isn't actually valid. data['form-0-DELETE'] = 'on' formset = PoetFormSet(data, queryset=Poet.objects.all()) self.assertIs(formset.is_valid(), True) formset.save() self.assertEqual(Poet.objects.count(), 0) def test_outdated_deletion(self): poet = Poet.objects.create(name='test') poem = Poem.objects.create(name='Brevity is the soul of wit', poet=poet) PoemFormSet = inlineformset_factory(Poet, Poem, fields="__all__", can_delete=True) # Simulate deletion of an object that doesn't exist in the database data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '2', 'form-0-id': str(poem.pk), 'form-0-name': 'foo', 'form-1-id': str(poem.pk + 1), # doesn't exist 'form-1-name': 'bar', 'form-1-DELETE': 'on', } formset = PoemFormSet(data, instance=poet, prefix="form") # The formset is valid even though poem.pk + 1 doesn't exist, # because it's marked for deletion anyway self.assertTrue(formset.is_valid()) formset.save() # Make sure the save went through correctly self.assertEqual(Poem.objects.get(pk=poem.pk).name, "foo") self.assertEqual(poet.poem_set.count(), 1) self.assertFalse(Poem.objects.filter(pk=poem.pk + 1).exists()) class ModelFormsetTest(TestCase): def test_modelformset_factory_without_fields(self): """ Regression for #19733 """ message = ( "Calling modelformset_factory without defining 'fields' or 'exclude' " "explicitly is prohibited." ) with self.assertRaisesMessage(ImproperlyConfigured, message): modelformset_factory(Author) def test_simple_save(self): qs = Author.objects.all() AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label>' '<input id="id_form-0-name" type="text" name="form-0-name" maxlength="100">' '<input type="hidden" name="form-0-id" id="id_form-0-id"></p>' ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label>' '<input id="id_form-1-name" type="text" name="form-1-name" maxlength="100">' '<input type="hidden" name="form-1-id" id="id_form-1-id"></p>' ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label>' ' <input id="id_form-2-name" type="text" name="form-2-name" maxlength="100">' '<input type="hidden" name="form-2-id" id="id_form-2-id"></p>' ) data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-name': 'Charles Baudelaire', 'form-1-name': 'Arthur Rimbaud', 'form-2-name': '', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) author1, author2 = saved self.assertEqual(author1, Author.objects.get(name='Charles Baudelaire')) self.assertEqual(author2, Author.objects.get(name='Arthur Rimbaud')) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1]) # Gah! We forgot Paul Verlaine. Let's create a formset to edit the # existing authors with an extra form to add him. We *could* pass in a # queryset to restrict the Author objects we edit, but in this case # we'll use it to display them in alphabetical order by name. qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=1, can_delete=False) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label>' '<input id="id_form-0-name" type="text" name="form-0-name" value="Arthur Rimbaud" maxlength="100">' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id"></p>' % author2.id ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label>' '<input id="id_form-1-name" type="text" name="form-1-name" value="Charles Baudelaire" maxlength="100">' '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id"></p>' % author1.id ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label>' '<input id="id_form-2-name" type="text" name="form-2-name" maxlength="100">' '<input type="hidden" name="form-2-id" id="id_form-2-id"></p>' ) data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '2', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Arthur Rimbaud', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-name': 'Paul Verlaine', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # Only changed or new objects are returned from formset.save() saved = formset.save() self.assertEqual(len(saved), 1) author3 = saved[0] self.assertEqual(author3, Author.objects.get(name='Paul Verlaine')) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1, author3]) # This probably shouldn't happen, but it will. If an add form was # marked for deletion, make sure we don't save that form. qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=1, can_delete=True) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 4) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label>' '<input id="id_form-0-name" type="text" name="form-0-name" ' 'value="Arthur Rimbaud" maxlength="100"></p>' '<p><label for="id_form-0-DELETE">Delete:</label>' '<input type="checkbox" name="form-0-DELETE" id="id_form-0-DELETE">' '<input type="hidden" name="form-0-id" value="%d" id="id_form-0-id"></p>' % author2.id ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label>' '<input id="id_form-1-name" type="text" name="form-1-name" ' 'value="Charles Baudelaire" maxlength="100"></p>' '<p><label for="id_form-1-DELETE">Delete:</label>' '<input type="checkbox" name="form-1-DELETE" id="id_form-1-DELETE">' '<input type="hidden" name="form-1-id" value="%d" id="id_form-1-id"></p>' % author1.id ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_form-2-name">Name:</label>' '<input id="id_form-2-name" type="text" name="form-2-name" ' 'value="Paul Verlaine" maxlength="100"></p>' '<p><label for="id_form-2-DELETE">Delete:</label>' '<input type="checkbox" name="form-2-DELETE" id="id_form-2-DELETE">' '<input type="hidden" name="form-2-id" value="%d" id="id_form-2-id"></p>' % author3.id ) self.assertHTMLEqual( formset.forms[3].as_p(), '<p><label for="id_form-3-name">Name:</label>' '<input id="id_form-3-name" type="text" name="form-3-name" maxlength="100"></p>' '<p><label for="id_form-3-DELETE">Delete:</label>' '<input type="checkbox" name="form-3-DELETE" id="id_form-3-DELETE">' '<input type="hidden" name="form-3-id" id="id_form-3-id"></p>' ) data = { 'form-TOTAL_FORMS': '4', # the number of forms rendered 'form-INITIAL_FORMS': '3', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Arthur Rimbaud', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-id': str(author3.id), 'form-2-name': 'Paul Verlaine', 'form-3-name': 'Walt Whitman', 'form-3-DELETE': 'on', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # No objects were changed or saved so nothing will come back. self.assertEqual(formset.save(), []) authors = list(Author.objects.order_by('name')) self.assertEqual(authors, [author2, author1, author3]) # Let's edit a record to ensure save only returns that one record. data = { 'form-TOTAL_FORMS': '4', # the number of forms rendered 'form-INITIAL_FORMS': '3', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Walt Whitman', 'form-1-id': str(author1.id), 'form-1-name': 'Charles Baudelaire', 'form-2-id': str(author3.id), 'form-2-name': 'Paul Verlaine', 'form-3-name': '', 'form-3-DELETE': '', } formset = AuthorFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) # One record has changed. saved = formset.save() self.assertEqual(len(saved), 1) self.assertEqual(saved[0], Author.objects.get(name='Walt Whitman')) def test_commit_false(self): # Test the behavior of commit=False and save_m2m author1 = Author.objects.create(name='Charles Baudelaire') author2 = Author.objects.create(name='Paul Verlaine') author3 = Author.objects.create(name='Walt Whitman') meeting = AuthorMeeting.objects.create(created=date.today()) meeting.authors.set(Author.objects.all()) # create an Author instance to add to the meeting. author4 = Author.objects.create(name='John Steinbeck') AuthorMeetingFormSet = modelformset_factory(AuthorMeeting, fields="__all__", extra=1, can_delete=True) data = { 'form-TOTAL_FORMS': '2', # the number of forms rendered 'form-INITIAL_FORMS': '1', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(meeting.id), 'form-0-name': '2nd Tuesday of the Week Meeting', 'form-0-authors': [author2.id, author1.id, author3.id, author4.id], 'form-1-name': '', 'form-1-authors': '', 'form-1-DELETE': '', } formset = AuthorMeetingFormSet(data=data, queryset=AuthorMeeting.objects.all()) self.assertTrue(formset.is_valid()) instances = formset.save(commit=False) for instance in instances: instance.created = date.today() instance.save() formset.save_m2m() self.assertQuerysetEqual(instances[0].authors.all(), [ '<Author: Charles Baudelaire>', '<Author: John Steinbeck>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) def test_max_num(self): # Test the behavior of max_num with model formsets. It should allow # all existing related objects/inlines for a given object to be # displayed, but not allow the creation of new inlines beyond max_num. Author.objects.create(name='Charles Baudelaire') Author.objects.create(name='Paul Verlaine') Author.objects.create(name='Walt Whitman') qs = Author.objects.order_by('name') AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=None, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 6) self.assertEqual(len(formset.extra_forms), 3) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=4, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 4) self.assertEqual(len(formset.extra_forms), 1) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=0, extra=3) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 3) self.assertEqual(len(formset.extra_forms), 0) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=None) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=0) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=4) formset = AuthorFormSet(queryset=qs) self.assertQuerysetEqual(formset.get_queryset(), [ '<Author: Charles Baudelaire>', '<Author: Paul Verlaine>', '<Author: Walt Whitman>', ]) def test_min_num(self): # Test the behavior of min_num with model formsets. It should be # added to extra. qs = Author.objects.none() AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=0) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 0) AuthorFormSet = modelformset_factory(Author, fields="__all__", min_num=1, extra=0) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 1) AuthorFormSet = modelformset_factory(Author, fields="__all__", min_num=1, extra=1) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 2) def test_min_num_with_existing(self): # Test the behavior of min_num with existing objects. Author.objects.create(name='Charles Baudelaire') qs = Author.objects.all() AuthorFormSet = modelformset_factory(Author, fields="__all__", extra=0, min_num=1) formset = AuthorFormSet(queryset=qs) self.assertEqual(len(formset.forms), 1) def test_custom_save_method(self): class PoetForm(forms.ModelForm): def save(self, commit=True): # change the name to "Vladimir Mayakovsky" just to be a jerk. author = super().save(commit=False) author.name = "Vladimir Mayakovsky" if commit: author.save() return author PoetFormSet = modelformset_factory(Poet, fields="__all__", form=PoetForm) data = { 'form-TOTAL_FORMS': '3', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-name': 'Walt Whitman', 'form-1-name': 'Charles Baudelaire', 'form-2-name': '', } qs = Poet.objects.all() formset = PoetFormSet(data=data, queryset=qs) self.assertTrue(formset.is_valid()) poets = formset.save() self.assertEqual(len(poets), 2) poet1, poet2 = poets self.assertEqual(poet1.name, 'Vladimir Mayakovsky') self.assertEqual(poet2.name, 'Vladimir Mayakovsky') def test_custom_form(self): """ model_formset_factory() respects fields and exclude parameters of a custom form. """ class PostForm1(forms.ModelForm): class Meta: model = Post fields = ('title', 'posted') class PostForm2(forms.ModelForm): class Meta: model = Post exclude = ('subtitle',) PostFormSet = modelformset_factory(Post, form=PostForm1) formset = PostFormSet() self.assertNotIn("subtitle", formset.forms[0].fields) PostFormSet = modelformset_factory(Post, form=PostForm2) formset = PostFormSet() self.assertNotIn("subtitle", formset.forms[0].fields) def test_custom_queryset_init(self): """ A queryset can be overridden in the formset's __init__() method. """ Author.objects.create(name='Charles Baudelaire') Author.objects.create(name='Paul Verlaine') class BaseAuthorFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = Author.objects.filter(name__startswith='Charles') AuthorFormSet = modelformset_factory(Author, fields='__all__', formset=BaseAuthorFormSet) formset = AuthorFormSet() self.assertEqual(len(formset.get_queryset()), 1) def test_model_inheritance(self): BetterAuthorFormSet = modelformset_factory(BetterAuthor, fields="__all__") formset = BetterAuthorFormSet() self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label>' '<input id="id_form-0-name" type="text" name="form-0-name" maxlength="100"></p>' '<p><label for="id_form-0-write_speed">Write speed:</label>' '<input type="number" name="form-0-write_speed" id="id_form-0-write_speed">' '<input type="hidden" name="form-0-author_ptr" id="id_form-0-author_ptr"></p>' ) data = { 'form-TOTAL_FORMS': '1', # the number of forms rendered 'form-INITIAL_FORMS': '0', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-author_ptr': '', 'form-0-name': 'Ernest Hemingway', 'form-0-write_speed': '10', } formset = BetterAuthorFormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) author1, = saved self.assertEqual(author1, BetterAuthor.objects.get(name='Ernest Hemingway')) hemingway_id = BetterAuthor.objects.get(name="Ernest Hemingway").pk formset = BetterAuthorFormSet() self.assertEqual(len(formset.forms), 2) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-name">Name:</label>' '<input id="id_form-0-name" type="text" name="form-0-name" value="Ernest Hemingway" maxlength="100"></p>' '<p><label for="id_form-0-write_speed">Write speed:</label>' '<input type="number" name="form-0-write_speed" value="10" id="id_form-0-write_speed">' '<input type="hidden" name="form-0-author_ptr" value="%d" id="id_form-0-author_ptr"></p>' % hemingway_id ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_form-1-name">Name:</label>' '<input id="id_form-1-name" type="text" name="form-1-name" maxlength="100"></p>' '<p><label for="id_form-1-write_speed">Write speed:</label>' '<input type="number" name="form-1-write_speed" id="id_form-1-write_speed">' '<input type="hidden" name="form-1-author_ptr" id="id_form-1-author_ptr"></p>' ) data = { 'form-TOTAL_FORMS': '2', # the number of forms rendered 'form-INITIAL_FORMS': '1', # the number of forms with initial data 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-author_ptr': hemingway_id, 'form-0-name': 'Ernest Hemingway', 'form-0-write_speed': '10', 'form-1-author_ptr': '', 'form-1-name': '', 'form-1-write_speed': '', } formset = BetterAuthorFormSet(data) self.assertTrue(formset.is_valid()) self.assertEqual(formset.save(), []) def test_inline_formsets(self): # We can also create a formset that is tied to a parent model. This is # how the admin system's edit inline functionality works. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=3, fields="__all__") author = Author.objects.create(name='Charles Baudelaire') formset = AuthorBooksFormSet(instance=author) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label> <input id="id_book_set-0-title" type="text" ' 'name="book_set-0-title" maxlength="100"><input type="hidden" name="book_set-0-author" value="%d" ' 'id="id_book_set-0-author"><input type="hidden" name="book_set-0-id" id="id_book_set-0-id">' '</p>' % author.id ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label>' '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">' '<input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author">' '<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>' % author.id ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label>' '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">' '<input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author">' '<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>' % author.id ) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '0', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-title': '', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1, Book.objects.get(title='Les Fleurs du Mal')) self.assertQuerysetEqual(author.book_set.all(), ['<Book: Les Fleurs du Mal>']) # Now that we've added a book to Charles Baudelaire, let's try adding # another one. This time though, an edit form will be available for # every existing book. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2, fields="__all__") author = Author.objects.get(name='Charles Baudelaire') formset = AuthorBooksFormSet(instance=author) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label>' '<input id="id_book_set-0-title" type="text" name="book_set-0-title" ' 'value="Les Fleurs du Mal" maxlength="100">' '<input type="hidden" name="book_set-0-author" value="%d" id="id_book_set-0-author">' '<input type="hidden" name="book_set-0-id" value="%d" id="id_book_set-0-id"></p>' % ( author.id, book1.id, ) ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label>' '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">' '<input type="hidden" name="book_set-1-author" value="%d" id="id_book_set-1-author">' '<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>' % author.id ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label>' '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">' '<input type="hidden" name="book_set-2-author" value="%d" id="id_book_set-2-author">' '<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>' % author.id ) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book1.id), 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-title': 'Les Paradis Artificiels', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book2, = saved self.assertEqual(book2, Book.objects.get(title='Les Paradis Artificiels')) # As you can see, 'Les Paradis Artificiels' is now a book belonging to # Charles Baudelaire. self.assertQuerysetEqual(author.book_set.order_by('title'), [ '<Book: Les Fleurs du Mal>', '<Book: Les Paradis Artificiels>', ]) def test_inline_formsets_save_as_new(self): # The save_as_new parameter lets you re-associate the data to a new # instance. This is used in the admin for save_as functionality. AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2, fields="__all__") Author.objects.create(name='Charles Baudelaire') # An immutable QueryDict simulates request.POST. data = QueryDict(mutable=True) data.update({ 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '2', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': '1', 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-id': '2', 'book_set-1-title': 'Les Paradis Artificiels', 'book_set-2-title': '', }) data._mutable = False formset = AuthorBooksFormSet(data, instance=Author(), save_as_new=True) self.assertTrue(formset.is_valid()) self.assertIs(data._mutable, False) new_author = Author.objects.create(name='Charles Baudelaire') formset = AuthorBooksFormSet(data, instance=new_author, save_as_new=True) saved = formset.save() self.assertEqual(len(saved), 2) book1, book2 = saved self.assertEqual(book1.title, 'Les Fleurs du Mal') self.assertEqual(book2.title, 'Les Paradis Artificiels') # Test using a custom prefix on an inline formset. formset = AuthorBooksFormSet(prefix="test") self.assertEqual(len(formset.forms), 2) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_test-0-title">Title:</label>' '<input id="id_test-0-title" type="text" name="test-0-title" maxlength="100">' '<input type="hidden" name="test-0-author" id="id_test-0-author">' '<input type="hidden" name="test-0-id" id="id_test-0-id"></p>' ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_test-1-title">Title:</label>' '<input id="id_test-1-title" type="text" name="test-1-title" maxlength="100">' '<input type="hidden" name="test-1-author" id="id_test-1-author">' '<input type="hidden" name="test-1-id" id="id_test-1-id"></p>' ) def test_inline_formsets_with_custom_pk(self): # Test inline formsets where the inline-edited object has a custom # primary key that is not the fk to the parent object. self.maxDiff = 1024 AuthorBooksFormSet2 = inlineformset_factory( Author, BookWithCustomPK, can_delete=False, extra=1, fields="__all__" ) author = Author.objects.create(pk=1, name='Charles Baudelaire') formset = AuthorBooksFormSet2(instance=author) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_bookwithcustompk_set-0-my_pk">My pk:</label>' '<input id="id_bookwithcustompk_set-0-my_pk" type="number" ' 'name="bookwithcustompk_set-0-my_pk" step="1"></p>' '<p><label for="id_bookwithcustompk_set-0-title">Title:</label>' '<input id="id_bookwithcustompk_set-0-title" type="text" ' 'name="bookwithcustompk_set-0-title" maxlength="100">' '<input type="hidden" name="bookwithcustompk_set-0-author" ' 'value="1" id="id_bookwithcustompk_set-0-author"></p>' ) data = { 'bookwithcustompk_set-TOTAL_FORMS': '1', # the number of forms rendered 'bookwithcustompk_set-INITIAL_FORMS': '0', # the number of forms with initial data 'bookwithcustompk_set-MAX_NUM_FORMS': '', # the max number of forms 'bookwithcustompk_set-0-my_pk': '77777', 'bookwithcustompk_set-0-title': 'Les Fleurs du Mal', } formset = AuthorBooksFormSet2(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1.pk, 77777) book1 = author.bookwithcustompk_set.get() self.assertEqual(book1.title, 'Les Fleurs du Mal') def test_inline_formsets_with_multi_table_inheritance(self): # Test inline formsets where the inline-edited object uses multi-table # inheritance, thus has a non AutoField yet auto-created primary key. AuthorBooksFormSet3 = inlineformset_factory(Author, AlternateBook, can_delete=False, extra=1, fields="__all__") author = Author.objects.create(pk=1, name='Charles Baudelaire') formset = AuthorBooksFormSet3(instance=author) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_alternatebook_set-0-title">Title:</label>' '<input id="id_alternatebook_set-0-title" type="text" ' 'name="alternatebook_set-0-title" maxlength="100"></p>' '<p><label for="id_alternatebook_set-0-notes">Notes:</label>' '<input id="id_alternatebook_set-0-notes" type="text" ' 'name="alternatebook_set-0-notes" maxlength="100">' '<input type="hidden" name="alternatebook_set-0-author" value="1" ' 'id="id_alternatebook_set-0-author">' '<input type="hidden" name="alternatebook_set-0-book_ptr" ' 'id="id_alternatebook_set-0-book_ptr"></p>' ) data = { 'alternatebook_set-TOTAL_FORMS': '1', # the number of forms rendered 'alternatebook_set-INITIAL_FORMS': '0', # the number of forms with initial data 'alternatebook_set-MAX_NUM_FORMS': '', # the max number of forms 'alternatebook_set-0-title': 'Flowers of Evil', 'alternatebook_set-0-notes': 'English translation of Les Fleurs du Mal' } formset = AuthorBooksFormSet3(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) book1, = saved self.assertEqual(book1.title, 'Flowers of Evil') self.assertEqual(book1.notes, 'English translation of Les Fleurs du Mal') @skipUnlessDBFeature('supports_partially_nullable_unique_constraints') def test_inline_formsets_with_nullable_unique_together(self): # Test inline formsets where the inline-edited object has a # unique_together constraint with a nullable member AuthorBooksFormSet4 = inlineformset_factory( Author, BookWithOptionalAltEditor, can_delete=False, extra=2, fields="__all__" ) author = Author.objects.create(pk=1, name='Charles Baudelaire') data = { 'bookwithoptionalalteditor_set-TOTAL_FORMS': '2', # the number of forms rendered 'bookwithoptionalalteditor_set-INITIAL_FORMS': '0', # the number of forms with initial data 'bookwithoptionalalteditor_set-MAX_NUM_FORMS': '', # the max number of forms 'bookwithoptionalalteditor_set-0-author': '1', 'bookwithoptionalalteditor_set-0-title': 'Les Fleurs du Mal', 'bookwithoptionalalteditor_set-1-author': '1', 'bookwithoptionalalteditor_set-1-title': 'Les Fleurs du Mal', } formset = AuthorBooksFormSet4(data, instance=author) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) book1, book2 = saved self.assertEqual(book1.author_id, 1) self.assertEqual(book1.title, 'Les Fleurs du Mal') self.assertEqual(book2.author_id, 1) self.assertEqual(book2.title, 'Les Fleurs du Mal') def test_inline_formsets_with_custom_save_method(self): AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2, fields="__all__") author = Author.objects.create(pk=1, name='Charles Baudelaire') book1 = Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels') book2 = Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal') book3 = Book.objects.create(pk=3, author=author, title='Flowers of Evil') class PoemForm(forms.ModelForm): def save(self, commit=True): # change the name to "Brooklyn Bridge" just to be a jerk. poem = super().save(commit=False) poem.name = "Brooklyn Bridge" if commit: poem.save() return poem PoemFormSet = inlineformset_factory(Poet, Poem, form=PoemForm, fields="__all__") data = { 'poem_set-TOTAL_FORMS': '3', # the number of forms rendered 'poem_set-INITIAL_FORMS': '0', # the number of forms with initial data 'poem_set-MAX_NUM_FORMS': '', # the max number of forms 'poem_set-0-name': 'The Cloud in Trousers', 'poem_set-1-name': 'I', 'poem_set-2-name': '', } poet = Poet.objects.create(name='Vladimir Mayakovsky') formset = PoemFormSet(data=data, instance=poet) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 2) poem1, poem2 = saved self.assertEqual(poem1.name, 'Brooklyn Bridge') self.assertEqual(poem2.name, 'Brooklyn Bridge') # We can provide a custom queryset to our InlineFormSet: custom_qs = Book.objects.order_by('-title') formset = AuthorBooksFormSet(instance=author, queryset=custom_qs) self.assertEqual(len(formset.forms), 5) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label>' '<input id="id_book_set-0-title" type="text" name="book_set-0-title" ' 'value="Les Paradis Artificiels" maxlength="100">' '<input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author">' '<input type="hidden" name="book_set-0-id" value="1" id="id_book_set-0-id"></p>' ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label>' '<input id="id_book_set-1-title" type="text" name="book_set-1-title" ' 'value="Les Fleurs du Mal" maxlength="100">' '<input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author">' '<input type="hidden" name="book_set-1-id" value="2" id="id_book_set-1-id"></p>' ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label>' '<input id="id_book_set-2-title" type="text" name="book_set-2-title" ' 'value="Flowers of Evil" maxlength="100">' '<input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author">' '<input type="hidden" name="book_set-2-id" value="3" id="id_book_set-2-id"></p>' ) self.assertHTMLEqual( formset.forms[3].as_p(), '<p><label for="id_book_set-3-title">Title:</label>' '<input id="id_book_set-3-title" type="text" name="book_set-3-title" maxlength="100">' '<input type="hidden" name="book_set-3-author" value="1" id="id_book_set-3-author">' '<input type="hidden" name="book_set-3-id" id="id_book_set-3-id"></p>' ) self.assertHTMLEqual( formset.forms[4].as_p(), '<p><label for="id_book_set-4-title">Title:</label>' '<input id="id_book_set-4-title" type="text" name="book_set-4-title" maxlength="100">' '<input type="hidden" name="book_set-4-author" value="1" id="id_book_set-4-author">' '<input type="hidden" name="book_set-4-id" id="id_book_set-4-id"></p>' ) data = { 'book_set-TOTAL_FORMS': '5', # the number of forms rendered 'book_set-INITIAL_FORMS': '3', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book1.id), 'book_set-0-title': 'Les Paradis Artificiels', 'book_set-1-id': str(book2.id), 'book_set-1-title': 'Les Fleurs du Mal', 'book_set-2-id': str(book3.id), 'book_set-2-title': 'Flowers of Evil', 'book_set-3-title': 'Revue des deux mondes', 'book_set-4-title': '', } formset = AuthorBooksFormSet(data, instance=author, queryset=custom_qs) self.assertTrue(formset.is_valid()) custom_qs = Book.objects.filter(title__startswith='F') formset = AuthorBooksFormSet(instance=author, queryset=custom_qs) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_book_set-0-title">Title:</label>' '<input id="id_book_set-0-title" type="text" name="book_set-0-title" ' 'value="Flowers of Evil" maxlength="100">' '<input type="hidden" name="book_set-0-author" value="1" id="id_book_set-0-author">' '<input type="hidden" name="book_set-0-id" value="3" id="id_book_set-0-id"></p>' ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_book_set-1-title">Title:</label>' '<input id="id_book_set-1-title" type="text" name="book_set-1-title" maxlength="100">' '<input type="hidden" name="book_set-1-author" value="1" id="id_book_set-1-author">' '<input type="hidden" name="book_set-1-id" id="id_book_set-1-id"></p>' ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_book_set-2-title">Title:</label>' '<input id="id_book_set-2-title" type="text" name="book_set-2-title" maxlength="100">' '<input type="hidden" name="book_set-2-author" value="1" id="id_book_set-2-author">' '<input type="hidden" name="book_set-2-id" id="id_book_set-2-id"></p>' ) data = { 'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book3.id), 'book_set-0-title': 'Flowers of Evil', 'book_set-1-title': 'Revue des deux mondes', 'book_set-2-title': '', } formset = AuthorBooksFormSet(data, instance=author, queryset=custom_qs) self.assertTrue(formset.is_valid()) def test_inline_formsets_with_custom_save_method_related_instance(self): """ The ModelForm.save() method should be able to access the related object if it exists in the database (#24395). """ class PoemForm2(forms.ModelForm): def save(self, commit=True): poem = super().save(commit=False) poem.name = "%s by %s" % (poem.name, poem.poet.name) if commit: poem.save() return poem PoemFormSet = inlineformset_factory(Poet, Poem, form=PoemForm2, fields="__all__") data = { 'poem_set-TOTAL_FORMS': '1', 'poem_set-INITIAL_FORMS': '0', 'poem_set-MAX_NUM_FORMS': '', 'poem_set-0-name': 'Le Lac', } poet = Poet() formset = PoemFormSet(data=data, instance=poet) self.assertTrue(formset.is_valid()) # The Poet instance is saved after the formset instantiation. This # happens in admin's changeform_view() when adding a new object and # some inlines in the same request. poet.name = 'Lamartine' poet.save() poem = formset.save()[0] self.assertEqual(poem.name, 'Le Lac by Lamartine') def test_inline_formsets_with_wrong_fk_name(self): """ Regression for #23451 """ message = "fk_name 'title' is not a ForeignKey to 'model_formsets.Author'." with self.assertRaisesMessage(ValueError, message): inlineformset_factory(Author, Book, fields="__all__", fk_name='title') def test_custom_pk(self): # We need to ensure that it is displayed CustomPrimaryKeyFormSet = modelformset_factory(CustomPrimaryKey, fields="__all__") formset = CustomPrimaryKeyFormSet() self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-my_pk">My pk:</label> <input id="id_form-0-my_pk" type="text" ' 'name="form-0-my_pk" maxlength="10"></p>' '<p><label for="id_form-0-some_field">Some field:</label>' '<input id="id_form-0-some_field" type="text" name="form-0-some_field" maxlength="100"></p>' ) # Custom primary keys with ForeignKey, OneToOneField and AutoField ############ place = Place.objects.create(pk=1, name='Giordanos', city='Chicago') FormSet = inlineformset_factory(Place, Owner, extra=2, can_delete=False, fields="__all__") formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 2) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_owner_set-0-name">Name:</label>' '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" maxlength="100">' '<input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place">' '<input type="hidden" name="owner_set-0-auto_id" id="id_owner_set-0-auto_id"></p>' ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_owner_set-1-name">Name:</label>' '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100">' '<input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place">' '<input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id"></p>' ) data = { 'owner_set-TOTAL_FORMS': '2', 'owner_set-INITIAL_FORMS': '0', 'owner_set-MAX_NUM_FORMS': '', 'owner_set-0-auto_id': '', 'owner_set-0-name': 'Joe Perry', 'owner_set-1-auto_id': '', 'owner_set-1-name': '', } formset = FormSet(data, instance=place) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) owner1, = saved self.assertEqual(owner1.name, 'Joe Perry') self.assertEqual(owner1.place.name, 'Giordanos') formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 3) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_owner_set-0-name">Name:</label>' '<input id="id_owner_set-0-name" type="text" name="owner_set-0-name" value="Joe Perry" maxlength="100">' '<input type="hidden" name="owner_set-0-place" value="1" id="id_owner_set-0-place">' '<input type="hidden" name="owner_set-0-auto_id" value="%d" id="id_owner_set-0-auto_id"></p>' % owner1.auto_id ) self.assertHTMLEqual( formset.forms[1].as_p(), '<p><label for="id_owner_set-1-name">Name:</label>' '<input id="id_owner_set-1-name" type="text" name="owner_set-1-name" maxlength="100">' '<input type="hidden" name="owner_set-1-place" value="1" id="id_owner_set-1-place">' '<input type="hidden" name="owner_set-1-auto_id" id="id_owner_set-1-auto_id"></p>' ) self.assertHTMLEqual( formset.forms[2].as_p(), '<p><label for="id_owner_set-2-name">Name:</label>' '<input id="id_owner_set-2-name" type="text" name="owner_set-2-name" maxlength="100">' '<input type="hidden" name="owner_set-2-place" value="1" id="id_owner_set-2-place">' '<input type="hidden" name="owner_set-2-auto_id" id="id_owner_set-2-auto_id"></p>' ) data = { 'owner_set-TOTAL_FORMS': '3', 'owner_set-INITIAL_FORMS': '1', 'owner_set-MAX_NUM_FORMS': '', 'owner_set-0-auto_id': str(owner1.auto_id), 'owner_set-0-name': 'Joe Perry', 'owner_set-1-auto_id': '', 'owner_set-1-name': 'Jack Berry', 'owner_set-2-auto_id': '', 'owner_set-2-name': '', } formset = FormSet(data, instance=place) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) owner2, = saved self.assertEqual(owner2.name, 'Jack Berry') self.assertEqual(owner2.place.name, 'Giordanos') # Ensure a custom primary key that is a ForeignKey or OneToOneField get rendered for the user to choose. FormSet = modelformset_factory(OwnerProfile, fields="__all__") formset = FormSet() self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_form-0-owner">Owner:</label>' '<select name="form-0-owner" id="id_form-0-owner">' '<option value="" selected>---------</option>' '<option value="%d">Joe Perry at Giordanos</option>' '<option value="%d">Jack Berry at Giordanos</option>' '</select></p>' '<p><label for="id_form-0-age">Age:</label>' '<input type="number" name="form-0-age" id="id_form-0-age" min="0"></p>' % (owner1.auto_id, owner2.auto_id) ) owner1 = Owner.objects.get(name='Joe Perry') FormSet = inlineformset_factory(Owner, OwnerProfile, max_num=1, can_delete=False, fields="__all__") self.assertEqual(FormSet.max_num, 1) formset = FormSet(instance=owner1) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_ownerprofile-0-age">Age:</label>' '<input type="number" name="ownerprofile-0-age" id="id_ownerprofile-0-age" min="0">' '<input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner"></p>' % owner1.auto_id ) data = { 'ownerprofile-TOTAL_FORMS': '1', 'ownerprofile-INITIAL_FORMS': '0', 'ownerprofile-MAX_NUM_FORMS': '1', 'ownerprofile-0-owner': '', 'ownerprofile-0-age': '54', } formset = FormSet(data, instance=owner1) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) profile1, = saved self.assertEqual(profile1.owner, owner1) self.assertEqual(profile1.age, 54) formset = FormSet(instance=owner1) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_ownerprofile-0-age">Age:</label>' '<input type="number" name="ownerprofile-0-age" value="54" id="id_ownerprofile-0-age" min="0">' '<input type="hidden" name="ownerprofile-0-owner" value="%d" id="id_ownerprofile-0-owner"></p>' % owner1.auto_id ) data = { 'ownerprofile-TOTAL_FORMS': '1', 'ownerprofile-INITIAL_FORMS': '1', 'ownerprofile-MAX_NUM_FORMS': '1', 'ownerprofile-0-owner': str(owner1.auto_id), 'ownerprofile-0-age': '55', } formset = FormSet(data, instance=owner1) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) profile1, = saved self.assertEqual(profile1.owner, owner1) self.assertEqual(profile1.age, 55) def test_unique_true_enforces_max_num_one(self): # ForeignKey with unique=True should enforce max_num=1 place = Place.objects.create(pk=1, name='Giordanos', city='Chicago') FormSet = inlineformset_factory(Place, Location, can_delete=False, fields="__all__") self.assertEqual(FormSet.max_num, 1) formset = FormSet(instance=place) self.assertEqual(len(formset.forms), 1) self.assertHTMLEqual( formset.forms[0].as_p(), '<p><label for="id_location_set-0-lat">Lat:</label>' '<input id="id_location_set-0-lat" type="text" name="location_set-0-lat" maxlength="100"></p>' '<p><label for="id_location_set-0-lon">Lon:</label> ' '<input id="id_location_set-0-lon" type="text" name="location_set-0-lon" maxlength="100">' '<input type="hidden" name="location_set-0-place" value="1" id="id_location_set-0-place">' '<input type="hidden" name="location_set-0-id" id="id_location_set-0-id"></p>' ) def test_foreign_keys_in_parents(self): self.assertEqual(type(_get_foreign_key(Restaurant, Owner)), models.ForeignKey) self.assertEqual(type(_get_foreign_key(MexicanRestaurant, Owner)), models.ForeignKey) def test_unique_validation(self): FormSet = modelformset_factory(Product, fields="__all__", extra=1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'car-red', } formset = FormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) product1, = saved self.assertEqual(product1.slug, 'car-red') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'car-red', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'slug': ['Product with this Slug already exists.']}]) def test_modelformset_validate_max_flag(self): # If validate_max is set and max_num is less than TOTAL_FORMS in the # data, then throw an exception. MAX_NUM_FORMS in the data is # irrelevant here (it's output as a hint for the client but its # value in the returned data is not checked) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '2', # should be ignored 'form-0-price': '12.00', 'form-0-quantity': '1', 'form-1-price': '24.00', 'form-1-quantity': '2', } FormSet = modelformset_factory(Price, fields="__all__", extra=1, max_num=1, validate_max=True) formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ['Please submit 1 or fewer forms.']) # Now test the same thing without the validate_max flag to ensure # default behavior is unchanged FormSet = modelformset_factory(Price, fields="__all__", extra=1, max_num=1) formset = FormSet(data) self.assertTrue(formset.is_valid()) def test_unique_together_validation(self): FormSet = modelformset_factory(Price, fields="__all__", extra=1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': '12.00', 'form-0-quantity': '1', } formset = FormSet(data) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) price1, = saved self.assertEqual(price1.price, Decimal('12.00')) self.assertEqual(price1.quantity, 1) data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': '12.00', 'form-0-quantity': '1', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'__all__': ['Price with this Price and Quantity already exists.']}]) def test_unique_together_with_inlineformset_factory(self): # Also see bug #8882. repository = Repository.objects.create(name='Test Repo') FormSet = inlineformset_factory(Repository, Revision, extra=1, fields="__all__") data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertTrue(formset.is_valid()) saved = formset.save() self.assertEqual(len(saved), 1) revision1, = saved self.assertEqual(revision1.repository, repository) self.assertEqual(revision1.revision, '146239817507f148d448db38840db7c3cbf47c76') # attempt to save the same revision against the same repo. data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{'__all__': ['Revision with this Repository and Revision already exists.']}]) # unique_together with inlineformset_factory with overridden form fields # Also see #9494 FormSet = inlineformset_factory(Repository, Revision, fields=('revision',), extra=1) data = { 'revision_set-TOTAL_FORMS': '1', 'revision_set-INITIAL_FORMS': '0', 'revision_set-MAX_NUM_FORMS': '', 'revision_set-0-repository': repository.pk, 'revision_set-0-revision': '146239817507f148d448db38840db7c3cbf47c76', 'revision_set-0-DELETE': '', } formset = FormSet(data, instance=repository) self.assertFalse(formset.is_valid()) def test_callable_defaults(self): # Use of callable defaults (see bug #7975). person = Person.objects.create(name='Ringo') FormSet = inlineformset_factory(Person, Membership, can_delete=False, extra=1, fields="__all__") formset = FormSet(instance=person) # Django will render a hidden field for model fields that have a callable # default. This is required to ensure the value is tested for change correctly # when determine what extra forms have changed to save. self.assertEqual(len(formset.forms), 1) # this formset only has one form form = formset.forms[0] now = form.fields['date_joined'].initial() result = form.as_p() result = re.sub(r'[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(?:\.[0-9]+)?', '__DATETIME__', result) self.assertHTMLEqual( result, '<p><label for="id_membership_set-0-date_joined">Date joined:</label>' '<input type="text" name="membership_set-0-date_joined" ' 'value="__DATETIME__" id="id_membership_set-0-date_joined">' '<input type="hidden" name="initial-membership_set-0-date_joined" value="__DATETIME__" ' 'id="initial-membership_set-0-id_membership_set-0-date_joined"></p>' '<p><label for="id_membership_set-0-karma">Karma:</label>' '<input type="number" name="membership_set-0-karma" id="id_membership_set-0-karma">' '<input type="hidden" name="membership_set-0-person" value="%d" id="id_membership_set-0-person">' '<input type="hidden" name="membership_set-0-id" id="id_membership_set-0-id"></p>' % person.id) # test for validation with callable defaults. Validations rely on hidden fields data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'), 'initial-membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'), 'membership_set-0-karma': '', } formset = FormSet(data, instance=person) self.assertTrue(formset.is_valid()) # now test for when the data changes one_day_later = now + datetime.timedelta(days=1) filled_data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined': one_day_later.strftime('%Y-%m-%d %H:%M:%S'), 'initial-membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'), 'membership_set-0-karma': '', } formset = FormSet(filled_data, instance=person) self.assertFalse(formset.is_valid()) # now test with split datetime fields class MembershipForm(forms.ModelForm): date_joined = forms.SplitDateTimeField(initial=now) class Meta: model = Membership fields = "__all__" def __init__(self, **kwargs): super().__init__(**kwargs) self.fields['date_joined'].widget = forms.SplitDateTimeWidget() FormSet = inlineformset_factory( Person, Membership, form=MembershipForm, can_delete=False, extra=1, fields="__all__", ) data = { 'membership_set-TOTAL_FORMS': '1', 'membership_set-INITIAL_FORMS': '0', 'membership_set-MAX_NUM_FORMS': '', 'membership_set-0-date_joined_0': now.strftime('%Y-%m-%d'), 'membership_set-0-date_joined_1': now.strftime('%H:%M:%S'), 'initial-membership_set-0-date_joined': now.strftime('%Y-%m-%d %H:%M:%S'), 'membership_set-0-karma': '', } formset = FormSet(data, instance=person) self.assertTrue(formset.is_valid()) def test_inlineformset_factory_with_null_fk(self): # inlineformset_factory tests with fk having null=True. see #9462. # create some data that will exhibit the issue team = Team.objects.create(name="Red Vipers") Player(name="Timmy").save() Player(name="Bobby", team=team).save() PlayerInlineFormSet = inlineformset_factory(Team, Player, fields="__all__") formset = PlayerInlineFormSet() self.assertQuerysetEqual(formset.get_queryset(), []) formset = PlayerInlineFormSet(instance=team) players = formset.get_queryset() self.assertEqual(len(players), 1) player1, = players self.assertEqual(player1.team, team) self.assertEqual(player1.name, 'Bobby') def test_inlineformset_with_arrayfield(self): class SimpleArrayField(forms.CharField): """A proxy for django.contrib.postgres.forms.SimpleArrayField.""" def to_python(self, value): value = super().to_python(value) return value.split(',') if value else [] class BookForm(forms.ModelForm): title = SimpleArrayField() class Meta: model = Book fields = ('title',) BookFormSet = inlineformset_factory(Author, Book, form=BookForm) data = { 'book_set-TOTAL_FORMS': '3', 'book_set-INITIAL_FORMS': '0', 'book_set-MAX_NUM_FORMS': '', 'book_set-0-title': 'test1,test2', 'book_set-1-title': 'test1,test2', 'book_set-2-title': 'test3,test4', } author = Author.objects.create(name='test') formset = BookFormSet(data, instance=author) self.assertEqual(formset.errors, [{}, {'__all__': ['Please correct the duplicate values below.']}, {}]) def test_model_formset_with_custom_pk(self): # a formset for a Model that has a custom primary key that still needs to be # added to the formset automatically FormSet = modelformset_factory(ClassyMexicanRestaurant, fields=["tacos_are_yummy"]) self.assertEqual(sorted(FormSet().forms[0].fields), ['tacos_are_yummy', 'the_restaurant']) def test_model_formset_with_initial_model_instance(self): # has_changed should compare model instance and primary key # see #18898 FormSet = modelformset_factory(Poem, fields='__all__') john_milton = Poet(name="John Milton") john_milton.save() data = { 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-name': '', 'form-0-poet': str(john_milton.id), } formset = FormSet(initial=[{'poet': john_milton}], data=data) self.assertFalse(formset.extra_forms[0].has_changed()) def test_model_formset_with_initial_queryset(self): # has_changed should work with queryset and list of pk's # see #18898 FormSet = modelformset_factory(AuthorMeeting, fields='__all__') Author.objects.create(pk=1, name='Charles Baudelaire') data = { 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-name': '', 'form-0-created': '', 'form-0-authors': list(Author.objects.values_list('id', flat=True)), } formset = FormSet(initial=[{'authors': Author.objects.all()}], data=data) self.assertFalse(formset.extra_forms[0].has_changed()) def test_prevent_duplicates_from_with_the_same_formset(self): FormSet = modelformset_factory(Product, fields="__all__", extra=2) data = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-slug': 'red_car', 'form-1-slug': 'red_car', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for slug.']) FormSet = modelformset_factory(Price, fields="__all__", extra=2) data = { 'form-TOTAL_FORMS': 2, 'form-INITIAL_FORMS': 0, 'form-MAX_NUM_FORMS': '', 'form-0-price': '25', 'form-0-quantity': '7', 'form-1-price': '25', 'form-1-quantity': '7', } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual( formset._non_form_errors, ['Please correct the duplicate data for price and quantity, which must be unique.'] ) # Only the price field is specified, this should skip any unique checks since # the unique_together is not fulfilled. This will fail with a KeyError if broken. FormSet = modelformset_factory(Price, fields=("price",), extra=2) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-price': '24', 'form-1-price': '24', } formset = FormSet(data) self.assertTrue(formset.is_valid()) FormSet = inlineformset_factory(Author, Book, extra=0, fields="__all__") author = Author.objects.create(pk=1, name='Charles Baudelaire') Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels') Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal') Book.objects.create(pk=3, author=author, title='Flowers of Evil') book_ids = author.book_set.order_by('id').values_list('id', flat=True) data = { 'book_set-TOTAL_FORMS': '2', 'book_set-INITIAL_FORMS': '2', 'book_set-MAX_NUM_FORMS': '', 'book_set-0-title': 'The 2008 Election', 'book_set-0-author': str(author.id), 'book_set-0-id': str(book_ids[0]), 'book_set-1-title': 'The 2008 Election', 'book_set-1-author': str(author.id), 'book_set-1-id': str(book_ids[1]), } formset = FormSet(data=data, instance=author) self.assertFalse(formset.is_valid()) self.assertEqual(formset._non_form_errors, ['Please correct the duplicate data for title.']) self.assertEqual(formset.errors, [{}, {'__all__': ['Please correct the duplicate values below.']}]) FormSet = modelformset_factory(Post, fields="__all__", extra=2) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'blah', 'form-0-slug': 'Morning', 'form-0-subtitle': 'foo', 'form-0-posted': '2009-01-01', 'form-1-title': 'blah', 'form-1-slug': 'Morning in Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-01-01' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual( formset._non_form_errors, ['Please correct the duplicate data for title which must be unique for the date in posted.'] ) self.assertEqual( formset.errors, [{}, {'__all__': ['Please correct the duplicate values below.']}] ) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'foo', 'form-0-slug': 'Morning in Prague', 'form-0-subtitle': 'foo', 'form-0-posted': '2009-01-01', 'form-1-title': 'blah', 'form-1-slug': 'Morning in Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-08-02' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual( formset._non_form_errors, ['Please correct the duplicate data for slug which must be unique for the year in posted.'] ) data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', 'form-0-title': 'foo', 'form-0-slug': 'Morning in Prague', 'form-0-subtitle': 'rawr', 'form-0-posted': '2008-08-01', 'form-1-title': 'blah', 'form-1-slug': 'Prague', 'form-1-subtitle': 'rawr', 'form-1-posted': '2009-08-02' } formset = FormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual( formset._non_form_errors, ['Please correct the duplicate data for subtitle which must be unique for the month in posted.'] ) def test_prevent_change_outer_model_and_create_invalid_data(self): author = Author.objects.create(name='Charles') other_author = Author.objects.create(name='Walt') AuthorFormSet = modelformset_factory(Author, fields='__all__') data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '2', 'form-MAX_NUM_FORMS': '', 'form-0-id': str(author.id), 'form-0-name': 'Charles', 'form-1-id': str(other_author.id), # A model not in the formset's queryset. 'form-1-name': 'Changed name', } # This formset is only for Walt Whitman and shouldn't accept data for # other_author. formset = AuthorFormSet(data=data, queryset=Author.objects.filter(id__in=(author.id,))) self.assertTrue(formset.is_valid()) formset.save() # The name of other_author shouldn't be changed and new models aren't # created. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Charles>', '<Author: Walt>']) def test_validation_without_id(self): AuthorFormSet = modelformset_factory(Author, fields='__all__') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '', 'form-0-name': 'Charles', } formset = AuthorFormSet(data) self.assertEqual( formset.errors, [{'id': ['This field is required.']}], ) def test_validation_with_child_model_without_id(self): BetterAuthorFormSet = modelformset_factory(BetterAuthor, fields='__all__') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '', 'form-0-name': 'Charles', 'form-0-write_speed': '10', } formset = BetterAuthorFormSet(data) self.assertEqual( formset.errors, [{'author_ptr': ['This field is required.']}], ) def test_validation_with_invalid_id(self): AuthorFormSet = modelformset_factory(Author, fields='__all__') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '', 'form-0-id': 'abc', 'form-0-name': 'Charles', } formset = AuthorFormSet(data) self.assertEqual( formset.errors, [{'id': ['Select a valid choice. That choice is not one of the available choices.']}], ) def test_validation_with_nonexistent_id(self): AuthorFormSet = modelformset_factory(Author, fields='__all__') data = { 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '1', 'form-MAX_NUM_FORMS': '', 'form-0-id': '12345', 'form-0-name': 'Charles', } formset = AuthorFormSet(data) self.assertEqual( formset.errors, [{'id': ['Select a valid choice. That choice is not one of the available choices.']}], ) def test_initial_form_count_empty_data_raises_validation_error(self): AuthorFormSet = modelformset_factory(Author, fields='__all__') msg = 'ManagementForm data is missing or has been tampered with' with self.assertRaisesMessage(ValidationError, msg): AuthorFormSet({}).initial_form_count() class TestModelFormsetOverridesTroughFormMeta(TestCase): def test_modelformset_factory_widgets(self): widgets = { 'name': forms.TextInput(attrs={'class': 'poet'}) } PoetFormSet = modelformset_factory(Poet, fields="__all__", widgets=widgets) form = PoetFormSet.form() self.assertHTMLEqual( "%s" % form['name'], '<input id="id_name" maxlength="100" type="text" class="poet" name="name" required>' ) def test_inlineformset_factory_widgets(self): widgets = { 'title': forms.TextInput(attrs={'class': 'book'}) } BookFormSet = inlineformset_factory(Author, Book, widgets=widgets, fields="__all__") form = BookFormSet.form() self.assertHTMLEqual( "%s" % form['title'], '<input class="book" id="id_title" maxlength="100" name="title" type="text" required>' ) def test_modelformset_factory_labels_overrides(self): BookFormSet = modelformset_factory(Book, fields="__all__", labels={ 'title': 'Name' }) form = BookFormSet.form() self.assertHTMLEqual(form['title'].label_tag(), '<label for="id_title">Name:</label>') def test_inlineformset_factory_labels_overrides(self): BookFormSet = inlineformset_factory(Author, Book, fields="__all__", labels={ 'title': 'Name' }) form = BookFormSet.form() self.assertHTMLEqual(form['title'].label_tag(), '<label for="id_title">Name:</label>') def test_modelformset_factory_help_text_overrides(self): BookFormSet = modelformset_factory(Book, fields="__all__", help_texts={ 'title': 'Choose carefully.' }) form = BookFormSet.form() self.assertEqual(form['title'].help_text, 'Choose carefully.') def test_inlineformset_factory_help_text_overrides(self): BookFormSet = inlineformset_factory(Author, Book, fields="__all__", help_texts={ 'title': 'Choose carefully.' }) form = BookFormSet.form() self.assertEqual(form['title'].help_text, 'Choose carefully.') def test_modelformset_factory_error_messages_overrides(self): author = Author.objects.create(pk=1, name='Charles Baudelaire') BookFormSet = modelformset_factory(Book, fields="__all__", error_messages={ 'title': { 'max_length': 'Title too long!!' } }) form = BookFormSet.form(data={'title': 'Foo ' * 30, 'author': author.id}) form.full_clean() self.assertEqual(form.errors, {'title': ['Title too long!!']}) def test_inlineformset_factory_error_messages_overrides(self): author = Author.objects.create(pk=1, name='Charles Baudelaire') BookFormSet = inlineformset_factory(Author, Book, fields="__all__", error_messages={ 'title': { 'max_length': 'Title too long!!' } }) form = BookFormSet.form(data={'title': 'Foo ' * 30, 'author': author.id}) form.full_clean() self.assertEqual(form.errors, {'title': ['Title too long!!']}) def test_modelformset_factory_field_class_overrides(self): author = Author.objects.create(pk=1, name='Charles Baudelaire') BookFormSet = modelformset_factory(Book, fields="__all__", field_classes={ 'title': forms.SlugField, }) form = BookFormSet.form(data={'title': 'Foo ' * 30, 'author': author.id}) self.assertIs(Book._meta.get_field('title').__class__, models.CharField) self.assertIsInstance(form.fields['title'], forms.SlugField) def test_inlineformset_factory_field_class_overrides(self): author = Author.objects.create(pk=1, name='Charles Baudelaire') BookFormSet = inlineformset_factory(Author, Book, fields="__all__", field_classes={ 'title': forms.SlugField, }) form = BookFormSet.form(data={'title': 'Foo ' * 30, 'author': author.id}) self.assertIs(Book._meta.get_field('title').__class__, models.CharField) self.assertIsInstance(form.fields['title'], forms.SlugField)
4993387302756672ea4c5bde6e20491e1c6a4ab24a74987ed7b42c8e4d3b1b23
import datetime import uuid from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ('name',) def __str__(self): return self.name class BetterAuthor(Author): write_speed = models.IntegerField() class Book(models.Model): author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100) class Meta: unique_together = ( ('author', 'title'), ) ordering = ['id'] def __str__(self): return self.title def clean(self): # Ensure author is always accessible in clean method assert self.author.name is not None class BookWithCustomPK(models.Model): my_pk = models.DecimalField(max_digits=5, decimal_places=0, primary_key=True) author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100) def __str__(self): return '%s: %s' % (self.my_pk, self.title) class Editor(models.Model): name = models.CharField(max_length=100) class BookWithOptionalAltEditor(models.Model): author = models.ForeignKey(Author, models.CASCADE) # Optional secondary author alt_editor = models.ForeignKey(Editor, models.SET_NULL, blank=True, null=True) title = models.CharField(max_length=100) class Meta: unique_together = ( ('author', 'title', 'alt_editor'), ) def __str__(self): return self.title class AlternateBook(Book): notes = models.CharField(max_length=100) def __str__(self): return '%s - %s' % (self.title, self.notes) class AuthorMeeting(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author) created = models.DateField(editable=False) def __str__(self): return self.name class CustomPrimaryKey(models.Model): my_pk = models.CharField(max_length=10, primary_key=True) some_field = models.CharField(max_length=100) # models for inheritance tests. class Place(models.Model): name = models.CharField(max_length=50) city = models.CharField(max_length=50) def __str__(self): return self.name class Owner(models.Model): auto_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) place = models.ForeignKey(Place, models.CASCADE) def __str__(self): return "%s at %s" % (self.name, self.place) class Location(models.Model): place = models.ForeignKey(Place, models.CASCADE, unique=True) # this is purely for testing the data doesn't matter here :) lat = models.CharField(max_length=100) lon = models.CharField(max_length=100) class OwnerProfile(models.Model): owner = models.OneToOneField(Owner, models.CASCADE, primary_key=True) age = models.PositiveIntegerField() def __str__(self): return "%s is %d" % (self.owner.name, self.age) class Restaurant(Place): serves_pizza = models.BooleanField(default=False) class Product(models.Model): slug = models.SlugField(unique=True) def __str__(self): return self.slug class Price(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField() class Meta: unique_together = (('price', 'quantity'),) def __str__(self): return "%s for %s" % (self.quantity, self.price) class MexicanRestaurant(Restaurant): serves_tacos = models.BooleanField(default=False) class ClassyMexicanRestaurant(MexicanRestaurant): the_restaurant = models.OneToOneField(MexicanRestaurant, models.CASCADE, parent_link=True, primary_key=True) tacos_are_yummy = models.BooleanField(default=False) # models for testing unique_together validation when a fk is involved and # using inlineformset_factory. class Repository(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Revision(models.Model): repository = models.ForeignKey(Repository, models.CASCADE) revision = models.CharField(max_length=40) class Meta: unique_together = (("repository", "revision"),) def __str__(self): return "%s (%s)" % (self.revision, str(self.repository)) # models for testing callable defaults (see bug #7975). If you define a model # with a callable default value, you cannot rely on the initial value in a # form. class Person(models.Model): name = models.CharField(max_length=128) class Membership(models.Model): person = models.ForeignKey(Person, models.CASCADE) date_joined = models.DateTimeField(default=datetime.datetime.now) karma = models.IntegerField() # models for testing a null=True fk to a parent class Team(models.Model): name = models.CharField(max_length=100) class Player(models.Model): team = models.ForeignKey(Team, models.SET_NULL, null=True) name = models.CharField(max_length=100) def __str__(self): return self.name # Models for testing custom ModelForm save methods in formsets and inline formsets class Poet(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Poem(models.Model): poet = models.ForeignKey(Poet, models.CASCADE) name = models.CharField(max_length=100) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateField() def __str__(self): return self.title # Models for testing UUID primary keys class UUIDPKParent(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) class UUIDPKChild(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) parent = models.ForeignKey(UUIDPKParent, models.CASCADE) class ChildWithEditablePK(models.Model): name = models.CharField(max_length=255, primary_key=True) parent = models.ForeignKey(UUIDPKParent, models.CASCADE) class AutoPKChildOfUUIDPKParent(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey(UUIDPKParent, models.CASCADE) class AutoPKParent(models.Model): name = models.CharField(max_length=255) class UUIDPKChildOfAutoPKParent(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=255) parent = models.ForeignKey(AutoPKParent, models.CASCADE) class ParentWithUUIDAlternateKey(models.Model): uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=50) class ChildRelatedViaAK(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey(ParentWithUUIDAlternateKey, models.CASCADE, to_field='uuid')
f9be2f5d24f52091b3ea63d4e9c9393a0edd26622830b7b38fc5723bf11cc771
import datetime from copy import deepcopy from django.core.exceptions import FieldError, MultipleObjectsReturned from django.db import models, transaction from django.db.utils import IntegrityError from django.test import TestCase from django.utils.translation import gettext_lazy from .models import ( Article, Category, Child, ChildNullableParent, City, District, First, Parent, Record, Relation, Reporter, School, Student, Third, ToFieldChild, ) class ManyToOneTests(TestCase): def setUp(self): # Create a few Reporters. self.r = Reporter(first_name='John', last_name='Smith', email='[email protected]') self.r.save() self.r2 = Reporter(first_name='Paul', last_name='Jones', email='[email protected]') self.r2.save() # Create an Article. self.a = Article(headline="This is a test", pub_date=datetime.date(2005, 7, 27), reporter=self.r) self.a.save() def test_get(self): # Article objects have access to their related Reporter objects. r = self.a.reporter self.assertEqual(r.id, self.r.id) self.assertEqual((r.first_name, self.r.last_name), ('John', 'Smith')) def test_create(self): # You can also instantiate an Article by passing the Reporter's ID # instead of a Reporter object. a3 = Article(headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id) a3.save() self.assertEqual(a3.reporter.id, self.r.id) # Similarly, the reporter ID can be a string. a4 = Article(headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id)) a4.save() self.assertEqual(repr(a4.reporter), "<Reporter: John Smith>") def test_add(self): # Create an Article via the Reporter object. new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) self.assertEqual(repr(new_article), "<Article: John's second story>") self.assertEqual(new_article.reporter.id, self.r.id) # Create a new article, and add it to the article set. new_article2 = Article(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) msg = "<Article: Paul's story> instance isn't saved. Use bulk=False or save the object first." with self.assertRaisesMessage(ValueError, msg): self.r.article_set.add(new_article2) self.r.article_set.add(new_article2, bulk=False) self.assertEqual(new_article2.reporter.id, self.r.id) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>"] ) # Add the same article to a different article set - check that it moves. self.r2.article_set.add(new_article2) self.assertEqual(new_article2.reporter.id, self.r2.id) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) # Adding an object of the wrong type raises TypeError. with transaction.atomic(): with self.assertRaisesMessage(TypeError, "'Article' instance expected, got <Reporter:"): self.r.article_set.add(self.r2) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: This is a test>"] ) def test_set(self): new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) new_article2 = self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) # Assign the article to the reporter. new_article2.reporter = self.r new_article2.save() self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>") self.assertEqual(new_article2.reporter.id, self.r.id) self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r2.article_set.all(), []) # Set the article back again. self.r2.article_set.set([new_article, new_article2]) self.assertQuerysetEqual(self.r.article_set.all(), ["<Article: This is a test>"]) self.assertQuerysetEqual( self.r2.article_set.all(), ["<Article: John's second story>", "<Article: Paul's story>"] ) # Funny case - because the ForeignKey cannot be null, # existing members of the set must remain. self.r.article_set.set([new_article]) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: This is a test>"] ) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) def test_reverse_assignment_deprecation(self): msg = ( "Direct assignment to the reverse side of a related set is " "prohibited. Use article_set.set() instead." ) with self.assertRaisesMessage(TypeError, msg): self.r2.article_set = [] def test_assign(self): new_article = self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) new_article2 = self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) # Assign the article to the reporter directly using the descriptor. new_article2.reporter = self.r new_article2.save() self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>") self.assertEqual(new_article2.reporter.id, self.r.id) self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r2.article_set.all(), []) # Set the article back again using set() method. self.r2.article_set.set([new_article, new_article2]) self.assertQuerysetEqual(self.r.article_set.all(), ["<Article: This is a test>"]) self.assertQuerysetEqual( self.r2.article_set.all(), ["<Article: John's second story>", "<Article: Paul's story>"] ) # Because the ForeignKey cannot be null, existing members of the set # must remain. self.r.article_set.set([new_article]) self.assertQuerysetEqual( self.r.article_set.all(), ["<Article: John's second story>", "<Article: This is a test>"] ) self.assertQuerysetEqual(self.r2.article_set.all(), ["<Article: Paul's story>"]) # Reporter cannot be null - there should not be a clear or remove method self.assertFalse(hasattr(self.r2.article_set, 'remove')) self.assertFalse(hasattr(self.r2.article_set, 'clear')) def test_selects(self): self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) # Reporter objects have access to their related Article objects. self.assertQuerysetEqual(self.r.article_set.all(), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual(self.r.article_set.filter(headline__startswith='This'), ["<Article: This is a test>"]) self.assertEqual(self.r.article_set.count(), 2) self.assertEqual(self.r2.article_set.count(), 1) # Get articles by id self.assertQuerysetEqual(Article.objects.filter(id__exact=self.a.id), ["<Article: This is a test>"]) self.assertQuerysetEqual(Article.objects.filter(pk=self.a.id), ["<Article: This is a test>"]) # Query on an article property self.assertQuerysetEqual(Article.objects.filter(headline__startswith='This'), ["<Article: This is a test>"]) # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want. There's no limit. # Find all Articles for any Reporter whose first name is "John". self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John'), ["<Article: John's second story>", "<Article: This is a test>"] ) # Implied __exact also works self.assertQuerysetEqual( Article.objects.filter(reporter__first_name='John'), ["<Article: John's second story>", "<Article: This is a test>"] ) # Query twice over the related field. self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith'), ["<Article: John's second story>", "<Article: This is a test>"] ) # The underlying query only makes one join when a related table is referenced twice. queryset = Article.objects.filter(reporter__first_name__exact='John', reporter__last_name__exact='Smith') self.assertNumQueries(1, list, queryset) self.assertEqual(queryset.query.get_compiler(queryset.db).as_sql()[0].count('INNER JOIN'), 1) # The automatically joined table has a predictable name. self.assertQuerysetEqual( Article.objects.filter(reporter__first_name__exact='John').extra( where=["many_to_one_reporter.last_name='Smith'"]), ["<Article: John's second story>", "<Article: This is a test>"] ) # ... and should work fine with the string that comes out of forms.Form.cleaned_data self.assertQuerysetEqual( (Article.objects .filter(reporter__first_name__exact='John') .extra(where=["many_to_one_reporter.last_name='%s'" % 'Smith'])), ["<Article: John's second story>", "<Article: This is a test>"] ) # Find all Articles for a Reporter. # Use direct ID check, pk check, and object comparison self.assertQuerysetEqual( Article.objects.filter(reporter__id__exact=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__pk=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter=self.r.id), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter=self.r), [ "<Article: John's second story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__in=[self.r.id, self.r2.id]).distinct(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) self.assertQuerysetEqual( Article.objects.filter(reporter__in=[self.r, self.r2]).distinct(), [ "<Article: John's second story>", "<Article: Paul's story>", "<Article: This is a test>", ]) # You can also use a queryset instead of a literal list of instances. # The queryset must be reduced to a list of values using values(), # then converted into a query self.assertQuerysetEqual( Article.objects.filter( reporter__in=Reporter.objects.filter(first_name='John').values('pk').query ).distinct(), [ "<Article: John's second story>", "<Article: This is a test>", ]) def test_reverse_selects(self): a3 = Article.objects.create( headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) Article.objects.create( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) john_smith = ["<Reporter: John Smith>"] # Reporters can be queried self.assertQuerysetEqual(Reporter.objects.filter(id__exact=self.r.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(pk=self.r.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(first_name__startswith='John'), john_smith) # Reporters can query in opposite direction of ForeignKey definition self.assertQuerysetEqual(Reporter.objects.filter(article__id__exact=self.a.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__pk=self.a.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article=self.a.id), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article=self.a), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a.id, a3.id]).distinct(), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a.id, a3]).distinct(), john_smith) self.assertQuerysetEqual(Reporter.objects.filter(article__in=[self.a, a3]).distinct(), john_smith) self.assertQuerysetEqual( Reporter.objects.filter(article__headline__startswith='T'), ["<Reporter: John Smith>", "<Reporter: John Smith>"], ordered=False ) self.assertQuerysetEqual(Reporter.objects.filter(article__headline__startswith='T').distinct(), john_smith) # Counting in the opposite direction works in conjunction with distinct() self.assertEqual(Reporter.objects.filter(article__headline__startswith='T').count(), 2) self.assertEqual(Reporter.objects.filter(article__headline__startswith='T').distinct().count(), 1) # Queries can go round in circles. self.assertQuerysetEqual( Reporter.objects.filter(article__reporter__first_name__startswith='John'), [ "<Reporter: John Smith>", "<Reporter: John Smith>", "<Reporter: John Smith>", ], ordered=False ) self.assertQuerysetEqual( Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct(), john_smith ) self.assertQuerysetEqual(Reporter.objects.filter(article__reporter__exact=self.r).distinct(), john_smith) # Implied __exact also works. self.assertQuerysetEqual(Reporter.objects.filter(article__reporter=self.r).distinct(), john_smith) # It's possible to use values() calls across many-to-one relations. # (Note, too, that we clear the ordering here so as not to drag the # 'headline' field into the columns being used to determine uniqueness) d = {'reporter__first_name': 'John', 'reporter__last_name': 'Smith'} qs = Article.objects.filter( reporter=self.r, ).distinct().order_by().values('reporter__first_name', 'reporter__last_name') self.assertEqual([d], list(qs)) def test_select_related(self): # Article.objects.select_related().dates() works properly when there # are multiple Articles with the same date but different foreign-key # objects (Reporters). r1 = Reporter.objects.create(first_name='Mike', last_name='Royko', email='[email protected]') r2 = Reporter.objects.create(first_name='John', last_name='Kass', email='[email protected]') Article.objects.create(headline='First', pub_date=datetime.date(1980, 4, 23), reporter=r1) Article.objects.create(headline='Second', pub_date=datetime.date(1980, 4, 23), reporter=r2) self.assertEqual( list(Article.objects.select_related().dates('pub_date', 'day')), [datetime.date(1980, 4, 23), datetime.date(2005, 7, 27)] ) self.assertEqual( list(Article.objects.select_related().dates('pub_date', 'month')), [datetime.date(1980, 4, 1), datetime.date(2005, 7, 1)] ) self.assertEqual( list(Article.objects.select_related().dates('pub_date', 'year')), [datetime.date(1980, 1, 1), datetime.date(2005, 1, 1)] ) def test_delete(self): self.r.article_set.create(headline="John's second story", pub_date=datetime.date(2005, 7, 29)) self.r2.article_set.create(headline="Paul's story", pub_date=datetime.date(2006, 1, 17)) Article.objects.create(headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id) Article.objects.create( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id), ) # If you delete a reporter, his articles will be deleted. self.assertQuerysetEqual( Article.objects.all(), [ "<Article: Fourth article>", "<Article: John's second story>", "<Article: Paul's story>", "<Article: Third article>", "<Article: This is a test>", ] ) self.assertQuerysetEqual( Reporter.objects.order_by('first_name'), ["<Reporter: John Smith>", "<Reporter: Paul Jones>"] ) self.r2.delete() self.assertQuerysetEqual( Article.objects.all(), [ "<Article: Fourth article>", "<Article: John's second story>", "<Article: Third article>", "<Article: This is a test>", ] ) self.assertQuerysetEqual(Reporter.objects.order_by('first_name'), ["<Reporter: John Smith>"]) # You can delete using a JOIN in the query. Reporter.objects.filter(article__headline__startswith='This').delete() self.assertQuerysetEqual(Reporter.objects.all(), []) self.assertQuerysetEqual(Article.objects.all(), []) def test_explicit_fk(self): # Create a new Article with get_or_create using an explicit value # for a ForeignKey. a2, created = Article.objects.get_or_create( headline="John's second test", pub_date=datetime.date(2011, 5, 7), reporter_id=self.r.id, ) self.assertTrue(created) self.assertEqual(a2.reporter.id, self.r.id) # You can specify filters containing the explicit FK value. self.assertQuerysetEqual( Article.objects.filter(reporter_id__exact=self.r.id), ["<Article: John's second test>", "<Article: This is a test>"] ) # Create an Article by Paul for the same date. a3 = Article.objects.create( headline="Paul's commentary", pub_date=datetime.date(2011, 5, 7), reporter_id=self.r2.id, ) self.assertEqual(a3.reporter.id, self.r2.id) # Get should respect explicit foreign keys as well. msg = 'get() returned more than one Article -- it returned 2!' with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(reporter_id=self.r.id) self.assertEqual( repr(a3), repr(Article.objects.get(reporter_id=self.r2.id, pub_date=datetime.date(2011, 5, 7))) ) def test_deepcopy_and_circular_references(self): # Regression for #12876 -- Model methods that include queries that # recursive don't cause recursion depth problems under deepcopy. self.r.cached_query = Article.objects.filter(reporter=self.r) self.assertEqual(repr(deepcopy(self.r)), "<Reporter: John Smith>") def test_manager_class_caching(self): r1 = Reporter.objects.create(first_name='Mike') r2 = Reporter.objects.create(first_name='John') # Same twice self.assertIs(r1.article_set.__class__, r1.article_set.__class__) # Same as each other self.assertIs(r1.article_set.__class__, r2.article_set.__class__) def test_create_relation_with_gettext_lazy(self): reporter = Reporter.objects.create(first_name='John', last_name='Smith', email='[email protected]') lazy = gettext_lazy('test') reporter.article_set.create(headline=lazy, pub_date=datetime.date(2011, 6, 10)) notlazy = str(lazy) article = reporter.article_set.get() self.assertEqual(article.headline, notlazy) def test_values_list_exception(self): expected_message = "Cannot resolve keyword 'notafield' into field. Choices are: %s" reporter_fields = ', '.join(sorted(f.name for f in Reporter._meta.get_fields())) with self.assertRaisesMessage(FieldError, expected_message % reporter_fields): Article.objects.values_list('reporter__notafield') article_fields = ', '.join(['EXTRA'] + sorted(f.name for f in Article._meta.get_fields())) with self.assertRaisesMessage(FieldError, expected_message % article_fields): Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list('notafield') def test_fk_assignment_and_related_object_cache(self): # Tests of ForeignKey assignment and the related-object cache (see #6886). p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) # Look up the object again so that we get a "fresh" object. c = Child.objects.get(name="Child") p = c.parent # Accessing the related object again returns the exactly same object. self.assertIs(c.parent, p) # But if we kill the cache, we get a new object. del c._state.fields_cache['parent'] self.assertIsNot(c.parent, p) # Assigning a new object results in that object getting cached immediately. p2 = Parent.objects.create(name="Parent 2") c.parent = p2 self.assertIs(c.parent, p2) # Assigning None succeeds if field is null=True. p.bestchild = None self.assertIsNone(p.bestchild) # bestchild should still be None after saving. p.save() self.assertIsNone(p.bestchild) # bestchild should still be None after fetching the object again. p = Parent.objects.get(name="Parent") self.assertIsNone(p.bestchild) # Assigning None will not fail: Child.parent is null=False. setattr(c, "parent", None) # You also can't assign an object of the wrong type here msg = ( 'Cannot assign "<First: First object (1)>": "Child.parent" must ' 'be a "Parent" instance.' ) with self.assertRaisesMessage(ValueError, msg): setattr(c, "parent", First(id=1, second=1)) # You can assign None to Child.parent during object creation. Child(name='xyzzy', parent=None) # But when trying to save a Child with parent=None, the database will # raise IntegrityError. with self.assertRaises(IntegrityError), transaction.atomic(): Child.objects.create(name='xyzzy', parent=None) # Creation using keyword argument should cache the related object. p = Parent.objects.get(name="Parent") c = Child(parent=p) self.assertIs(c.parent, p) # Creation using keyword argument and unsaved related instance (#8070). p = Parent() msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'." with self.assertRaisesMessage(ValueError, msg): Child.objects.create(parent=p) msg = "save() prohibited to prevent data loss due to unsaved related object 'parent'." with self.assertRaisesMessage(ValueError, msg): ToFieldChild.objects.create(parent=p) # Creation using attname keyword argument and an id will cause the # related object to be fetched. p = Parent.objects.get(name="Parent") c = Child(parent_id=p.id) self.assertIsNot(c.parent, p) self.assertEqual(c.parent, p) def test_save_nullable_fk_after_parent(self): parent = Parent() child = ChildNullableParent(parent=parent) parent.save() child.save() child.refresh_from_db() self.assertEqual(child.parent, parent) def test_save_nullable_fk_after_parent_with_to_field(self): parent = Parent(name='jeff') child = ToFieldChild(parent=parent) parent.save() child.save() child.refresh_from_db() self.assertEqual(child.parent, parent) self.assertEqual(child.parent_id, parent.name) def test_fk_to_bigautofield(self): ch = City.objects.create(name='Chicago') District.objects.create(city=ch, name='Far South') District.objects.create(city=ch, name='North') ny = City.objects.create(name='New York', id=2 ** 33) District.objects.create(city=ny, name='Brooklyn') District.objects.create(city=ny, name='Manhattan') def test_multiple_foreignkeys(self): # Test of multiple ForeignKeys to the same model (bug #7125). c1 = Category.objects.create(name='First') c2 = Category.objects.create(name='Second') c3 = Category.objects.create(name='Third') r1 = Record.objects.create(category=c1) r2 = Record.objects.create(category=c1) r3 = Record.objects.create(category=c2) r4 = Record.objects.create(category=c2) r5 = Record.objects.create(category=c3) Relation.objects.create(left=r1, right=r2) Relation.objects.create(left=r3, right=r4) Relation.objects.create(left=r1, right=r3) Relation.objects.create(left=r5, right=r2) Relation.objects.create(left=r3, right=r2) q1 = Relation.objects.filter(left__category__name__in=['First'], right__category__name__in=['Second']) self.assertQuerysetEqual(q1, ["<Relation: First - Second>"]) q2 = Category.objects.filter(record__left_set__right__category__name='Second').order_by('name') self.assertQuerysetEqual(q2, ["<Category: First>", "<Category: Second>"]) p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) msg = 'Cannot assign "%r": "Child.parent" must be a "Parent" instance.' % c with self.assertRaisesMessage(ValueError, msg): Child.objects.create(name="Grandchild", parent=c) def test_fk_instantiation_outside_model(self): # Regression for #12190 -- Should be able to instantiate a FK outside # of a model, and interrogate its related field. cat = models.ForeignKey(Category, models.CASCADE) self.assertEqual('id', cat.remote_field.get_related_field().name) def test_relation_unsaved(self): # The <field>_set manager does not join on Null value fields (#17541) Third.objects.create(name='Third 1') Third.objects.create(name='Third 2') th = Third(name="testing") # The object isn't saved and thus the relation field is null - we won't even # execute a query in this case. with self.assertNumQueries(0): self.assertEqual(th.child_set.count(), 0) th.save() # Now the model is saved, so we will need to execute a query. with self.assertNumQueries(1): self.assertEqual(th.child_set.count(), 0) def test_related_object(self): public_school = School.objects.create(is_public=True) public_student = Student.objects.create(school=public_school) private_school = School.objects.create(is_public=False) private_student = Student.objects.create(school=private_school) # Only one school is available via all() due to the custom default manager. self.assertSequenceEqual(School.objects.all(), [public_school]) self.assertEqual(public_student.school, public_school) # Make sure the base manager is used so that a student can still access # its related school even if the default manager doesn't normally # allow it. self.assertEqual(private_student.school, private_school) School._meta.base_manager_name = 'objects' School._meta._expire_cache() try: private_student = Student.objects.get(pk=private_student.pk) with self.assertRaises(School.DoesNotExist): private_student.school finally: School._meta.base_manager_name = None School._meta._expire_cache() def test_hasattr_related_object(self): # The exception raised on attribute access when a related object # doesn't exist should be an instance of a subclass of `AttributeError` # refs #21563 self.assertFalse(hasattr(Article(), 'reporter')) def test_clear_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) city = City.objects.prefetch_related('districts').get(id=c.id) self.assertQuerysetEqual(city.districts.all(), ['<District: Ladida>']) city.districts.clear() self.assertQuerysetEqual(city.districts.all(), []) def test_remove_after_prefetch(self): c = City.objects.create(name='Musical City') d = District.objects.create(name='Ladida', city=c) city = City.objects.prefetch_related('districts').get(id=c.id) self.assertQuerysetEqual(city.districts.all(), ['<District: Ladida>']) city.districts.remove(d) self.assertQuerysetEqual(city.districts.all(), []) def test_add_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) d2 = District.objects.create(name='Ladidu') city = City.objects.prefetch_related('districts').get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.add(d2) self.assertEqual(city.districts.count(), 2) def test_set_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) d2 = District.objects.create(name='Ladidu') city = City.objects.prefetch_related('districts').get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.set([d2]) self.assertQuerysetEqual(city.districts.all(), ['<District: Ladidu>']) def test_add_then_remove_after_prefetch(self): c = City.objects.create(name='Musical City') District.objects.create(name='Ladida', city=c) d2 = District.objects.create(name='Ladidu') city = City.objects.prefetch_related('districts').get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.add(d2) self.assertEqual(city.districts.count(), 2) city.districts.remove(d2) self.assertEqual(city.districts.count(), 1) def test_cached_relation_invalidated_on_save(self): """ Model.save() invalidates stale ForeignKey relations after a primary key assignment. """ self.assertEqual(self.a.reporter, self.r) # caches a.reporter self.a.reporter_id = self.r2.pk self.a.save() self.assertEqual(self.a.reporter, self.r2) def test_cached_foreign_key_with_to_field_not_cleared_by_save(self): parent = Parent.objects.create(name='a') child = ToFieldChild.objects.create(parent=parent) with self.assertNumQueries(0): self.assertIs(child.parent, parent) def test_reverse_foreign_key_instance_to_field_caching(self): parent = Parent.objects.create(name='a') ToFieldChild.objects.create(parent=parent) child = parent.to_field_children.get() with self.assertNumQueries(0): self.assertIs(child.parent, parent)
7467524389d57be996fc1c2c6c4c307e1ae7082909c1b06f5bebb41b7ea410ea
""" Many-to-one relationships To define a many-to-one relationship, use ``ForeignKey()``. """ from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, models.CASCADE) class Meta: ordering = ('headline',) def __str__(self): return self.headline class City(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=50) def __str__(self): return self.name class District(models.Model): city = models.ForeignKey(City, models.CASCADE, related_name='districts', null=True) name = models.CharField(max_length=50) def __str__(self): return self.name # If ticket #1578 ever slips back in, these models will not be able to be # created (the field names being lowercased versions of their opposite classes # is important here). class First(models.Model): second = models.IntegerField() class Second(models.Model): first = models.ForeignKey(First, models.CASCADE, related_name='the_first') # Protect against repetition of #1839, #2415 and #2536. class Third(models.Model): name = models.CharField(max_length=20) third = models.ForeignKey('self', models.SET_NULL, null=True, related_name='child_set') class Parent(models.Model): name = models.CharField(max_length=20, unique=True) bestchild = models.ForeignKey('Child', models.SET_NULL, null=True, related_name='favored_by') class Child(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey(Parent, models.CASCADE) class ChildNullableParent(models.Model): parent = models.ForeignKey(Parent, models.CASCADE, null=True) class ToFieldChild(models.Model): parent = models.ForeignKey(Parent, models.CASCADE, to_field='name', related_name='to_field_children') # Multiple paths to the same model (#7110, #7125) class Category(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Record(models.Model): category = models.ForeignKey(Category, models.CASCADE) class Relation(models.Model): left = models.ForeignKey(Record, models.CASCADE, related_name='left_set') right = models.ForeignKey(Record, models.CASCADE, related_name='right_set') def __str__(self): return "%s - %s" % (self.left.category.name, self.right.category.name) # Test related objects visibility. class SchoolManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_public=True) class School(models.Model): is_public = models.BooleanField(default=False) objects = SchoolManager() class Student(models.Model): school = models.ForeignKey(School, models.CASCADE)
2dafa66d96ce6dc8dacd0ff45a553e55c9c70efcc1e848803fb2c4685df48cbe
import base64 import os import shutil import string import tempfile import unittest from datetime import timedelta from http import cookies from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.contrib.sessions.backends.cache import SessionStore as CacheSession from django.contrib.sessions.backends.cached_db import ( SessionStore as CacheDBSession, ) from django.contrib.sessions.backends.db import SessionStore as DatabaseSession from django.contrib.sessions.backends.file import SessionStore as FileSession from django.contrib.sessions.backends.signed_cookies import ( SessionStore as CookieSession, ) from django.contrib.sessions.exceptions import InvalidSessionKey from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sessions.models import Session from django.contrib.sessions.serializers import ( JSONSerializer, PickleSerializer, ) from django.core import management from django.core.cache import caches from django.core.cache.backends.base import InvalidCacheBackendError from django.core.exceptions import ImproperlyConfigured, SuspiciousOperation from django.http import HttpResponse from django.test import ( RequestFactory, TestCase, ignore_warnings, override_settings, ) from django.utils import timezone from .models import SessionStore as CustomDatabaseSession class SessionTestsMixin: # This does not inherit from TestCase to avoid any tests being run with this # class, which wouldn't work, and to allow different TestCase subclasses to # be used. backend = None # subclasses must specify def setUp(self): self.session = self.backend() def tearDown(self): # NB: be careful to delete any sessions created; stale sessions fill up # the /tmp (with some backends) and eventually overwhelm it after lots # of runs (think buildbots) self.session.delete() def test_new_session(self): self.assertIs(self.session.modified, False) self.assertIs(self.session.accessed, False) def test_get_empty(self): self.assertIsNone(self.session.get('cat')) def test_store(self): self.session['cat'] = "dog" self.assertIs(self.session.modified, True) self.assertEqual(self.session.pop('cat'), 'dog') def test_pop(self): self.session['some key'] = 'exists' # Need to reset these to pretend we haven't accessed it: self.accessed = False self.modified = False self.assertEqual(self.session.pop('some key'), 'exists') self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) self.assertIsNone(self.session.get('some key')) def test_pop_default(self): self.assertEqual(self.session.pop('some key', 'does not exist'), 'does not exist') self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_pop_default_named_argument(self): self.assertEqual(self.session.pop('some key', default='does not exist'), 'does not exist') self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_pop_no_default_keyerror_raised(self): with self.assertRaises(KeyError): self.session.pop('some key') def test_setdefault(self): self.assertEqual(self.session.setdefault('foo', 'bar'), 'bar') self.assertEqual(self.session.setdefault('foo', 'baz'), 'bar') self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) def test_update(self): self.session.update({'update key': 1}) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) self.assertEqual(self.session.get('update key', None), 1) def test_has_key(self): self.session['some key'] = 1 self.session.modified = False self.session.accessed = False self.assertIn('some key', self.session) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_values(self): self.assertEqual(list(self.session.values()), []) self.assertIs(self.session.accessed, True) self.session['some key'] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.values()), [1]) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_keys(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.keys()), ['x']) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_items(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.items()), [('x', 1)]) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, False) def test_clear(self): self.session['x'] = 1 self.session.modified = False self.session.accessed = False self.assertEqual(list(self.session.items()), [('x', 1)]) self.session.clear() self.assertEqual(list(self.session.items()), []) self.assertIs(self.session.accessed, True) self.assertIs(self.session.modified, True) def test_save(self): self.session.save() self.assertIs(self.session.exists(self.session.session_key), True) def test_delete(self): self.session.save() self.session.delete(self.session.session_key) self.assertIs(self.session.exists(self.session.session_key), False) def test_flush(self): self.session['foo'] = 'bar' self.session.save() prev_key = self.session.session_key self.session.flush() self.assertIs(self.session.exists(prev_key), False) self.assertNotEqual(self.session.session_key, prev_key) self.assertIsNone(self.session.session_key) self.assertIs(self.session.modified, True) self.assertIs(self.session.accessed, True) def test_cycle(self): self.session['a'], self.session['b'] = 'c', 'd' self.session.save() prev_key = self.session.session_key prev_data = list(self.session.items()) self.session.cycle_key() self.assertIs(self.session.exists(prev_key), False) self.assertNotEqual(self.session.session_key, prev_key) self.assertEqual(list(self.session.items()), prev_data) def test_cycle_with_no_session_cache(self): self.session['a'], self.session['b'] = 'c', 'd' self.session.save() prev_data = self.session.items() self.session = self.backend(self.session.session_key) self.assertIs(hasattr(self.session, '_session_cache'), False) self.session.cycle_key() self.assertCountEqual(self.session.items(), prev_data) def test_save_doesnt_clear_data(self): self.session['a'] = 'b' self.session.save() self.assertEqual(self.session['a'], 'b') def test_invalid_key(self): # Submitting an invalid session key (either by guessing, or if the db has # removed the key) results in a new key being generated. try: session = self.backend('1') session.save() self.assertNotEqual(session.session_key, '1') self.assertIsNone(session.get('cat')) session.delete() finally: # Some backends leave a stale cache entry for the invalid # session key; make sure that entry is manually deleted session.delete('1') def test_session_key_empty_string_invalid(self): """Falsey values (Such as an empty string) are rejected.""" self.session._session_key = '' self.assertIsNone(self.session.session_key) def test_session_key_too_short_invalid(self): """Strings shorter than 8 characters are rejected.""" self.session._session_key = '1234567' self.assertIsNone(self.session.session_key) def test_session_key_valid_string_saved(self): """Strings of length 8 and up are accepted and stored.""" self.session._session_key = '12345678' self.assertEqual(self.session.session_key, '12345678') def test_session_key_is_read_only(self): def set_session_key(session): session.session_key = session._get_new_session_key() with self.assertRaises(AttributeError): set_session_key(self.session) # Custom session expiry def test_default_expiry(self): # A normal session has a max age equal to settings self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) # So does a custom session with an idle expiration time of 0 (but it'll # expire at browser close) self.session.set_expiry(0) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) def test_custom_expiry_seconds(self): modification = timezone.now() self.session.set_expiry(10) date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_timedelta(self): modification = timezone.now() # Mock timezone.now, because set_expiry calls it on this code path. original_now = timezone.now try: timezone.now = lambda: modification self.session.set_expiry(timedelta(seconds=10)) finally: timezone.now = original_now date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_datetime(self): modification = timezone.now() self.session.set_expiry(modification + timedelta(seconds=10)) date = self.session.get_expiry_date(modification=modification) self.assertEqual(date, modification + timedelta(seconds=10)) age = self.session.get_expiry_age(modification=modification) self.assertEqual(age, 10) def test_custom_expiry_reset(self): self.session.set_expiry(None) self.session.set_expiry(10) self.session.set_expiry(None) self.assertEqual(self.session.get_expiry_age(), settings.SESSION_COOKIE_AGE) def test_get_expire_at_browser_close(self): # Tests get_expire_at_browser_close with different settings and different # set_expiry calls with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=False): self.session.set_expiry(10) self.assertIs(self.session.get_expire_at_browser_close(), False) self.session.set_expiry(0) self.assertIs(self.session.get_expire_at_browser_close(), True) self.session.set_expiry(None) self.assertIs(self.session.get_expire_at_browser_close(), False) with override_settings(SESSION_EXPIRE_AT_BROWSER_CLOSE=True): self.session.set_expiry(10) self.assertIs(self.session.get_expire_at_browser_close(), False) self.session.set_expiry(0) self.assertIs(self.session.get_expire_at_browser_close(), True) self.session.set_expiry(None) self.assertIs(self.session.get_expire_at_browser_close(), True) def test_decode(self): # Ensure we can decode what we encode data = {'a test key': 'a test value'} encoded = self.session.encode(data) self.assertEqual(self.session.decode(encoded), data) def test_decode_failure_logged_to_security(self): bad_encode = base64.b64encode(b'flaskdj:alkdjf').decode('ascii') with self.assertLogs('django.security.SuspiciousSession', 'WARNING') as cm: self.assertEqual({}, self.session.decode(bad_encode)) # The failed decode is logged. self.assertIn('corrupted', cm.output[0]) def test_actual_expiry(self): # this doesn't work with JSONSerializer (serializing timedelta) with override_settings(SESSION_SERIALIZER='django.contrib.sessions.serializers.PickleSerializer'): self.session = self.backend() # reinitialize after overriding settings # Regression test for #19200 old_session_key = None new_session_key = None try: self.session['foo'] = 'bar' self.session.set_expiry(-timedelta(seconds=10)) self.session.save() old_session_key = self.session.session_key # With an expiry date in the past, the session expires instantly. new_session = self.backend(self.session.session_key) new_session_key = new_session.session_key self.assertNotIn('foo', new_session) finally: self.session.delete(old_session_key) self.session.delete(new_session_key) def test_session_load_does_not_create_record(self): """ Loading an unknown session key does not create a session record. Creating session records on load is a DOS vulnerability. """ session = self.backend('someunknownkey') session.load() self.assertIsNone(session.session_key) self.assertIs(session.exists(session.session_key), False) # provided unknown key was cycled, not reused self.assertNotEqual(session.session_key, 'someunknownkey') def test_session_save_does_not_resurrect_session_logged_out_in_other_context(self): """ Sessions shouldn't be resurrected by a concurrent request. """ # Create new session. s1 = self.backend() s1['test_data'] = 'value1' s1.save(must_create=True) # Logout in another context. s2 = self.backend(s1.session_key) s2.delete() # Modify session in first context. s1['test_data'] = 'value2' with self.assertRaises(UpdateError): # This should throw an exception as the session is deleted, not # resurrect the session. s1.save() self.assertEqual(s1.load(), {}) class DatabaseSessionTests(SessionTestsMixin, TestCase): backend = DatabaseSession session_engine = 'django.contrib.sessions.backends.db' @property def model(self): return self.backend.get_model_class() def test_session_str(self): "Session repr should be the session key." self.session['x'] = 1 self.session.save() session_key = self.session.session_key s = self.model.objects.get(session_key=session_key) self.assertEqual(str(s), session_key) def test_session_get_decoded(self): """ Test we can use Session.get_decoded to retrieve data stored in normal way """ self.session['x'] = 1 self.session.save() s = self.model.objects.get(session_key=self.session.session_key) self.assertEqual(s.get_decoded(), {'x': 1}) def test_sessionmanager_save(self): """ Test SessionManager.save method """ # Create a session self.session['y'] = 1 self.session.save() s = self.model.objects.get(session_key=self.session.session_key) # Change it self.model.objects.save(s.session_key, {'y': 2}, s.expire_date) # Clear cache, so that it will be retrieved from DB del self.session._session_cache self.assertEqual(self.session['y'], 2) def test_clearsessions_command(self): """ Test clearsessions command for clearing expired sessions. """ self.assertEqual(0, self.model.objects.count()) # One object in the future self.session['foo'] = 'bar' self.session.set_expiry(3600) self.session.save() # One object in the past other_session = self.backend() other_session['foo'] = 'bar' other_session.set_expiry(-3600) other_session.save() # Two sessions are in the database before clearsessions... self.assertEqual(2, self.model.objects.count()) with override_settings(SESSION_ENGINE=self.session_engine): management.call_command('clearsessions') # ... and one is deleted. self.assertEqual(1, self.model.objects.count()) @override_settings(USE_TZ=True) class DatabaseSessionWithTimeZoneTests(DatabaseSessionTests): pass class CustomDatabaseSessionTests(DatabaseSessionTests): backend = CustomDatabaseSession session_engine = 'sessions_tests.models' custom_session_cookie_age = 60 * 60 * 24 # One day. def test_extra_session_field(self): # Set the account ID to be picked up by a custom session storage # and saved to a custom session model database column. self.session['_auth_user_id'] = 42 self.session.save() # Make sure that the customized create_model_instance() was called. s = self.model.objects.get(session_key=self.session.session_key) self.assertEqual(s.account_id, 42) # Make the session "anonymous". self.session.pop('_auth_user_id') self.session.save() # Make sure that save() on an existing session did the right job. s = self.model.objects.get(session_key=self.session.session_key) self.assertIsNone(s.account_id) def test_custom_expiry_reset(self): self.session.set_expiry(None) self.session.set_expiry(10) self.session.set_expiry(None) self.assertEqual(self.session.get_expiry_age(), self.custom_session_cookie_age) def test_default_expiry(self): self.assertEqual(self.session.get_expiry_age(), self.custom_session_cookie_age) self.session.set_expiry(0) self.assertEqual(self.session.get_expiry_age(), self.custom_session_cookie_age) class CacheDBSessionTests(SessionTestsMixin, TestCase): backend = CacheDBSession def test_exists_searches_cache_first(self): self.session.save() with self.assertNumQueries(0): self.assertIs(self.session.exists(self.session.session_key), True) # Some backends might issue a warning @ignore_warnings(module="django.core.cache.backends.base") def test_load_overlong_key(self): self.session._session_key = (string.ascii_letters + string.digits) * 20 self.assertEqual(self.session.load(), {}) @override_settings(SESSION_CACHE_ALIAS='sessions') def test_non_default_cache(self): # 21000 - CacheDB backend should respect SESSION_CACHE_ALIAS. with self.assertRaises(InvalidCacheBackendError): self.backend() @override_settings(USE_TZ=True) class CacheDBSessionWithTimeZoneTests(CacheDBSessionTests): pass # Don't need DB flushing for these tests, so can use unittest.TestCase as base class class FileSessionTests(SessionTestsMixin, unittest.TestCase): backend = FileSession def setUp(self): # Do file session tests in an isolated directory, and kill it after we're done. self.original_session_file_path = settings.SESSION_FILE_PATH self.temp_session_store = settings.SESSION_FILE_PATH = tempfile.mkdtemp() # Reset the file session backend's internal caches if hasattr(self.backend, '_storage_path'): del self.backend._storage_path super().setUp() def tearDown(self): super().tearDown() settings.SESSION_FILE_PATH = self.original_session_file_path shutil.rmtree(self.temp_session_store) @override_settings( SESSION_FILE_PATH='/if/this/directory/exists/you/have/a/weird/computer', ) def test_configuration_check(self): del self.backend._storage_path # Make sure the file backend checks for a good storage dir with self.assertRaises(ImproperlyConfigured): self.backend() def test_invalid_key_backslash(self): # Ensure we don't allow directory-traversal. # This is tested directly on _key_to_file, as load() will swallow # a SuspiciousOperation in the same way as an OSError - by creating # a new session, making it unclear whether the slashes were detected. with self.assertRaises(InvalidSessionKey): self.backend()._key_to_file("a\\b\\c") def test_invalid_key_forwardslash(self): # Ensure we don't allow directory-traversal with self.assertRaises(InvalidSessionKey): self.backend()._key_to_file("a/b/c") @override_settings( SESSION_ENGINE="django.contrib.sessions.backends.file", SESSION_COOKIE_AGE=0, ) def test_clearsessions_command(self): """ Test clearsessions command for clearing expired sessions. """ storage_path = self.backend._get_storage_path() file_prefix = settings.SESSION_COOKIE_NAME def count_sessions(): return len([ session_file for session_file in os.listdir(storage_path) if session_file.startswith(file_prefix) ]) self.assertEqual(0, count_sessions()) # One object in the future self.session['foo'] = 'bar' self.session.set_expiry(3600) self.session.save() # One object in the past other_session = self.backend() other_session['foo'] = 'bar' other_session.set_expiry(-3600) other_session.save() # One object in the present without an expiry (should be deleted since # its modification time + SESSION_COOKIE_AGE will be in the past when # clearsessions runs). other_session2 = self.backend() other_session2['foo'] = 'bar' other_session2.save() # Three sessions are in the filesystem before clearsessions... self.assertEqual(3, count_sessions()) management.call_command('clearsessions') # ... and two are deleted. self.assertEqual(1, count_sessions()) class CacheSessionTests(SessionTestsMixin, unittest.TestCase): backend = CacheSession # Some backends might issue a warning @ignore_warnings(module="django.core.cache.backends.base") def test_load_overlong_key(self): self.session._session_key = (string.ascii_letters + string.digits) * 20 self.assertEqual(self.session.load(), {}) def test_default_cache(self): self.session.save() self.assertIsNotNone(caches['default'].get(self.session.cache_key)) @override_settings(CACHES={ 'default': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', }, 'sessions': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'session', }, }, SESSION_CACHE_ALIAS='sessions') def test_non_default_cache(self): # Re-initialize the session backend to make use of overridden settings. self.session = self.backend() self.session.save() self.assertIsNone(caches['default'].get(self.session.cache_key)) self.assertIsNotNone(caches['sessions'].get(self.session.cache_key)) def test_create_and_save(self): self.session = self.backend() self.session.create() self.session.save() self.assertIsNotNone(caches['default'].get(self.session.cache_key)) class SessionMiddlewareTests(TestCase): request_factory = RequestFactory() @override_settings(SESSION_COOKIE_SECURE=True) def test_secure_session_cookie(self): request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) self.assertIs(response.cookies[settings.SESSION_COOKIE_NAME]['secure'], True) @override_settings(SESSION_COOKIE_HTTPONLY=True) def test_httponly_session_cookie(self): request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) self.assertIs(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], True) self.assertIn( cookies.Morsel._reserved['httponly'], str(response.cookies[settings.SESSION_COOKIE_NAME]) ) @override_settings(SESSION_COOKIE_SAMESITE='Strict') def test_samesite_session_cookie(self): request = self.request_factory.get('/') response = HttpResponse() middleware = SessionMiddleware() middleware.process_request(request) request.session['hello'] = 'world' response = middleware.process_response(request, response) self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['samesite'], 'Strict') @override_settings(SESSION_COOKIE_HTTPONLY=False) def test_no_httponly_session_cookie(self): request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) self.assertEqual(response.cookies[settings.SESSION_COOKIE_NAME]['httponly'], '') self.assertNotIn( cookies.Morsel._reserved['httponly'], str(response.cookies[settings.SESSION_COOKIE_NAME]) ) def test_session_save_on_500(self): request = self.request_factory.get('/') response = HttpResponse('Horrible error') response.status_code = 500 middleware = SessionMiddleware() # Simulate a request the modifies the session middleware.process_request(request) request.session['hello'] = 'world' # Handle the response through the middleware response = middleware.process_response(request, response) # The value wasn't saved above. self.assertNotIn('hello', request.session.load()) def test_session_update_error_redirect(self): path = '/foo/' request = self.request_factory.get(path) response = HttpResponse() middleware = SessionMiddleware() request.session = DatabaseSession() request.session.save(must_create=True) request.session.delete() msg = ( "The request's session was deleted before the request completed. " "The user may have logged out in a concurrent request, for example." ) with self.assertRaisesMessage(SuspiciousOperation, msg): # Handle the response through the middleware. It will try to save # the deleted session which will cause an UpdateError that's caught # and raised as a SuspiciousOperation. middleware.process_response(request, response) def test_session_delete_on_end(self): request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Before deleting, there has to be an existing cookie request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc' # Simulate a request that ends the session middleware.process_request(request) request.session.flush() # Handle the response through the middleware response = middleware.process_response(request, response) # The cookie was deleted, not recreated. # A deleted cookie header looks like: # Set-Cookie: sessionid=; expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/ self.assertEqual( 'Set-Cookie: {}=""; expires=Thu, 01 Jan 1970 00:00:00 GMT; ' 'Max-Age=0; Path=/'.format( settings.SESSION_COOKIE_NAME, ), str(response.cookies[settings.SESSION_COOKIE_NAME]) ) # SessionMiddleware sets 'Vary: Cookie' to prevent the 'Set-Cookie' # from being cached. self.assertEqual(response['Vary'], 'Cookie') @override_settings(SESSION_COOKIE_DOMAIN='.example.local', SESSION_COOKIE_PATH='/example/') def test_session_delete_on_end_with_custom_domain_and_path(self): request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Before deleting, there has to be an existing cookie request.COOKIES[settings.SESSION_COOKIE_NAME] = 'abc' # Simulate a request that ends the session middleware.process_request(request) request.session.flush() # Handle the response through the middleware response = middleware.process_response(request, response) # The cookie was deleted, not recreated. # A deleted cookie header with a custom domain and path looks like: # Set-Cookie: sessionid=; Domain=.example.local; # expires=Thu, 01 Jan 1970 00:00:00 GMT; Max-Age=0; # Path=/example/ self.assertEqual( 'Set-Cookie: {}=""; Domain=.example.local; expires=Thu, ' '01 Jan 1970 00:00:00 GMT; Max-Age=0; Path=/example/'.format( settings.SESSION_COOKIE_NAME, ), str(response.cookies[settings.SESSION_COOKIE_NAME]) ) def test_flush_empty_without_session_cookie_doesnt_set_cookie(self): request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Simulate a request that ends the session middleware.process_request(request) request.session.flush() # Handle the response through the middleware response = middleware.process_response(request, response) # A cookie should not be set. self.assertEqual(response.cookies, {}) # The session is accessed so "Vary: Cookie" should be set. self.assertEqual(response['Vary'], 'Cookie') def test_empty_session_saved(self): """ If a session is emptied of data but still has a key, it should still be updated. """ request = self.request_factory.get('/') response = HttpResponse('Session test') middleware = SessionMiddleware() # Set a session key and some data. middleware.process_request(request) request.session['foo'] = 'bar' # Handle the response through the middleware. response = middleware.process_response(request, response) self.assertEqual(tuple(request.session.items()), (('foo', 'bar'),)) # A cookie should be set, along with Vary: Cookie. self.assertIn( 'Set-Cookie: sessionid=%s' % request.session.session_key, str(response.cookies) ) self.assertEqual(response['Vary'], 'Cookie') # Empty the session data. del request.session['foo'] # Handle the response through the middleware. response = HttpResponse('Session test') response = middleware.process_response(request, response) self.assertEqual(dict(request.session.values()), {}) session = Session.objects.get(session_key=request.session.session_key) self.assertEqual(session.get_decoded(), {}) # While the session is empty, it hasn't been flushed so a cookie should # still be set, along with Vary: Cookie. self.assertGreater(len(request.session.session_key), 8) self.assertIn( 'Set-Cookie: sessionid=%s' % request.session.session_key, str(response.cookies) ) self.assertEqual(response['Vary'], 'Cookie') # Don't need DB flushing for these tests, so can use unittest.TestCase as base class class CookieSessionTests(SessionTestsMixin, unittest.TestCase): backend = CookieSession def test_save(self): """ This test tested exists() in the other session backends, but that doesn't make sense for us. """ pass def test_cycle(self): """ This test tested cycle_key() which would create a new session key for the same session data. But we can't invalidate previously signed cookies (other than letting them expire naturally) so testing for this behavior is meaningless. """ pass @unittest.expectedFailure def test_actual_expiry(self): # The cookie backend doesn't handle non-default expiry dates, see #19201 super().test_actual_expiry() def test_unpickling_exception(self): # signed_cookies backend should handle unpickle exceptions gracefully # by creating a new session self.assertEqual(self.session.serializer, JSONSerializer) self.session.save() self.session.serializer = PickleSerializer self.session.load() @unittest.skip("Cookie backend doesn't have an external store to create records in.") def test_session_load_does_not_create_record(self): pass @unittest.skip("CookieSession is stored in the client and there is no way to query it.") def test_session_save_does_not_resurrect_session_logged_out_in_other_context(self): pass
8b2a10b2520c0312a186428b4ba127e224b6133f2c782f656ef5b6cec215fe72
""" This custom Session model adds an extra column to store an account ID. In real-world applications, it gives you the option of querying the database for all active sessions for a particular account. """ from django.contrib.sessions.backends.db import SessionStore as DBStore from django.contrib.sessions.base_session import AbstractBaseSession from django.db import models class CustomSession(AbstractBaseSession): """ A session model with a column for an account ID. """ account_id = models.IntegerField(null=True, db_index=True) @classmethod def get_session_store_class(cls): return SessionStore class SessionStore(DBStore): """ A database session store, that handles updating the account ID column inside the custom session model. """ @classmethod def get_model_class(cls): return CustomSession def create_model_instance(self, data): obj = super().create_model_instance(data) try: account_id = int(data.get('_auth_user_id')) except (ValueError, TypeError): account_id = None obj.account_id = account_id return obj def get_session_cookie_age(self): return 60 * 60 * 24 # One day.
bf9941616c822e8f8f333fb6408de27ea83d6a2c90ef2f4e453509072f5aa5fd
from unittest import mock from urllib.parse import urlencode from django.contrib.sitemaps import ( SitemapNotFound, _get_sitemap_full_url, ping_google, ) from django.core.exceptions import ImproperlyConfigured from django.test import modify_settings, override_settings from .base import SitemapTestsBase class PingGoogleTests(SitemapTestsBase): @mock.patch('django.contrib.sitemaps.urlopen') def test_something(self, urlopen): ping_google() params = urlencode({'sitemap': 'https://example.com/sitemap-without-entries/sitemap.xml'}) full_url = 'https://www.google.com/webmasters/tools/ping?%s' % params urlopen.assert_called_with(full_url) def test_get_sitemap_full_url_global(self): self.assertEqual(_get_sitemap_full_url(None), 'https://example.com/sitemap-without-entries/sitemap.xml') @override_settings(ROOT_URLCONF='sitemaps_tests.urls.index_only') def test_get_sitemap_full_url_index(self): self.assertEqual(_get_sitemap_full_url(None), 'https://example.com/simple/index.xml') @override_settings(ROOT_URLCONF='sitemaps_tests.urls.empty') def test_get_sitemap_full_url_not_detected(self): msg = "You didn't provide a sitemap_url, and the sitemap URL couldn't be auto-detected." with self.assertRaisesMessage(SitemapNotFound, msg): _get_sitemap_full_url(None) def test_get_sitemap_full_url_exact_url(self): self.assertEqual(_get_sitemap_full_url('/foo.xml'), 'https://example.com/foo.xml') def test_get_sitemap_full_url_insecure(self): self.assertEqual( _get_sitemap_full_url('/foo.xml', sitemap_uses_https=False), 'http://example.com/foo.xml' ) @modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}) def test_get_sitemap_full_url_no_sites(self): msg = "ping_google requires django.contrib.sites, which isn't installed." with self.assertRaisesMessage(ImproperlyConfigured, msg): _get_sitemap_full_url(None)
3b061518785df35f9efbefec83801f55b993b625b660e5c671fe1a649167c577
from unittest import mock from django.core.management import call_command from .base import SitemapTestsBase @mock.patch('django.contrib.sitemaps.management.commands.ping_google.ping_google') class PingGoogleTests(SitemapTestsBase): def test_default(self, ping_google_func): call_command('ping_google') ping_google_func.assert_called_with(sitemap_url=None, sitemap_uses_https=True) def test_args(self, ping_google_func): call_command('ping_google', 'foo.xml', '--sitemap-uses-http') ping_google_func.assert_called_with(sitemap_url='foo.xml', sitemap_uses_https=False)
2d1739dbe26d36b35f30a9727c71973f5aac8676b38852f046c2928a729ea2b0
from django.apps import apps from django.contrib.sites.models import Site from django.core.cache import cache from django.test import TestCase, modify_settings, override_settings from .models import I18nTestModel, TestModel @modify_settings(INSTALLED_APPS={'append': 'django.contrib.sitemaps'}) @override_settings(ROOT_URLCONF='sitemaps_tests.urls.http') class SitemapTestsBase(TestCase): protocol = 'http' sites_installed = apps.is_installed('django.contrib.sites') domain = 'example.com' if sites_installed else 'testserver' @classmethod def setUpTestData(cls): # Create an object for sitemap content. TestModel.objects.create(name='Test Object') cls.i18n_model = I18nTestModel.objects.create(name='Test Object') def setUp(self): self.base_url = '%s://%s' % (self.protocol, self.domain) cache.clear() @classmethod def setUpClass(cls): super().setUpClass() # This cleanup is necessary because contrib.sites cache # makes tests interfere with each other, see #11505 Site.objects.clear_cache()
244dac3a31be6fcb5b373f18d8a27fb55fd6fefa55457ec537cf879d9bf3cb4d
import os from datetime import date from unittest import skipUnless from django.conf import settings from django.contrib.sitemaps import Sitemap from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.test import modify_settings, override_settings from django.utils.formats import localize from django.utils.translation import activate, deactivate from .base import SitemapTestsBase from .models import TestModel class HTTPSitemapTests(SitemapTestsBase): use_sitemap_err_msg = ( 'To use sitemaps, either enable the sites framework or pass a ' 'Site/RequestSite object in your view.' ) def test_simple_sitemap_index(self): "A simple sitemap index can be rendered" response = self.client.get('/simple/index.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap> </sitemapindex> """ % self.base_url self.assertXMLEqual(response.content.decode(), expected_content) def test_sitemap_not_callable(self): """A sitemap may not be callable.""" response = self.client.get('/simple-not-callable/index.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap> </sitemapindex> """ % self.base_url self.assertXMLEqual(response.content.decode(), expected_content) def test_paged_sitemap(self): """A sitemap may have multiple pages.""" response = self.client.get('/simple-paged/index.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap><loc>{0}/simple/sitemap-simple.xml</loc></sitemap><sitemap><loc>{0}/simple/sitemap-simple.xml?p=2</loc></sitemap> </sitemapindex> """.format(self.base_url) self.assertXMLEqual(response.content.decode(), expected_content) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(__file__), 'templates')], }]) def test_simple_sitemap_custom_index(self): "A simple sitemap index can be rendered with a custom template" response = self.client.get('/simple/custom-index.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <!-- This is a customised template --> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap><loc>%s/simple/sitemap-simple.xml</loc></sitemap> </sitemapindex> """ % self.base_url self.assertXMLEqual(response.content.decode(), expected_content) def test_simple_sitemap_section(self): "A simple sitemap section can be rendered" response = self.client.get('/simple/sitemap-simple.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url> </urlset> """ % (self.base_url, date.today()) self.assertXMLEqual(response.content.decode(), expected_content) def test_no_section(self): response = self.client.get('/simple/sitemap-simple2.xml') self.assertEqual(str(response.context['exception']), "No sitemap available for section: 'simple2'") self.assertEqual(response.status_code, 404) def test_empty_page(self): response = self.client.get('/simple/sitemap-simple.xml?p=0') self.assertEqual(str(response.context['exception']), 'Page 0 empty') self.assertEqual(response.status_code, 404) def test_page_not_int(self): response = self.client.get('/simple/sitemap-simple.xml?p=test') self.assertEqual(str(response.context['exception']), "No page 'test'") self.assertEqual(response.status_code, 404) def test_simple_sitemap(self): "A simple sitemap can be rendered" response = self.client.get('/simple/sitemap.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url> </urlset> """ % (self.base_url, date.today()) self.assertXMLEqual(response.content.decode(), expected_content) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(__file__), 'templates')], }]) def test_simple_custom_sitemap(self): "A simple sitemap can be rendered with a custom template" response = self.client.get('/simple/custom-sitemap.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <!-- This is a customised template --> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url><loc>%s/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url> </urlset> """ % (self.base_url, date.today()) self.assertXMLEqual(response.content.decode(), expected_content) def test_sitemap_last_modified(self): "Last-Modified header is set correctly" response = self.client.get('/lastmod/sitemap.xml') self.assertEqual(response['Last-Modified'], 'Wed, 13 Mar 2013 10:00:00 GMT') def test_sitemap_last_modified_date(self): """ The Last-Modified header should be support dates (without time). """ response = self.client.get('/lastmod/date-sitemap.xml') self.assertEqual(response['Last-Modified'], 'Wed, 13 Mar 2013 00:00:00 GMT') def test_sitemap_last_modified_tz(self): """ The Last-Modified header should be converted from timezone aware dates to GMT. """ response = self.client.get('/lastmod/tz-sitemap.xml') self.assertEqual(response['Last-Modified'], 'Wed, 13 Mar 2013 15:00:00 GMT') def test_sitemap_last_modified_missing(self): "Last-Modified header is missing when sitemap has no lastmod" response = self.client.get('/generic/sitemap.xml') self.assertFalse(response.has_header('Last-Modified')) def test_sitemap_last_modified_mixed(self): "Last-Modified header is omitted when lastmod not on all items" response = self.client.get('/lastmod-mixed/sitemap.xml') self.assertFalse(response.has_header('Last-Modified')) def test_sitemaps_lastmod_mixed_ascending_last_modified_missing(self): """ The Last-Modified header is omitted when lastmod isn't found in all sitemaps. Test sitemaps are sorted by lastmod in ascending order. """ response = self.client.get('/lastmod-sitemaps/mixed-ascending.xml') self.assertFalse(response.has_header('Last-Modified')) def test_sitemaps_lastmod_mixed_descending_last_modified_missing(self): """ The Last-Modified header is omitted when lastmod isn't found in all sitemaps. Test sitemaps are sorted by lastmod in descending order. """ response = self.client.get('/lastmod-sitemaps/mixed-descending.xml') self.assertFalse(response.has_header('Last-Modified')) def test_sitemaps_lastmod_ascending(self): """ The Last-Modified header is set to the most recent sitemap lastmod. Test sitemaps are sorted by lastmod in ascending order. """ response = self.client.get('/lastmod-sitemaps/ascending.xml') self.assertEqual(response['Last-Modified'], 'Sat, 20 Apr 2013 05:00:00 GMT') def test_sitemaps_lastmod_descending(self): """ The Last-Modified header is set to the most recent sitemap lastmod. Test sitemaps are sorted by lastmod in descending order. """ response = self.client.get('/lastmod-sitemaps/descending.xml') self.assertEqual(response['Last-Modified'], 'Sat, 20 Apr 2013 05:00:00 GMT') @skipUnless(settings.USE_I18N, "Internationalization is not enabled") @override_settings(USE_L10N=True) def test_localized_priority(self): "The priority value should not be localized (Refs #14164)" activate('fr') self.assertEqual('0,3', localize(0.3)) # Priorities haven't been rendered in localized format. response = self.client.get('/simple/sitemap.xml') self.assertContains(response, '<priority>0.5</priority>') self.assertContains(response, '<lastmod>%s</lastmod>' % date.today()) deactivate() @modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}) def test_requestsite_sitemap(self): # Hitting the flatpages sitemap without the sites framework installed # doesn't raise an exception. response = self.client.get('/simple/sitemap.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url><loc>http://testserver/location/</loc><lastmod>%s</lastmod><changefreq>never</changefreq><priority>0.5</priority></url> </urlset> """ % date.today() self.assertXMLEqual(response.content.decode(), expected_content) def test_sitemap_get_urls_no_site_1(self): """ Check we get ImproperlyConfigured if we don't pass a site object to Sitemap.get_urls and no Site objects exist """ Site.objects.all().delete() with self.assertRaisesMessage(ImproperlyConfigured, self.use_sitemap_err_msg): Sitemap().get_urls() @modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}) def test_sitemap_get_urls_no_site_2(self): """ Check we get ImproperlyConfigured when we don't pass a site object to Sitemap.get_urls if Site objects exists, but the sites framework is not actually installed. """ with self.assertRaisesMessage(ImproperlyConfigured, self.use_sitemap_err_msg): Sitemap().get_urls() def test_sitemap_item(self): """ Check to make sure that the raw item is included with each Sitemap.get_url() url result. """ test_sitemap = Sitemap() test_sitemap.items = TestModel.objects.order_by('pk').all def is_testmodel(url): return isinstance(url['item'], TestModel) item_in_url_info = all(map(is_testmodel, test_sitemap.get_urls())) self.assertTrue(item_in_url_info) def test_cached_sitemap_index(self): """ A cached sitemap index can be rendered (#2713). """ response = self.client.get('/cached/index.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <sitemap><loc>%s/cached/sitemap-simple.xml</loc></sitemap> </sitemapindex> """ % self.base_url self.assertXMLEqual(response.content.decode(), expected_content) def test_x_robots_sitemap(self): response = self.client.get('/simple/index.xml') self.assertEqual(response['X-Robots-Tag'], 'noindex, noodp, noarchive') response = self.client.get('/simple/sitemap.xml') self.assertEqual(response['X-Robots-Tag'], 'noindex, noodp, noarchive') def test_empty_sitemap(self): response = self.client.get('/empty/sitemap.xml') self.assertEqual(response.status_code, 200) @override_settings(LANGUAGES=(('en', 'English'), ('pt', 'Portuguese'))) def test_simple_i18nsitemap_index(self): "A simple i18n sitemap index can be rendered" response = self.client.get('/simple/i18n.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url><loc>{0}/en/i18n/testmodel/{1}/</loc><changefreq>never</changefreq><priority>0.5</priority></url><url><loc>{0}/pt/i18n/testmodel/{1}/</loc><changefreq>never</changefreq><priority>0.5</priority></url> </urlset> """.format(self.base_url, self.i18n_model.pk) self.assertXMLEqual(response.content.decode(), expected_content) def test_sitemap_without_entries(self): response = self.client.get('/sitemap-without-entries/sitemap.xml') expected_content = """<?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> </urlset>""" self.assertXMLEqual(response.content.decode(), expected_content)
a1993eedf601443c14d9bf1ce162b79db282b8fe8afa9005e5a22ad4ca58c009
"""Tests for django.db.utils.""" import unittest from django.core.exceptions import ImproperlyConfigured from django.db import DEFAULT_DB_ALIAS, connection from django.db.utils import ConnectionHandler, ProgrammingError, load_backend from django.test import SimpleTestCase, TestCase class ConnectionHandlerTests(SimpleTestCase): def test_connection_handler_no_databases(self): """ Empty DATABASES and empty 'default' settings default to the dummy backend. """ for DATABASES in ( {}, # Empty DATABASES setting. {'default': {}}, # Empty 'default' database. ): with self.subTest(DATABASES=DATABASES): self.assertImproperlyConfigured(DATABASES) def assertImproperlyConfigured(self, DATABASES): conns = ConnectionHandler(DATABASES) self.assertEqual(conns[DEFAULT_DB_ALIAS].settings_dict['ENGINE'], 'django.db.backends.dummy') msg = ( 'settings.DATABASES is improperly configured. Please supply the ' 'ENGINE value. Check settings documentation for more details.' ) with self.assertRaisesMessage(ImproperlyConfigured, msg): conns[DEFAULT_DB_ALIAS].ensure_connection() def test_no_default_database(self): DATABASES = {'other': {}} conns = ConnectionHandler(DATABASES) msg = "You must define a 'default' database." with self.assertRaisesMessage(ImproperlyConfigured, msg): conns['other'].ensure_connection() class DatabaseErrorWrapperTests(TestCase): @unittest.skipUnless(connection.vendor == 'postgresql', 'PostgreSQL test') def test_reraising_backend_specific_database_exception(self): with connection.cursor() as cursor: msg = 'table "X" does not exist' with self.assertRaisesMessage(ProgrammingError, msg) as cm: cursor.execute('DROP TABLE "X"') self.assertNotEqual(type(cm.exception), type(cm.exception.__cause__)) self.assertIsNotNone(cm.exception.__cause__) self.assertIsNotNone(cm.exception.__cause__.pgcode) self.assertIsNotNone(cm.exception.__cause__.pgerror) class LoadBackendTests(SimpleTestCase): def test_load_backend_invalid_name(self): msg = ( "'foo' isn't an available database backend.\n" "Try using 'django.db.backends.XXX', where XXX is one of:\n" " 'mysql', 'oracle', 'postgresql', 'sqlite3'" ) with self.assertRaisesMessage(ImproperlyConfigured, msg) as cm: load_backend('foo') self.assertEqual(str(cm.exception.__cause__), "No module named 'foo'")
859bcf6f5d93db6cc405b624518bc0d697d8fc78405266023a3b7901c1e675c4
import datetime from django.db import connection, models, transaction from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from .models import ( Award, AwardNote, Book, Child, Contact, Eaten, Email, File, Food, FooFile, FooFileProxy, FooImage, FooPhoto, House, Image, Item, Location, Login, OrderedPerson, OrgUnit, Person, Photo, PlayedWith, PlayedWithNote, Policy, Researcher, Toy, Version, ) # Can't run this test under SQLite, because you can't # get two connections to an in-memory database. @skipUnlessDBFeature('test_db_allows_multiple_connections') class DeleteLockingTest(TransactionTestCase): available_apps = ['delete_regress'] def setUp(self): # Create a second connection to the default database self.conn2 = connection.copy() self.conn2.set_autocommit(False) def tearDown(self): # Close down the second connection. self.conn2.rollback() self.conn2.close() def test_concurrent_delete(self): """Concurrent deletes don't collide and lock the database (#9479).""" with transaction.atomic(): Book.objects.create(id=1, pagecount=100) Book.objects.create(id=2, pagecount=200) Book.objects.create(id=3, pagecount=300) with transaction.atomic(): # Start a transaction on the main connection. self.assertEqual(3, Book.objects.count()) # Delete something using another database connection. with self.conn2.cursor() as cursor2: cursor2.execute("DELETE from delete_regress_book WHERE id = 1") self.conn2.commit() # In the same transaction on the main connection, perform a # queryset delete that covers the object deleted with the other # connection. This causes an infinite loop under MySQL InnoDB # unless we keep track of already deleted objects. Book.objects.filter(pagecount__lt=250).delete() self.assertEqual(1, Book.objects.count()) class DeleteCascadeTests(TestCase): def test_generic_relation_cascade(self): """ Django cascades deletes through generic-related objects to their reverse relations. """ person = Person.objects.create(name='Nelson Mandela') award = Award.objects.create(name='Nobel', content_object=person) AwardNote.objects.create(note='a peace prize', award=award) self.assertEqual(AwardNote.objects.count(), 1) person.delete() self.assertEqual(Award.objects.count(), 0) # first two asserts are just sanity checks, this is the kicker: self.assertEqual(AwardNote.objects.count(), 0) def test_fk_to_m2m_through(self): """ If an M2M relationship has an explicitly-specified through model, and some other model has an FK to that through model, deletion is cascaded from one of the participants in the M2M, to the through model, to its related model. """ juan = Child.objects.create(name='Juan') paints = Toy.objects.create(name='Paints') played = PlayedWith.objects.create(child=juan, toy=paints, date=datetime.date.today()) PlayedWithNote.objects.create(played=played, note='the next Jackson Pollock') self.assertEqual(PlayedWithNote.objects.count(), 1) paints.delete() self.assertEqual(PlayedWith.objects.count(), 0) # first two asserts just sanity checks, this is the kicker: self.assertEqual(PlayedWithNote.objects.count(), 0) def test_15776(self): policy = Policy.objects.create(pk=1, policy_number="1234") version = Version.objects.create(policy=policy) location = Location.objects.create(version=version) Item.objects.create(version=version, location=location) policy.delete() class DeleteCascadeTransactionTests(TransactionTestCase): available_apps = ['delete_regress'] def test_inheritance(self): """ Auto-created many-to-many through tables referencing a parent model are correctly found by the delete cascade when a child of that parent is deleted. Refs #14896. """ r = Researcher.objects.create() email = Email.objects.create( label="office-email", email_address="[email protected]" ) r.contacts.add(email) email.delete() def test_to_field(self): """ Cascade deletion works with ForeignKey.to_field set to non-PK. """ apple = Food.objects.create(name="apple") Eaten.objects.create(food=apple, meal="lunch") apple.delete() self.assertFalse(Food.objects.exists()) self.assertFalse(Eaten.objects.exists()) class LargeDeleteTests(TestCase): def test_large_deletes(self): "Regression for #13309 -- if the number of objects > chunk size, deletion still occurs" for x in range(300): Book.objects.create(pagecount=x + 100) # attach a signal to make sure we will not fast-delete def noop(*args, **kwargs): pass models.signals.post_delete.connect(noop, sender=Book) Book.objects.all().delete() models.signals.post_delete.disconnect(noop, sender=Book) self.assertEqual(Book.objects.count(), 0) class ProxyDeleteTest(TestCase): """ Tests on_delete behavior for proxy models. See #16128. """ def create_image(self): """Return an Image referenced by both a FooImage and a FooFile.""" # Create an Image test_image = Image() test_image.save() foo_image = FooImage(my_image=test_image) foo_image.save() # Get the Image instance as a File test_file = File.objects.get(pk=test_image.pk) foo_file = FooFile(my_file=test_file) foo_file.save() return test_image def test_delete_proxy(self): """ Deleting the *proxy* instance bubbles through to its non-proxy and *all* referring objects are deleted. """ self.create_image() Image.objects.all().delete() # An Image deletion == File deletion self.assertEqual(len(Image.objects.all()), 0) self.assertEqual(len(File.objects.all()), 0) # The Image deletion cascaded and *all* references to it are deleted. self.assertEqual(len(FooImage.objects.all()), 0) self.assertEqual(len(FooFile.objects.all()), 0) def test_delete_proxy_of_proxy(self): """ Deleting a proxy-of-proxy instance should bubble through to its proxy and non-proxy parents, deleting *all* referring objects. """ test_image = self.create_image() # Get the Image as a Photo test_photo = Photo.objects.get(pk=test_image.pk) foo_photo = FooPhoto(my_photo=test_photo) foo_photo.save() Photo.objects.all().delete() # A Photo deletion == Image deletion == File deletion self.assertEqual(len(Photo.objects.all()), 0) self.assertEqual(len(Image.objects.all()), 0) self.assertEqual(len(File.objects.all()), 0) # The Photo deletion should have cascaded and deleted *all* # references to it. self.assertEqual(len(FooPhoto.objects.all()), 0) self.assertEqual(len(FooFile.objects.all()), 0) self.assertEqual(len(FooImage.objects.all()), 0) def test_delete_concrete_parent(self): """ Deleting an instance of a concrete model should also delete objects referencing its proxy subclass. """ self.create_image() File.objects.all().delete() # A File deletion == Image deletion self.assertEqual(len(File.objects.all()), 0) self.assertEqual(len(Image.objects.all()), 0) # The File deletion should have cascaded and deleted *all* references # to it. self.assertEqual(len(FooFile.objects.all()), 0) self.assertEqual(len(FooImage.objects.all()), 0) def test_delete_proxy_pair(self): """ If a pair of proxy models are linked by an FK from one concrete parent to the other, deleting one proxy model cascade-deletes the other, and the deletion happens in the right order (not triggering an IntegrityError on databases unable to defer integrity checks). Refs #17918. """ # Create an Image (proxy of File) and FooFileProxy (proxy of FooFile, # which has an FK to File) image = Image.objects.create() as_file = File.objects.get(pk=image.pk) FooFileProxy.objects.create(my_file=as_file) Image.objects.all().delete() self.assertEqual(len(FooFileProxy.objects.all()), 0) def test_19187_values(self): msg = 'Cannot call delete() after .values() or .values_list()' with self.assertRaisesMessage(TypeError, msg): Image.objects.values().delete() with self.assertRaisesMessage(TypeError, msg): Image.objects.values_list().delete() class Ticket19102Tests(TestCase): """ Test different queries which alter the SELECT clause of the query. We also must be using a subquery for the deletion (that is, the original query has a join in it). The deletion should be done as "fast-path" deletion (that is, just one query for the .delete() call). Note that .values() is not tested here on purpose. .values().delete() doesn't work for non fast-path deletes at all. """ @classmethod def setUpTestData(cls): cls.o1 = OrgUnit.objects.create(name='o1') cls.o2 = OrgUnit.objects.create(name='o2') cls.l1 = Login.objects.create(description='l1', orgunit=cls.o1) cls.l2 = Login.objects.create(description='l2', orgunit=cls.o2) @skipUnlessDBFeature("update_can_self_select") def test_ticket_19102_annotate(self): with self.assertNumQueries(1): Login.objects.order_by('description').filter( orgunit__name__isnull=False ).annotate( n=models.Count('description') ).filter( n=1, pk=self.l1.pk ).delete() self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists()) self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists()) @skipUnlessDBFeature("update_can_self_select") def test_ticket_19102_extra(self): with self.assertNumQueries(1): Login.objects.order_by('description').filter( orgunit__name__isnull=False ).extra( select={'extraf': '1'} ).filter( pk=self.l1.pk ).delete() self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists()) self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists()) @skipUnlessDBFeature("update_can_self_select") @skipUnlessDBFeature('can_distinct_on_fields') def test_ticket_19102_distinct_on(self): # Both Login objs should have same description so that only the one # having smaller PK will be deleted. Login.objects.update(description='description') with self.assertNumQueries(1): Login.objects.distinct('description').order_by('pk').filter( orgunit__name__isnull=False ).delete() # Assumed that l1 which is created first has smaller PK. self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists()) self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists()) @skipUnlessDBFeature("update_can_self_select") def test_ticket_19102_select_related(self): with self.assertNumQueries(1): Login.objects.filter( pk=self.l1.pk ).filter( orgunit__name__isnull=False ).order_by( 'description' ).select_related('orgunit').delete() self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists()) self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists()) @skipUnlessDBFeature("update_can_self_select") def test_ticket_19102_defer(self): with self.assertNumQueries(1): Login.objects.filter( pk=self.l1.pk ).filter( orgunit__name__isnull=False ).order_by( 'description' ).only('id').delete() self.assertFalse(Login.objects.filter(pk=self.l1.pk).exists()) self.assertTrue(Login.objects.filter(pk=self.l2.pk).exists()) class DeleteTests(TestCase): def test_meta_ordered_delete(self): # When a subquery is performed by deletion code, the subquery must be # cleared of all ordering. There was a but that caused _meta ordering # to be used. Refs #19720. h = House.objects.create(address='Foo') OrderedPerson.objects.create(name='Jack', lives_in=h) OrderedPerson.objects.create(name='Bob', lives_in=h) OrderedPerson.objects.filter(lives_in__address='Foo').delete() self.assertEqual(OrderedPerson.objects.count(), 0) def test_foreign_key_delete_nullifies_correct_columns(self): """ With a model (Researcher) that has two foreign keys pointing to the same model (Contact), deleting an instance of the target model (contact1) nullifies the correct fields of Researcher. """ contact1 = Contact.objects.create(label='Contact 1') contact2 = Contact.objects.create(label='Contact 2') researcher1 = Researcher.objects.create( primary_contact=contact1, secondary_contact=contact2, ) researcher2 = Researcher.objects.create( primary_contact=contact2, secondary_contact=contact1, ) contact1.delete() researcher1.refresh_from_db() researcher2.refresh_from_db() self.assertIsNone(researcher1.primary_contact) self.assertEqual(researcher1.secondary_contact, contact2) self.assertEqual(researcher2.primary_contact, contact2) self.assertIsNone(researcher2.secondary_contact)
6fb0c32189694ccb88b25501eada380326d63ce66ac08533331cf2a7ddaee5a3
""" Testing using the Test Client The test client is a class that can act like a simple browser for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. ``Client`` objects are stateful - they will retain cookie (and thus session) details for the lifetime of the ``Client`` instance. This is not intended as a replacement for Twill, Selenium, or other browser automation frameworks - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ import itertools import tempfile from unittest import mock from django.contrib.auth.models import User from django.core import mail from django.http import HttpResponse from django.test import ( Client, RequestFactory, SimpleTestCase, TestCase, override_settings, ) from django.urls import reverse_lazy from .views import TwoArgException, get_view, post_view, trace_view @override_settings(ROOT_URLCONF='test_client.urls') class ClientTest(TestCase): @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_user(username='testclient', password='password') cls.u2 = User.objects.create_user(username='inactive', password='password', is_active=False) def test_get_view(self): "GET a view" # The data is ignored, but let's check it doesn't crash the system # anyway. data = {'var': '\xf2'} response = self.client.get('/get_view/', data) # Check some response details self.assertContains(response, 'This is a test') self.assertEqual(response.context['var'], '\xf2') self.assertEqual(response.templates[0].name, 'GET Template') def test_query_string_encoding(self): # WSGI requires latin-1 encoded strings. response = self.client.get('/get_view/?var=1\ufffd') self.assertEqual(response.context['var'], '1\ufffd') def test_get_data_none(self): msg = ( 'Cannot encode None in a query string. Did you mean to pass an ' 'empty string or omit the value?' ) with self.assertRaisesMessage(TypeError, msg): self.client.get('/get_view/', {'value': None}) def test_get_post_view(self): "GET a view that normally expects POSTs" response = self.client.get('/post_view/', {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, 'Empty GET Template') self.assertTemplateUsed(response, 'Empty GET Template') self.assertTemplateNotUsed(response, 'Empty POST Template') def test_empty_post(self): "POST an empty dictionary to a view" response = self.client.post('/post_view/', {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, 'Empty POST Template') self.assertTemplateNotUsed(response, 'Empty GET Template') self.assertTemplateUsed(response, 'Empty POST Template') def test_post(self): "POST some data to a view" post_data = { 'value': 37 } response = self.client.post('/post_view/', post_data) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.context['data'], '37') self.assertEqual(response.templates[0].name, 'POST Template') self.assertContains(response, 'Data received') def test_post_data_none(self): msg = ( 'Cannot encode None as POST data. Did you mean to pass an empty ' 'string or omit the value?' ) with self.assertRaisesMessage(TypeError, msg): self.client.post('/post_view/', {'value': None}) def test_json_serialization(self): """The test client serializes JSON data.""" methods = ('post', 'put', 'patch', 'delete') tests = ( ({'value': 37}, {'value': 37}), ([37, True], [37, True]), ((37, False), [37, False]), ) for method in methods: with self.subTest(method=method): for data, expected in tests: with self.subTest(data): client_method = getattr(self.client, method) method_name = method.upper() response = client_method('/json_view/', data, content_type='application/json') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['data'], expected) self.assertContains(response, 'Viewing %s page.' % method_name) def test_json_encoder_argument(self): """The test Client accepts a json_encoder.""" mock_encoder = mock.MagicMock() mock_encoding = mock.MagicMock() mock_encoder.return_value = mock_encoding mock_encoding.encode.return_value = '{"value": 37}' client = self.client_class(json_encoder=mock_encoder) # Vendored tree JSON content types are accepted. client.post('/json_view/', {'value': 37}, content_type='application/vnd.api+json') self.assertTrue(mock_encoder.called) self.assertTrue(mock_encoding.encode.called) def test_put(self): response = self.client.put('/put_view/', {'foo': 'bar'}) self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, 'PUT Template') self.assertEqual(response.context['data'], "{'foo': 'bar'}") self.assertEqual(response.context['Content-Length'], '14') def test_trace(self): """TRACE a view""" response = self.client.trace('/trace_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['method'], 'TRACE') self.assertEqual(response.templates[0].name, 'TRACE Template') def test_response_headers(self): "Check the value of HTTP headers returned in a response" response = self.client.get("/header_view/") self.assertEqual(response['X-DJANGO-TEST'], 'Slartibartfast') def test_response_attached_request(self): """ The returned response has a ``request`` attribute with the originating environ dict and a ``wsgi_request`` with the originating WSGIRequest. """ response = self.client.get("/header_view/") self.assertTrue(hasattr(response, 'request')) self.assertTrue(hasattr(response, 'wsgi_request')) for key, value in response.request.items(): self.assertIn(key, response.wsgi_request.environ) self.assertEqual(response.wsgi_request.environ[key], value) def test_response_resolver_match(self): """ The response contains a ResolverMatch instance. """ response = self.client.get('/header_view/') self.assertTrue(hasattr(response, 'resolver_match')) def test_response_resolver_match_redirect_follow(self): """ The response ResolverMatch instance contains the correct information when following redirects. """ response = self.client.get('/redirect_view/', follow=True) self.assertEqual(response.resolver_match.url_name, 'get_view') def test_response_resolver_match_regular_view(self): """ The response ResolverMatch instance contains the correct information when accessing a regular view. """ response = self.client.get('/get_view/') self.assertEqual(response.resolver_match.url_name, 'get_view') def test_raw_post(self): "POST raw data (with a content type) to a view" test_doc = """<?xml version="1.0" encoding="utf-8"?> <library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library> """ response = self.client.post('/raw_post_view/', test_doc, content_type='text/xml') self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Book template") self.assertEqual(response.content, b"Blink - Malcolm Gladwell") def test_insecure(self): "GET a URL through http" response = self.client.get('/secure_view/', secure=False) self.assertFalse(response.test_was_secure_request) self.assertEqual(response.test_server_port, '80') def test_secure(self): "GET a URL through https" response = self.client.get('/secure_view/', secure=True) self.assertTrue(response.test_was_secure_request) self.assertEqual(response.test_server_port, '443') def test_redirect(self): "GET a URL that redirects elsewhere" response = self.client.get('/redirect_view/') self.assertRedirects(response, '/get_view/') def test_redirect_with_query(self): "GET a URL that redirects with given GET parameters" response = self.client.get('/redirect_view/', {'var': 'value'}) self.assertRedirects(response, '/get_view/?var=value') def test_redirect_with_query_ordering(self): """assertRedirects() ignores the order of query string parameters.""" response = self.client.get('/redirect_view/', {'var': 'value', 'foo': 'bar'}) self.assertRedirects(response, '/get_view/?var=value&foo=bar') self.assertRedirects(response, '/get_view/?foo=bar&var=value') def test_permanent_redirect(self): "GET a URL that redirects permanently elsewhere" response = self.client.get('/permanent_redirect_view/') self.assertRedirects(response, '/get_view/', status_code=301) def test_temporary_redirect(self): "GET a URL that does a non-permanent redirect" response = self.client.get('/temporary_redirect_view/') self.assertRedirects(response, '/get_view/', status_code=302) def test_redirect_to_strange_location(self): "GET a URL that redirects to a non-200 page" response = self.client.get('/double_redirect_view/') # The response was a 302, and that the attempt to get the redirection # location returned 301 when retrieved self.assertRedirects(response, '/permanent_redirect_view/', target_status_code=301) def test_follow_redirect(self): "A URL that redirects can be followed to termination." response = self.client.get('/double_redirect_view/', follow=True) self.assertRedirects(response, '/get_view/', status_code=302, target_status_code=200) self.assertEqual(len(response.redirect_chain), 2) def test_follow_relative_redirect(self): "A URL with a relative redirect can be followed." response = self.client.get('/accounts/', follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request['PATH_INFO'], '/accounts/login/') def test_follow_relative_redirect_no_trailing_slash(self): "A URL with a relative redirect with no trailing slash can be followed." response = self.client.get('/accounts/no_trailing_slash', follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request['PATH_INFO'], '/accounts/login/') def test_follow_307_and_308_redirect(self): """ A 307 or 308 redirect preserves the request method after the redirect. """ methods = ('get', 'post', 'head', 'options', 'put', 'patch', 'delete', 'trace') codes = (307, 308) for method, code in itertools.product(methods, codes): with self.subTest(method=method, code=code): req_method = getattr(self.client, method) response = req_method('/redirect_view_%s/' % code, data={'value': 'test'}, follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request['PATH_INFO'], '/post_view/') self.assertEqual(response.request['REQUEST_METHOD'], method.upper()) def test_follow_307_and_308_preserves_post_data(self): for code in (307, 308): with self.subTest(code=code): response = self.client.post('/redirect_view_%s/' % code, data={'value': 'test'}, follow=True) self.assertContains(response, 'test is the value') def test_follow_307_and_308_preserves_put_body(self): for code in (307, 308): with self.subTest(code=code): response = self.client.put('/redirect_view_%s/?to=/put_view/' % code, data='a=b', follow=True) self.assertContains(response, 'a=b is the body') def test_follow_307_and_308_preserves_get_params(self): data = {'var': 30, 'to': '/get_view/'} for code in (307, 308): with self.subTest(code=code): response = self.client.get('/redirect_view_%s/' % code, data=data, follow=True) self.assertContains(response, '30 is the value') def test_redirect_http(self): "GET a URL that redirects to an http URI" response = self.client.get('/http_redirect_view/', follow=True) self.assertFalse(response.test_was_secure_request) def test_redirect_https(self): "GET a URL that redirects to an https URI" response = self.client.get('/https_redirect_view/', follow=True) self.assertTrue(response.test_was_secure_request) def test_notfound_response(self): "GET a URL that responds as '404:Not Found'" response = self.client.get('/bad_view/') self.assertContains(response, 'MAGIC', status_code=404) def test_valid_form(self): "POST valid data to a form" post_data = { 'text': 'Hello World', 'email': '[email protected]', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e') } response = self.client.post('/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Valid POST Template") def test_valid_form_with_hints(self): "GET a form, providing hints in the GET data" hints = { 'text': 'Hello World', 'multi': ('b', 'c', 'e') } response = self.client.get('/form_view/', data=hints) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Form GET Template") # The multi-value data has been rolled out ok self.assertContains(response, 'Select a valid choice.', 0) def test_incomplete_data_form(self): "POST incomplete data to a form" post_data = { 'text': 'Hello World', 'value': 37 } response = self.client.post('/form_view/', post_data) self.assertContains(response, 'This field is required.', 3) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'This field is required.') self.assertFormError(response, 'form', 'single', 'This field is required.') self.assertFormError(response, 'form', 'multi', 'This field is required.') def test_form_error(self): "POST erroneous data to a form" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e') } response = self.client.post('/form_view/', post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'Enter a valid email address.') def test_valid_form_with_template(self): "POST valid data to a form using multiple templates" post_data = { 'text': 'Hello World', 'email': '[email protected]', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e') } response = self.client.post('/form_view_with_template/', post_data) self.assertContains(response, 'POST data OK') self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Valid POST Template") def test_incomplete_data_form_with_template(self): "POST incomplete data to a form using multiple templates" post_data = { 'text': 'Hello World', 'value': 37 } response = self.client.post('/form_view_with_template/', post_data) self.assertContains(response, 'POST data has errors') self.assertTemplateUsed(response, 'form_view.html') self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'This field is required.') self.assertFormError(response, 'form', 'single', 'This field is required.') self.assertFormError(response, 'form', 'multi', 'This field is required.') def test_form_error_with_template(self): "POST erroneous data to a form using multiple templates" post_data = { 'text': 'Hello World', 'email': 'not an email address', 'value': 37, 'single': 'b', 'multi': ('b', 'c', 'e') } response = self.client.post('/form_view_with_template/', post_data) self.assertContains(response, 'POST data has errors') self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, 'base.html') self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError(response, 'form', 'email', 'Enter a valid email address.') def test_unknown_page(self): "GET an invalid URL" response = self.client.get('/unknown_view/') # The response was a 404 self.assertEqual(response.status_code, 404) def test_url_parameters(self): "Make sure that URL ;-parameters are not stripped." response = self.client.get('/unknown_view/;some-parameter') # The path in the response includes it (ignore that it's a 404) self.assertEqual(response.request['PATH_INFO'], '/unknown_view/;some-parameter') def test_view_with_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') @override_settings( INSTALLED_APPS=['django.contrib.auth'], SESSION_ENGINE='django.contrib.sessions.backends.file', ) def test_view_with_login_when_sessions_app_is_not_installed(self): self.test_view_with_login() def test_view_with_force_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_method_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_method_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_method_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/login_protected_method_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_method_force_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_method_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_method_view/') # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get('/login_protected_method_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_login_and_custom_redirect(self): "Request a page that is protected with @login_required(redirect_field_name='redirect_to')" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view_custom_redirect/') self.assertRedirects(response, '/accounts/login/?redirect_to=/login_protected_view_custom_redirect/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Request a page that requires a login response = self.client.get('/login_protected_view_custom_redirect/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_force_login_and_custom_redirect(self): """ Request a page that is protected with @login_required(redirect_field_name='redirect_to') """ # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view_custom_redirect/') self.assertRedirects(response, '/accounts/login/?redirect_to=/login_protected_view_custom_redirect/') # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get('/login_protected_view_custom_redirect/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') def test_view_with_bad_login(self): "Request a page that is protected with @login, but use bad credentials" login = self.client.login(username='otheruser', password='nopassword') self.assertFalse(login) def test_view_with_inactive_login(self): """ An inactive user may login if the authenticate backend allows it. """ credentials = {'username': 'inactive', 'password': 'password'} self.assertFalse(self.client.login(**credentials)) with self.settings(AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.AllowAllUsersModelBackend']): self.assertTrue(self.client.login(**credentials)) @override_settings( AUTHENTICATION_BACKENDS=[ 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth.backends.AllowAllUsersModelBackend', ] ) def test_view_with_inactive_force_login(self): "Request a page that is protected with @login, but use an inactive login" # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') # Log in self.client.force_login(self.u2, backend='django.contrib.auth.backends.AllowAllUsersModelBackend') # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'inactive') def test_logout(self): "Request a logout after logging in" # Log in self.client.login(username='testclient', password='password') # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') # Log out self.client.logout() # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') def test_logout_with_force_login(self): "Request a logout after logging in" # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') # Log out self.client.logout() # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') @override_settings( AUTHENTICATION_BACKENDS=[ 'django.contrib.auth.backends.ModelBackend', 'test_client.auth_backends.TestClientBackend', ], ) def test_force_login_with_backend(self): """ Request a page that is protected with @login_required when using force_login() and passing a backend. """ # Get the page without logging in. Should result in 302. response = self.client.get('/login_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/') # Log in self.client.force_login(self.u1, backend='test_client.auth_backends.TestClientBackend') self.assertEqual(self.u1.backend, 'test_client.auth_backends.TestClientBackend') # Request a page that requires a login response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') @override_settings( AUTHENTICATION_BACKENDS=[ 'django.contrib.auth.backends.ModelBackend', 'test_client.auth_backends.TestClientBackend', ], ) def test_force_login_without_backend(self): """ force_login() without passing a backend and with multiple backends configured should automatically use the first backend. """ self.client.force_login(self.u1) response = self.client.get('/login_protected_view/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['user'].username, 'testclient') self.assertEqual(self.u1.backend, 'django.contrib.auth.backends.ModelBackend') @override_settings(AUTHENTICATION_BACKENDS=[ 'test_client.auth_backends.BackendWithoutGetUserMethod', 'django.contrib.auth.backends.ModelBackend', ]) def test_force_login_with_backend_missing_get_user(self): """ force_login() skips auth backends without a get_user() method. """ self.client.force_login(self.u1) self.assertEqual(self.u1.backend, 'django.contrib.auth.backends.ModelBackend') @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies") def test_logout_cookie_sessions(self): self.test_logout() def test_view_with_permissions(self): "Request a page that is protected with @permission_required" # Get the page without logging in. Should result in 302. response = self.client.get('/permission_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/permission_protected_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Log in with wrong permissions. Should result in 302. response = self.client.get('/permission_protected_view/') self.assertRedirects(response, '/accounts/login/?next=/permission_protected_view/') # TODO: Log in with right permissions and request the page again def test_view_with_permissions_exception(self): "Request a page that is protected with @permission_required but raises an exception" # Get the page without logging in. Should result in 403. response = self.client.get('/permission_protected_view_exception/') self.assertEqual(response.status_code, 403) # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Log in with wrong permissions. Should result in 403. response = self.client.get('/permission_protected_view_exception/') self.assertEqual(response.status_code, 403) def test_view_with_method_permissions(self): "Request a page that is protected with a @permission_required method" # Get the page without logging in. Should result in 302. response = self.client.get('/permission_protected_method_view/') self.assertRedirects(response, '/accounts/login/?next=/permission_protected_method_view/') # Log in login = self.client.login(username='testclient', password='password') self.assertTrue(login, 'Could not log in') # Log in with wrong permissions. Should result in 302. response = self.client.get('/permission_protected_method_view/') self.assertRedirects(response, '/accounts/login/?next=/permission_protected_method_view/') # TODO: Log in with right permissions and request the page again def test_external_redirect(self): response = self.client.get('/django_project_redirect/') self.assertRedirects(response, 'https://www.djangoproject.com/', fetch_redirect_response=False) def test_external_redirect_with_fetch_error_msg(self): """ assertRedirects without fetch_redirect_response=False raises a relevant ValueError rather than a non-descript AssertionError. """ response = self.client.get('/django_project_redirect/') msg = ( "The test client is unable to fetch remote URLs (got " "https://www.djangoproject.com/). If the host is served by Django, " "add 'www.djangoproject.com' to ALLOWED_HOSTS. " "Otherwise, use assertRedirects(..., fetch_redirect_response=False)." ) with self.assertRaisesMessage(ValueError, msg): self.assertRedirects(response, 'https://www.djangoproject.com/') def test_session_modifying_view(self): "Request a page that modifies the session" # Session value isn't set initially with self.assertRaises(KeyError): self.client.session['tobacconist'] self.client.post('/session_view/') # The session was modified self.assertEqual(self.client.session['tobacconist'], 'hovercraft') @override_settings( INSTALLED_APPS=[], SESSION_ENGINE='django.contrib.sessions.backends.file', ) def test_sessions_app_is_not_installed(self): self.test_session_modifying_view() @override_settings( INSTALLED_APPS=[], SESSION_ENGINE='django.contrib.sessions.backends.nonexistent', ) def test_session_engine_is_invalid(self): with self.assertRaisesMessage(ImportError, 'nonexistent'): self.test_session_modifying_view() def test_view_with_exception(self): "Request a page that is known to throw an error" with self.assertRaises(KeyError): self.client.get("/broken_view/") def test_exc_info(self): client = Client(raise_request_exception=False) response = client.get("/broken_view/") self.assertEqual(response.status_code, 500) exc_type, exc_value, exc_traceback = response.exc_info self.assertIs(exc_type, KeyError) self.assertIsInstance(exc_value, KeyError) self.assertEqual(str(exc_value), "'Oops! Looks like you wrote some bad code.'") self.assertIsNotNone(exc_traceback) def test_exc_info_none(self): response = self.client.get("/get_view/") self.assertIsNone(response.exc_info) def test_mail_sending(self): "Mail is redirected to a dummy outbox during test setup" response = self.client.get('/mail_sending_view/') self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'Test message') self.assertEqual(mail.outbox[0].body, 'This is a test email') self.assertEqual(mail.outbox[0].from_email, '[email protected]') self.assertEqual(mail.outbox[0].to[0], '[email protected]') self.assertEqual(mail.outbox[0].to[1], '[email protected]') def test_reverse_lazy_decodes(self): "reverse_lazy() works in the test client" data = {'var': 'data'} response = self.client.get(reverse_lazy('get_view'), data) # Check some response details self.assertContains(response, 'This is a test') def test_relative_redirect(self): response = self.client.get('/accounts/') self.assertRedirects(response, '/accounts/login/') def test_relative_redirect_no_trailing_slash(self): response = self.client.get('/accounts/no_trailing_slash') self.assertRedirects(response, '/accounts/login/') def test_mass_mail_sending(self): "Mass mail is redirected to a dummy outbox during test setup" response = self.client.get('/mass_mail_sending_view/') self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, 'First Test message') self.assertEqual(mail.outbox[0].body, 'This is the first test email') self.assertEqual(mail.outbox[0].from_email, '[email protected]') self.assertEqual(mail.outbox[0].to[0], '[email protected]') self.assertEqual(mail.outbox[0].to[1], '[email protected]') self.assertEqual(mail.outbox[1].subject, 'Second Test message') self.assertEqual(mail.outbox[1].body, 'This is the second test email') self.assertEqual(mail.outbox[1].from_email, '[email protected]') self.assertEqual(mail.outbox[1].to[0], '[email protected]') self.assertEqual(mail.outbox[1].to[1], '[email protected]') def test_exception_following_nested_client_request(self): """ A nested test client request shouldn't clobber exception signals from the outer client request. """ with self.assertRaisesMessage(Exception, 'exception message'): self.client.get('/nesting_exception_view/') def test_response_raises_multi_arg_exception(self): """A request may raise an exception with more than one required arg.""" with self.assertRaises(TwoArgException) as cm: self.client.get('/two_arg_exception/') self.assertEqual(cm.exception.args, ('one', 'two')) def test_uploading_temp_file(self): with tempfile.TemporaryFile() as test_file: response = self.client.post('/upload_view/', data={'temp_file': test_file}) self.assertEqual(response.content, b'temp_file') def test_uploading_named_temp_file(self): test_file = tempfile.NamedTemporaryFile() response = self.client.post('/upload_view/', data={'named_temp_file': test_file}) self.assertEqual(response.content, b'named_temp_file') @override_settings( MIDDLEWARE=['django.middleware.csrf.CsrfViewMiddleware'], ROOT_URLCONF='test_client.urls', ) class CSRFEnabledClientTests(SimpleTestCase): def test_csrf_enabled_client(self): "A client can be instantiated with CSRF checks enabled" csrf_client = Client(enforce_csrf_checks=True) # The normal client allows the post response = self.client.post('/post_view/', {}) self.assertEqual(response.status_code, 200) # The CSRF-enabled client rejects it response = csrf_client.post('/post_view/', {}) self.assertEqual(response.status_code, 403) class CustomTestClient(Client): i_am_customized = "Yes" class CustomTestClientTest(SimpleTestCase): client_class = CustomTestClient def test_custom_test_client(self): """A test case can specify a custom class for self.client.""" self.assertIs(hasattr(self.client, "i_am_customized"), True) def _generic_view(request): return HttpResponse(status=200) @override_settings(ROOT_URLCONF='test_client.urls') class RequestFactoryTest(SimpleTestCase): """Tests for the request factory.""" # A mapping between names of HTTP/1.1 methods and their test views. http_methods_and_views = ( ('get', get_view), ('post', post_view), ('put', _generic_view), ('patch', _generic_view), ('delete', _generic_view), ('head', _generic_view), ('options', _generic_view), ('trace', trace_view), ) request_factory = RequestFactory() def test_request_factory(self): """The request factory implements all the HTTP/1.1 methods.""" for method_name, view in self.http_methods_and_views: method = getattr(self.request_factory, method_name) request = method('/somewhere/') response = view(request) self.assertEqual(response.status_code, 200) def test_get_request_from_factory(self): """ The request factory returns a templated response for a GET request. """ request = self.request_factory.get('/somewhere/') response = get_view(request) self.assertContains(response, 'This is a test') def test_trace_request_from_factory(self): """The request factory returns an echo response for a TRACE request.""" url_path = '/somewhere/' request = self.request_factory.trace(url_path) response = trace_view(request) protocol = request.META["SERVER_PROTOCOL"] echoed_request_line = "TRACE {} {}".format(url_path, protocol) self.assertContains(response, echoed_request_line)
2db50f839bf7962019b93abcd9db0572b0f8eb3fc06b38408573a9136fe78fdc
from django.test import SimpleTestCase from django.test.client import FakePayload class FakePayloadTests(SimpleTestCase): def test_write_after_read(self): payload = FakePayload() payload.read() msg = "Unable to write a payload after it's been read" with self.assertRaisesMessage(ValueError, msg): payload.write(b'abc')
6f25522ec5c8e15232290b0657d7cb08708d9f1e8b0f99a2f6e6164f16e52947
from django.contrib.auth import views as auth_views from django.urls import path from django.views.generic import RedirectView from . import views urlpatterns = [ path('upload_view/', views.upload_view, name='upload_view'), path('get_view/', views.get_view, name='get_view'), path('post_view/', views.post_view), path('put_view/', views.put_view), path('trace_view/', views.trace_view), path('header_view/', views.view_with_header), path('raw_post_view/', views.raw_post_view), path('redirect_view/', views.redirect_view), path('redirect_view_307/', views.method_saving_307_redirect_view), path('redirect_view_308/', views.method_saving_308_redirect_view), path('secure_view/', views.view_with_secure), path('permanent_redirect_view/', RedirectView.as_view(url='/get_view/', permanent=True)), path('temporary_redirect_view/', RedirectView.as_view(url='/get_view/', permanent=False)), path('http_redirect_view/', RedirectView.as_view(url='/secure_view/')), path('https_redirect_view/', RedirectView.as_view(url='https://testserver/secure_view/')), path('double_redirect_view/', views.double_redirect_view), path('bad_view/', views.bad_view), path('form_view/', views.form_view), path('form_view_with_template/', views.form_view_with_template), path('formset_view/', views.formset_view), path('json_view/', views.json_view), path('login_protected_view/', views.login_protected_view), path('login_protected_method_view/', views.login_protected_method_view), path('login_protected_view_custom_redirect/', views.login_protected_view_changed_redirect), path('permission_protected_view/', views.permission_protected_view), path('permission_protected_view_exception/', views.permission_protected_view_exception), path('permission_protected_method_view/', views.permission_protected_method_view), path('session_view/', views.session_view), path('broken_view/', views.broken_view), path('mail_sending_view/', views.mail_sending_view), path('mass_mail_sending_view/', views.mass_mail_sending_view), path('nesting_exception_view/', views.nesting_exception_view), path('django_project_redirect/', views.django_project_redirect), path('two_arg_exception/', views.two_arg_exception), path('accounts/', RedirectView.as_view(url='login/')), path('accounts/no_trailing_slash', RedirectView.as_view(url='login/')), path('accounts/login/', auth_views.LoginView.as_view(template_name='login.html')), path('accounts/logout/', auth_views.LogoutView.as_view()), ]
c2d78324e7e47b6c12b9684835fa1e8feb3ce80cdee5f56bf02c36a95b91e7f7
import json from urllib.parse import urlencode from xml.dom.minidom import parseString from django.contrib.auth.decorators import login_required, permission_required from django.core import mail from django.forms import fields from django.forms.forms import Form, ValidationError from django.forms.formsets import BaseFormSet, formset_factory from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound, HttpResponseRedirect, ) from django.shortcuts import render from django.template import Context, Template from django.test import Client from django.utils.decorators import method_decorator def get_view(request): "A simple view that expects a GET request, and returns a rendered template" t = Template('This is a test. {{ var }} is the value.', name='GET Template') c = Context({'var': request.GET.get('var', 42)}) return HttpResponse(t.render(c)) def trace_view(request): """ A simple view that expects a TRACE request and echoes its status line. TRACE requests should not have an entity; the view will return a 400 status response if it is present. """ if request.method.upper() != "TRACE": return HttpResponseNotAllowed("TRACE") elif request.body: return HttpResponseBadRequest("TRACE requests MUST NOT include an entity") else: protocol = request.META["SERVER_PROTOCOL"] t = Template( '{{ method }} {{ uri }} {{ version }}', name="TRACE Template", ) c = Context({ 'method': request.method, 'uri': request.path, 'version': protocol, }) return HttpResponse(t.render(c)) def put_view(request): if request.method == 'PUT': t = Template('Data received: {{ data }} is the body.', name='PUT Template') c = Context({ 'Content-Length': request.META['CONTENT_LENGTH'], 'data': request.body.decode(), }) else: t = Template('Viewing GET page.', name='Empty GET Template') c = Context() return HttpResponse(t.render(c)) def post_view(request): """A view that expects a POST, and returns a different template depending on whether any POST data is available """ if request.method == 'POST': if request.POST: t = Template('Data received: {{ data }} is the value.', name='POST Template') c = Context({'data': request.POST['value']}) else: t = Template('Viewing POST page.', name='Empty POST Template') c = Context() else: t = Template('Viewing GET page.', name='Empty GET Template') c = Context() return HttpResponse(t.render(c)) def json_view(request): """ A view that expects a request with the header 'application/json' and JSON data, which is deserialized and included in the context. """ if request.META.get('CONTENT_TYPE') != 'application/json': return HttpResponse() t = Template('Viewing {} page. With data {{ data }}.'.format(request.method)) data = json.loads(request.body.decode('utf-8')) c = Context({'data': data}) return HttpResponse(t.render(c)) def view_with_header(request): "A view that has a custom header" response = HttpResponse() response['X-DJANGO-TEST'] = 'Slartibartfast' return response def raw_post_view(request): """A view which expects raw XML to be posted and returns content extracted from the XML""" if request.method == 'POST': root = parseString(request.body) first_book = root.firstChild.firstChild title, author = [n.firstChild.nodeValue for n in first_book.childNodes] t = Template("{{ title }} - {{ author }}", name="Book template") c = Context({"title": title, "author": author}) else: t = Template("GET request.", name="Book GET template") c = Context() return HttpResponse(t.render(c)) def redirect_view(request): "A view that redirects all requests to the GET view" if request.GET: query = '?' + urlencode(request.GET, True) else: query = '' return HttpResponseRedirect('/get_view/' + query) def _post_view_redirect(request, status_code): """Redirect to /post_view/ using the status code.""" redirect_to = request.GET.get('to', '/post_view/') return HttpResponseRedirect(redirect_to, status=status_code) def method_saving_307_redirect_view(request): return _post_view_redirect(request, 307) def method_saving_308_redirect_view(request): return _post_view_redirect(request, 308) def view_with_secure(request): "A view that indicates if the request was secure" response = HttpResponse() response.test_was_secure_request = request.is_secure() response.test_server_port = request.META.get('SERVER_PORT', 80) return response def double_redirect_view(request): "A view that redirects all requests to a redirection view" return HttpResponseRedirect('/permanent_redirect_view/') def bad_view(request): "A view that returns a 404 with some error content" return HttpResponseNotFound('Not found!. This page contains some MAGIC content') TestChoices = ( ('a', 'First Choice'), ('b', 'Second Choice'), ('c', 'Third Choice'), ('d', 'Fourth Choice'), ('e', 'Fifth Choice') ) class TestForm(Form): text = fields.CharField() email = fields.EmailField() value = fields.IntegerField() single = fields.ChoiceField(choices=TestChoices) multi = fields.MultipleChoiceField(choices=TestChoices) def clean(self): cleaned_data = self.cleaned_data if cleaned_data.get("text") == "Raise non-field error": raise ValidationError("Non-field error.") return cleaned_data def form_view(request): "A view that tests a simple form" if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): t = Template('Valid POST data.', name='Valid POST Template') c = Context() else: t = Template('Invalid POST data. {{ form.errors }}', name='Invalid POST Template') c = Context({'form': form}) else: form = TestForm(request.GET) t = Template('Viewing base form. {{ form }}.', name='Form GET Template') c = Context({'form': form}) return HttpResponse(t.render(c)) def form_view_with_template(request): "A view that tests a simple form" if request.method == 'POST': form = TestForm(request.POST) if form.is_valid(): message = 'POST data OK' else: message = 'POST data has errors' else: form = TestForm() message = 'GET form page' return render(request, 'form_view.html', { 'form': form, 'message': message, }) class BaseTestFormSet(BaseFormSet): def clean(self): """No two email addresses are the same.""" if any(self.errors): # Don't bother validating the formset unless each form is valid return emails = [] for i in range(0, self.total_form_count()): form = self.forms[i] email = form.cleaned_data['email'] if email in emails: raise ValidationError( "Forms in a set must have distinct email addresses." ) emails.append(email) TestFormSet = formset_factory(TestForm, BaseTestFormSet) def formset_view(request): "A view that tests a simple formset" if request.method == 'POST': formset = TestFormSet(request.POST) if formset.is_valid(): t = Template('Valid POST data.', name='Valid POST Template') c = Context() else: t = Template('Invalid POST data. {{ my_formset.errors }}', name='Invalid POST Template') c = Context({'my_formset': formset}) else: formset = TestForm(request.GET) t = Template('Viewing base formset. {{ my_formset }}.', name='Formset GET Template') c = Context({'my_formset': formset}) return HttpResponse(t.render(c)) @login_required def login_protected_view(request): "A simple view that is login protected." t = Template('This is a login protected test. Username is {{ user.username }}.', name='Login Template') c = Context({'user': request.user}) return HttpResponse(t.render(c)) @login_required(redirect_field_name='redirect_to') def login_protected_view_changed_redirect(request): "A simple view that is login protected with a custom redirect field set" t = Template('This is a login protected test. Username is {{ user.username }}.', name='Login Template') c = Context({'user': request.user}) return HttpResponse(t.render(c)) def _permission_protected_view(request): "A simple view that is permission protected." t = Template('This is a permission protected test. ' 'Username is {{ user.username }}. ' 'Permissions are {{ user.get_all_permissions }}.', name='Permissions Template') c = Context({'user': request.user}) return HttpResponse(t.render(c)) permission_protected_view = permission_required('permission_not_granted')(_permission_protected_view) permission_protected_view_exception = ( permission_required('permission_not_granted', raise_exception=True)(_permission_protected_view) ) class _ViewManager: @method_decorator(login_required) def login_protected_view(self, request): t = Template('This is a login protected test using a method. ' 'Username is {{ user.username }}.', name='Login Method Template') c = Context({'user': request.user}) return HttpResponse(t.render(c)) @method_decorator(permission_required('permission_not_granted')) def permission_protected_view(self, request): t = Template('This is a permission protected test using a method. ' 'Username is {{ user.username }}. ' 'Permissions are {{ user.get_all_permissions }}.', name='Permissions Template') c = Context({'user': request.user}) return HttpResponse(t.render(c)) _view_manager = _ViewManager() login_protected_method_view = _view_manager.login_protected_view permission_protected_method_view = _view_manager.permission_protected_view def session_view(request): "A view that modifies the session" request.session['tobacconist'] = 'hovercraft' t = Template('This is a view that modifies the session.', name='Session Modifying View Template') c = Context() return HttpResponse(t.render(c)) def broken_view(request): """A view which just raises an exception, simulating a broken view.""" raise KeyError("Oops! Looks like you wrote some bad code.") def mail_sending_view(request): mail.EmailMessage( "Test message", "This is a test email", "[email protected]", ['[email protected]', '[email protected]']).send() return HttpResponse("Mail sent") def mass_mail_sending_view(request): m1 = mail.EmailMessage( 'First Test message', 'This is the first test email', '[email protected]', ['[email protected]', '[email protected]']) m2 = mail.EmailMessage( 'Second Test message', 'This is the second test email', '[email protected]', ['[email protected]', '[email protected]']) c = mail.get_connection() c.send_messages([m1, m2]) return HttpResponse("Mail sent") def nesting_exception_view(request): """ A view that uses a nested client to call another view and then raises an exception. """ client = Client() client.get('/get_view/') raise Exception('exception message') def django_project_redirect(request): return HttpResponseRedirect('https://www.djangoproject.com/') def upload_view(request): """Prints keys of request.FILES to the response.""" return HttpResponse(', '.join(request.FILES)) class TwoArgException(Exception): def __init__(self, one, two): pass def two_arg_exception(request): raise TwoArgException('one', 'two')
0a5e89848f45e4050bd3082ae8c89334fb0ecbd05ca57c2be17cccf9aff1af29
from django.core.exceptions import PermissionDenied from django.template.response import TemplateResponse from django.test import SimpleTestCase, modify_settings, override_settings from django.urls import path class MiddlewareAccessingContent: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # Response.content should be available in the middleware even with a # TemplateResponse-based exception response. assert response.content return response def template_response_error_handler(request, exception=None): return TemplateResponse(request, 'test_handler.html', status=403) def permission_denied_view(request): raise PermissionDenied urlpatterns = [ path('', permission_denied_view), ] handler403 = template_response_error_handler @override_settings(ROOT_URLCONF='handlers.tests_custom_error_handlers') @modify_settings(MIDDLEWARE={'append': 'handlers.tests_custom_error_handlers.MiddlewareAccessingContent'}) class CustomErrorHandlerTests(SimpleTestCase): def test_handler_renders_template_response(self): """ BaseHandler should render TemplateResponse if necessary. """ response = self.client.get('/') self.assertContains(response, 'Error handler content', status_code=403)
94d6fa09ba8562e979eead76d3f79dd8e1c9813fd5f6e20755ff6eb9694f3a69
from django.core.exceptions import ImproperlyConfigured from django.core.handlers.wsgi import WSGIHandler, WSGIRequest, get_script_name from django.core.signals import request_finished, request_started from django.db import close_old_connections, connection from django.test import ( RequestFactory, SimpleTestCase, TransactionTestCase, override_settings, ) from django.utils.version import PY37 class HandlerTests(SimpleTestCase): request_factory = RequestFactory() def setUp(self): request_started.disconnect(close_old_connections) def tearDown(self): request_started.connect(close_old_connections) def test_middleware_initialized(self): handler = WSGIHandler() self.assertIsNotNone(handler._middleware_chain) def test_bad_path_info(self): """ A non-UTF-8 path populates PATH_INFO with an URL-encoded path and produces a 404. """ environ = self.request_factory.get('/').environ environ['PATH_INFO'] = '\xed' handler = WSGIHandler() response = handler(environ, lambda *a, **k: None) # The path of the request will be encoded to '/%ED'. self.assertEqual(response.status_code, 404) def test_non_ascii_query_string(self): """ Non-ASCII query strings are properly decoded (#20530, #22996). """ environ = self.request_factory.get('/').environ raw_query_strings = [ b'want=caf%C3%A9', # This is the proper way to encode 'café' b'want=caf\xc3\xa9', # UA forgot to quote bytes b'want=caf%E9', # UA quoted, but not in UTF-8 b'want=caf\xe9', # UA forgot to convert Latin-1 to UTF-8 and to quote (typical of MSIE) ] got = [] for raw_query_string in raw_query_strings: # Simulate http.server.BaseHTTPRequestHandler.parse_request handling of raw request environ['QUERY_STRING'] = str(raw_query_string, 'iso-8859-1') request = WSGIRequest(environ) got.append(request.GET['want']) # %E9 is converted to the unicode replacement character by parse_qsl self.assertEqual(got, ['café', 'café', 'caf\ufffd', 'café']) def test_non_ascii_cookie(self): """Non-ASCII cookies set in JavaScript are properly decoded (#20557).""" environ = self.request_factory.get('/').environ raw_cookie = 'want="café"'.encode('utf-8').decode('iso-8859-1') environ['HTTP_COOKIE'] = raw_cookie request = WSGIRequest(environ) self.assertEqual(request.COOKIES['want'], "café") def test_invalid_unicode_cookie(self): """ Invalid cookie content should result in an absent cookie, but not in a crash while trying to decode it (#23638). """ environ = self.request_factory.get('/').environ environ['HTTP_COOKIE'] = 'x=W\x03c(h]\x8e' request = WSGIRequest(environ) # We don't test COOKIES content, as the result might differ between # Python version because parsing invalid content became stricter in # latest versions. self.assertIsInstance(request.COOKIES, dict) @override_settings(ROOT_URLCONF='handlers.urls') def test_invalid_multipart_boundary(self): """ Invalid boundary string should produce a "Bad Request" response, not a server error (#23887). """ environ = self.request_factory.post('/malformed_post/').environ environ['CONTENT_TYPE'] = 'multipart/form-data; boundary=WRONG\x07' handler = WSGIHandler() response = handler(environ, lambda *a, **k: None) # Expect "bad request" response self.assertEqual(response.status_code, 400) @override_settings(ROOT_URLCONF='handlers.urls', MIDDLEWARE=[]) class TransactionsPerRequestTests(TransactionTestCase): available_apps = [] def test_no_transaction(self): response = self.client.get('/in_transaction/') self.assertContains(response, 'False') def test_auto_transaction(self): old_atomic_requests = connection.settings_dict['ATOMIC_REQUESTS'] try: connection.settings_dict['ATOMIC_REQUESTS'] = True response = self.client.get('/in_transaction/') finally: connection.settings_dict['ATOMIC_REQUESTS'] = old_atomic_requests self.assertContains(response, 'True') def test_no_auto_transaction(self): old_atomic_requests = connection.settings_dict['ATOMIC_REQUESTS'] try: connection.settings_dict['ATOMIC_REQUESTS'] = True response = self.client.get('/not_in_transaction/') finally: connection.settings_dict['ATOMIC_REQUESTS'] = old_atomic_requests self.assertContains(response, 'False') @override_settings(ROOT_URLCONF='handlers.urls') class SignalsTests(SimpleTestCase): def setUp(self): self.signals = [] self.signaled_environ = None request_started.connect(self.register_started) request_finished.connect(self.register_finished) def tearDown(self): request_started.disconnect(self.register_started) request_finished.disconnect(self.register_finished) def register_started(self, **kwargs): self.signals.append('started') self.signaled_environ = kwargs.get('environ') def register_finished(self, **kwargs): self.signals.append('finished') def test_request_signals(self): response = self.client.get('/regular/') self.assertEqual(self.signals, ['started', 'finished']) self.assertEqual(response.content, b"regular content") self.assertEqual(self.signaled_environ, response.wsgi_request.environ) def test_request_signals_streaming_response(self): response = self.client.get('/streaming/') self.assertEqual(self.signals, ['started']) self.assertEqual(b''.join(response.streaming_content), b"streaming content") self.assertEqual(self.signals, ['started', 'finished']) def empty_middleware(get_response): pass @override_settings(ROOT_URLCONF='handlers.urls') class HandlerRequestTests(SimpleTestCase): request_factory = RequestFactory() def test_suspiciousop_in_view_returns_400(self): response = self.client.get('/suspicious/') self.assertEqual(response.status_code, 400) def test_invalid_urls(self): response = self.client.get('~%A9helloworld') self.assertEqual(response.status_code, 404) self.assertEqual(response.context['request_path'], '/~%25A9helloworld' if PY37 else '/%7E%25A9helloworld') response = self.client.get('d%aao%aaw%aan%aal%aao%aaa%aad%aa/') self.assertEqual(response.context['request_path'], '/d%25AAo%25AAw%25AAn%25AAl%25AAo%25AAa%25AAd%25AA') response = self.client.get('/%E2%99%E2%99%A5/') self.assertEqual(response.context['request_path'], '/%25E2%2599%E2%99%A5/') response = self.client.get('/%E2%98%8E%E2%A9%E2%99%A5/') self.assertEqual(response.context['request_path'], '/%E2%98%8E%25E2%25A9%E2%99%A5/') def test_environ_path_info_type(self): environ = self.request_factory.get('/%E2%A8%87%87%A5%E2%A8%A0').environ self.assertIsInstance(environ['PATH_INFO'], str) def test_handle_accepts_httpstatus_enum_value(self): def start_response(status, headers): start_response.status = status environ = self.request_factory.get('/httpstatus_enum/').environ WSGIHandler()(environ, start_response) self.assertEqual(start_response.status, '200 OK') @override_settings(MIDDLEWARE=['handlers.tests.empty_middleware']) def test_middleware_returns_none(self): msg = 'Middleware factory handlers.tests.empty_middleware returned None.' with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get('/') def test_no_response(self): msg = "The view %s didn't return an HttpResponse object. It returned None instead." tests = ( ('/no_response_fbv/', 'handlers.views.no_response'), ('/no_response_cbv/', 'handlers.views.NoResponse.__call__'), ) for url, view in tests: with self.subTest(url=url), self.assertRaisesMessage(ValueError, msg % view): self.client.get(url) class ScriptNameTests(SimpleTestCase): def test_get_script_name(self): # Regression test for #23173 # Test first without PATH_INFO script_name = get_script_name({'SCRIPT_URL': '/foobar/'}) self.assertEqual(script_name, '/foobar/') script_name = get_script_name({'SCRIPT_URL': '/foobar/', 'PATH_INFO': '/'}) self.assertEqual(script_name, '/foobar') def test_get_script_name_double_slashes(self): """ WSGI squashes multiple successive slashes in PATH_INFO, get_script_name should take that into account when forming SCRIPT_NAME (#17133). """ script_name = get_script_name({ 'SCRIPT_URL': '/mst/milestones//accounts/login//help', 'PATH_INFO': '/milestones/accounts/login/help', }) self.assertEqual(script_name, '/mst')
4703d953445f1a03a7da51f0d7fb8b51b63dbc5f60a8643d183a8660917c7962
from django.urls import path from . import views urlpatterns = [ path('regular/', views.regular), path('no_response_fbv/', views.no_response), path('no_response_cbv/', views.NoResponse()), path('streaming/', views.streaming), path('in_transaction/', views.in_transaction), path('not_in_transaction/', views.not_in_transaction), path('suspicious/', views.suspicious), path('malformed_post/', views.malformed_post), path('httpstatus_enum/', views.httpstatus_enum), ]
6313b461527e994d506e8d702a0c0fca26ca33e206bb5576f7574bbbbcdf9fb0
from http import HTTPStatus from django.core.exceptions import SuspiciousOperation from django.db import connection, transaction from django.http import HttpResponse, StreamingHttpResponse from django.views.decorators.csrf import csrf_exempt def regular(request): return HttpResponse(b"regular content") def no_response(request): pass class NoResponse: def __call__(self, request): pass def streaming(request): return StreamingHttpResponse([b"streaming", b" ", b"content"]) def in_transaction(request): return HttpResponse(str(connection.in_atomic_block)) @transaction.non_atomic_requests def not_in_transaction(request): return HttpResponse(str(connection.in_atomic_block)) def suspicious(request): raise SuspiciousOperation('dubious') @csrf_exempt def malformed_post(request): request.POST return HttpResponse() def httpstatus_enum(request): return HttpResponse(status=HTTPStatus.OK)
67a2aaf983cf6994823e31b233096644eb27466678c3b9f8cedef8e562f31602
from django.core.exceptions import ImproperlyConfigured from django.core.servers.basehttp import get_internal_wsgi_application from django.core.signals import request_started from django.core.wsgi import get_wsgi_application from django.db import close_old_connections from django.test import SimpleTestCase, override_settings from django.test.client import RequestFactory @override_settings(ROOT_URLCONF='wsgi.urls') class WSGITest(SimpleTestCase): request_factory = RequestFactory() def setUp(self): request_started.disconnect(close_old_connections) def tearDown(self): request_started.connect(close_old_connections) def test_get_wsgi_application(self): """ get_wsgi_application() returns a functioning WSGI callable. """ application = get_wsgi_application() environ = self.request_factory._base_environ( PATH_INFO="/", CONTENT_TYPE="text/html; charset=utf-8", REQUEST_METHOD="GET" ) response_data = {} def start_response(status, headers): response_data["status"] = status response_data["headers"] = headers response = application(environ, start_response) self.assertEqual(response_data["status"], "200 OK") self.assertEqual( set(response_data["headers"]), {('Content-Length', '12'), ('Content-Type', 'text/html; charset=utf-8')}) self.assertIn(bytes(response), [ b"Content-Length: 12\r\nContent-Type: text/html; charset=utf-8\r\n\r\nHello World!", b"Content-Type: text/html; charset=utf-8\r\nContent-Length: 12\r\n\r\nHello World!" ]) def test_file_wrapper(self): """ FileResponse uses wsgi.file_wrapper. """ class FileWrapper: def __init__(self, filelike, blksize=8192): filelike.close() application = get_wsgi_application() environ = self.request_factory._base_environ( PATH_INFO='/file/', REQUEST_METHOD='GET', **{'wsgi.file_wrapper': FileWrapper} ) response_data = {} def start_response(status, headers): response_data['status'] = status response_data['headers'] = headers response = application(environ, start_response) self.assertEqual(response_data['status'], '200 OK') self.assertIsInstance(response, FileWrapper) class GetInternalWSGIApplicationTest(SimpleTestCase): @override_settings(WSGI_APPLICATION="wsgi.wsgi.application") def test_success(self): """ If ``WSGI_APPLICATION`` is a dotted path, the referenced object is returned. """ app = get_internal_wsgi_application() from .wsgi import application self.assertIs(app, application) @override_settings(WSGI_APPLICATION=None) def test_default(self): """ If ``WSGI_APPLICATION`` is ``None``, the return value of ``get_wsgi_application`` is returned. """ # Mock out get_wsgi_application so we know its return value is used fake_app = object() def mock_get_wsgi_app(): return fake_app from django.core.servers import basehttp _orig_get_wsgi_app = basehttp.get_wsgi_application basehttp.get_wsgi_application = mock_get_wsgi_app try: app = get_internal_wsgi_application() self.assertIs(app, fake_app) finally: basehttp.get_wsgi_application = _orig_get_wsgi_app @override_settings(WSGI_APPLICATION="wsgi.noexist.app") def test_bad_module(self): msg = "WSGI application 'wsgi.noexist.app' could not be loaded; Error importing" with self.assertRaisesMessage(ImproperlyConfigured, msg): get_internal_wsgi_application() @override_settings(WSGI_APPLICATION="wsgi.wsgi.noexist") def test_bad_name(self): msg = "WSGI application 'wsgi.wsgi.noexist' could not be loaded; Error importing" with self.assertRaisesMessage(ImproperlyConfigured, msg): get_internal_wsgi_application()
cd9b4bcec982e93a3d5a827d655f37d6dd40a736eba95bcd4a83fa2918f6eec6
from django.http import FileResponse, HttpResponse from django.urls import path def helloworld(request): return HttpResponse("Hello World!") urlpatterns = [ path('', helloworld), path('file/', lambda x: FileResponse(open(__file__, 'rb'))), ]
58421e049c4055e57b16b0e67173608c21c83a0f7bf92e21c46b265a556ec912
"""Tests related to django.db.backends that haven't been organized.""" import datetime import threading import unittest import warnings from django.core.management.color import no_style from django.db import ( DEFAULT_DB_ALIAS, DatabaseError, IntegrityError, connection, connections, reset_queries, transaction, ) from django.db.backends.base.base import BaseDatabaseWrapper from django.db.backends.signals import connection_created from django.db.backends.utils import CursorWrapper from django.db.models.sql.constants import CURSOR from django.test import ( TestCase, TransactionTestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from .models import ( Article, Object, ObjectReference, Person, Post, RawData, Reporter, ReporterProxy, SchoolClass, Square, VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ, ) class DateQuotingTest(TestCase): def test_django_date_trunc(self): """ Test the custom ``django_date_trunc method``, in particular against fields which clash with strings passed to it (e.g. 'year') (#12818). """ updated = datetime.datetime(2010, 2, 20) SchoolClass.objects.create(year=2009, last_updated=updated) years = SchoolClass.objects.dates('last_updated', 'year') self.assertEqual(list(years), [datetime.date(2010, 1, 1)]) def test_django_date_extract(self): """ Test the custom ``django_date_extract method``, in particular against fields which clash with strings passed to it (e.g. 'day') (#12818). """ updated = datetime.datetime(2010, 2, 20) SchoolClass.objects.create(year=2009, last_updated=updated) classes = SchoolClass.objects.filter(last_updated__day=20) self.assertEqual(len(classes), 1) @override_settings(DEBUG=True) class LastExecutedQueryTest(TestCase): def test_last_executed_query_without_previous_query(self): """ last_executed_query should not raise an exception even if no previous query has been run. """ with connection.cursor() as cursor: connection.ops.last_executed_query(cursor, '', ()) def test_debug_sql(self): list(Reporter.objects.filter(first_name="test")) sql = connection.queries[-1]['sql'].lower() self.assertIn("select", sql) self.assertIn(Reporter._meta.db_table, sql) def test_query_encoding(self): """last_executed_query() returns a string.""" data = RawData.objects.filter(raw_data=b'\x00\x46 \xFE').extra(select={'föö': 1}) sql, params = data.query.sql_with_params() cursor = data.query.get_compiler('default').execute_sql(CURSOR) last_sql = cursor.db.ops.last_executed_query(cursor, sql, params) self.assertIsInstance(last_sql, str) def test_last_executed_query(self): # last_executed_query() interpolate all parameters, in most cases it is # not equal to QuerySet.query. for qs in ( Article.objects.filter(pk=1), Article.objects.filter(pk__in=(1, 2), reporter__pk=3), ): sql, params = qs.query.sql_with_params() cursor = qs.query.get_compiler(DEFAULT_DB_ALIAS).execute_sql(CURSOR) self.assertEqual( cursor.db.ops.last_executed_query(cursor, sql, params), str(qs.query), ) @skipUnlessDBFeature('supports_paramstyle_pyformat') def test_last_executed_query_dict(self): square_opts = Square._meta sql = 'INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)' % ( connection.introspection.identifier_converter(square_opts.db_table), connection.ops.quote_name(square_opts.get_field('root').column), connection.ops.quote_name(square_opts.get_field('square').column), ) with connection.cursor() as cursor: params = {'root': 2, 'square': 4} cursor.execute(sql, params) self.assertEqual( cursor.db.ops.last_executed_query(cursor, sql, params), sql % params, ) class ParameterHandlingTest(TestCase): def test_bad_parameter_count(self): "An executemany call with too many/not enough parameters will raise an exception (Refs #12612)" with connection.cursor() as cursor: query = ('INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % ( connection.introspection.identifier_converter('backends_square'), connection.ops.quote_name('root'), connection.ops.quote_name('square') )) with self.assertRaises(Exception): cursor.executemany(query, [(1, 2, 3)]) with self.assertRaises(Exception): cursor.executemany(query, [(1,)]) class LongNameTest(TransactionTestCase): """Long primary keys and model names can result in a sequence name that exceeds the database limits, which will result in truncation on certain databases (e.g., Postgres). The backend needs to use the correct sequence name in last_insert_id and other places, so check it is. Refs #8901. """ available_apps = ['backends'] def test_sequence_name_length_limits_create(self): """Test creation of model with long name and long pk name doesn't error. Ref #8901""" VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() def test_sequence_name_length_limits_m2m(self): """ An m2m save of a model with a long name and a long m2m field name doesn't error (#8901). """ obj = VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() rel_obj = Person.objects.create(first_name='Django', last_name='Reinhardt') obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj) def test_sequence_name_length_limits_flush(self): """ Sequence resetting as part of a flush with model with long name and long pk name doesn't error (#8901). """ # A full flush is expensive to the full test, so we dig into the # internals to generate the likely offending SQL and run it manually # Some convenience aliases VLM = VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ VLM_m2m = VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through tables = [ VLM._meta.db_table, VLM_m2m._meta.db_table, ] sequences = [ { 'column': VLM._meta.pk.column, 'table': VLM._meta.db_table }, ] sql_list = connection.ops.sql_flush(no_style(), tables, sequences) with connection.cursor() as cursor: for statement in sql_list: cursor.execute(statement) class SequenceResetTest(TestCase): def test_generic_relation(self): "Sequence names are correct when resetting generic relations (Ref #13941)" # Create an object with a manually specified PK Post.objects.create(id=10, name='1st post', text='hello world') # Reset the sequences for the database commands = connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql(no_style(), [Post]) with connection.cursor() as cursor: for sql in commands: cursor.execute(sql) # If we create a new object now, it should have a PK greater # than the PK we specified manually. obj = Post.objects.create(name='New post', text='goodbye world') self.assertGreater(obj.pk, 10) # This test needs to run outside of a transaction, otherwise closing the # connection would implicitly rollback and cause problems during teardown. class ConnectionCreatedSignalTest(TransactionTestCase): available_apps = [] # Unfortunately with sqlite3 the in-memory test database cannot be closed, # and so it cannot be re-opened during testing. @skipUnlessDBFeature('test_db_allows_multiple_connections') def test_signal(self): data = {} def receiver(sender, connection, **kwargs): data["connection"] = connection connection_created.connect(receiver) connection.close() connection.cursor() self.assertIs(data["connection"].connection, connection.connection) connection_created.disconnect(receiver) data.clear() connection.cursor() self.assertEqual(data, {}) class EscapingChecks(TestCase): """ All tests in this test case are also run with settings.DEBUG=True in EscapingChecksDebug test case, to also test CursorDebugWrapper. """ bare_select_suffix = connection.features.bare_select_suffix def test_paramless_no_escaping(self): with connection.cursor() as cursor: cursor.execute("SELECT '%s'" + self.bare_select_suffix) self.assertEqual(cursor.fetchall()[0][0], '%s') def test_parameter_escaping(self): with connection.cursor() as cursor: cursor.execute("SELECT '%%', %s" + self.bare_select_suffix, ('%d',)) self.assertEqual(cursor.fetchall()[0], ('%', '%d')) @override_settings(DEBUG=True) class EscapingChecksDebug(EscapingChecks): pass class BackendTestCase(TransactionTestCase): available_apps = ['backends'] def create_squares_with_executemany(self, args): self.create_squares(args, 'format', True) def create_squares(self, args, paramstyle, multiple): opts = Square._meta tbl = connection.introspection.identifier_converter(opts.db_table) f1 = connection.ops.quote_name(opts.get_field('root').column) f2 = connection.ops.quote_name(opts.get_field('square').column) if paramstyle == 'format': query = 'INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % (tbl, f1, f2) elif paramstyle == 'pyformat': query = 'INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)' % (tbl, f1, f2) else: raise ValueError("unsupported paramstyle in test") with connection.cursor() as cursor: if multiple: cursor.executemany(query, args) else: cursor.execute(query, args) def test_cursor_executemany(self): # Test cursor.executemany #4896 args = [(i, i ** 2) for i in range(-5, 6)] self.create_squares_with_executemany(args) self.assertEqual(Square.objects.count(), 11) for i in range(-5, 6): square = Square.objects.get(root=i) self.assertEqual(square.square, i ** 2) def test_cursor_executemany_with_empty_params_list(self): # Test executemany with params=[] does nothing #4765 args = [] self.create_squares_with_executemany(args) self.assertEqual(Square.objects.count(), 0) def test_cursor_executemany_with_iterator(self): # Test executemany accepts iterators #10320 args = ((i, i ** 2) for i in range(-3, 2)) self.create_squares_with_executemany(args) self.assertEqual(Square.objects.count(), 5) args = ((i, i ** 2) for i in range(3, 7)) with override_settings(DEBUG=True): # same test for DebugCursorWrapper self.create_squares_with_executemany(args) self.assertEqual(Square.objects.count(), 9) @skipUnlessDBFeature('supports_paramstyle_pyformat') def test_cursor_execute_with_pyformat(self): # Support pyformat style passing of parameters #10070 args = {'root': 3, 'square': 9} self.create_squares(args, 'pyformat', multiple=False) self.assertEqual(Square.objects.count(), 1) @skipUnlessDBFeature('supports_paramstyle_pyformat') def test_cursor_executemany_with_pyformat(self): # Support pyformat style passing of parameters #10070 args = [{'root': i, 'square': i ** 2} for i in range(-5, 6)] self.create_squares(args, 'pyformat', multiple=True) self.assertEqual(Square.objects.count(), 11) for i in range(-5, 6): square = Square.objects.get(root=i) self.assertEqual(square.square, i ** 2) @skipUnlessDBFeature('supports_paramstyle_pyformat') def test_cursor_executemany_with_pyformat_iterator(self): args = ({'root': i, 'square': i ** 2} for i in range(-3, 2)) self.create_squares(args, 'pyformat', multiple=True) self.assertEqual(Square.objects.count(), 5) args = ({'root': i, 'square': i ** 2} for i in range(3, 7)) with override_settings(DEBUG=True): # same test for DebugCursorWrapper self.create_squares(args, 'pyformat', multiple=True) self.assertEqual(Square.objects.count(), 9) def test_unicode_fetches(self): # fetchone, fetchmany, fetchall return strings as unicode objects #6254 qn = connection.ops.quote_name Person(first_name="John", last_name="Doe").save() Person(first_name="Jane", last_name="Doe").save() Person(first_name="Mary", last_name="Agnelline").save() Person(first_name="Peter", last_name="Parker").save() Person(first_name="Clark", last_name="Kent").save() opts2 = Person._meta f3, f4 = opts2.get_field('first_name'), opts2.get_field('last_name') with connection.cursor() as cursor: cursor.execute( 'SELECT %s, %s FROM %s ORDER BY %s' % ( qn(f3.column), qn(f4.column), connection.introspection.identifier_converter(opts2.db_table), qn(f3.column), ) ) self.assertEqual(cursor.fetchone(), ('Clark', 'Kent')) self.assertEqual(list(cursor.fetchmany(2)), [('Jane', 'Doe'), ('John', 'Doe')]) self.assertEqual(list(cursor.fetchall()), [('Mary', 'Agnelline'), ('Peter', 'Parker')]) def test_unicode_password(self): old_password = connection.settings_dict['PASSWORD'] connection.settings_dict['PASSWORD'] = "françois" try: connection.cursor() except DatabaseError: # As password is probably wrong, a database exception is expected pass except Exception as e: self.fail("Unexpected error raised with unicode password: %s" % e) finally: connection.settings_dict['PASSWORD'] = old_password def test_database_operations_helper_class(self): # Ticket #13630 self.assertTrue(hasattr(connection, 'ops')) self.assertTrue(hasattr(connection.ops, 'connection')) self.assertEqual(connection, connection.ops.connection) def test_database_operations_init(self): """ DatabaseOperations initialization doesn't query the database. See #17656. """ with self.assertNumQueries(0): connection.ops.__class__(connection) def test_cached_db_features(self): self.assertIn(connection.features.supports_transactions, (True, False)) self.assertIn(connection.features.can_introspect_foreign_keys, (True, False)) def test_duplicate_table_error(self): """ Creating an existing table returns a DatabaseError """ query = 'CREATE TABLE %s (id INTEGER);' % Article._meta.db_table with connection.cursor() as cursor: with self.assertRaises(DatabaseError): cursor.execute(query) def test_cursor_contextmanager(self): """ Cursors can be used as a context manager """ with connection.cursor() as cursor: self.assertIsInstance(cursor, CursorWrapper) # Both InterfaceError and ProgrammingError seem to be used when # accessing closed cursor (psycopg2 has InterfaceError, rest seem # to use ProgrammingError). with self.assertRaises(connection.features.closed_cursor_error_class): # cursor should be closed, so no queries should be possible. cursor.execute("SELECT 1" + connection.features.bare_select_suffix) @unittest.skipUnless(connection.vendor == 'postgresql', "Psycopg2 specific cursor.closed attribute needed") def test_cursor_contextmanager_closing(self): # There isn't a generic way to test that cursors are closed, but # psycopg2 offers us a way to check that by closed attribute. # So, run only on psycopg2 for that reason. with connection.cursor() as cursor: self.assertIsInstance(cursor, CursorWrapper) self.assertTrue(cursor.closed) # Unfortunately with sqlite3 the in-memory test database cannot be closed. @skipUnlessDBFeature('test_db_allows_multiple_connections') def test_is_usable_after_database_disconnects(self): """ is_usable() doesn't crash when the database disconnects (#21553). """ # Open a connection to the database. with connection.cursor(): pass # Emulate a connection close by the database. connection._close() # Even then is_usable() should not raise an exception. try: self.assertFalse(connection.is_usable()) finally: # Clean up the mess created by connection._close(). Since the # connection is already closed, this crashes on some backends. try: connection.close() except Exception: pass @override_settings(DEBUG=True) def test_queries(self): """ Test the documented API of connection.queries. """ sql = 'SELECT 1' + connection.features.bare_select_suffix with connection.cursor() as cursor: reset_queries() cursor.execute(sql) self.assertEqual(1, len(connection.queries)) self.assertIsInstance(connection.queries, list) self.assertIsInstance(connection.queries[0], dict) self.assertEqual(list(connection.queries[0]), ['sql', 'time']) self.assertEqual(connection.queries[0]['sql'], sql) reset_queries() self.assertEqual(0, len(connection.queries)) sql = ('INSERT INTO %s (%s, %s) VALUES (%%s, %%s)' % ( connection.introspection.identifier_converter('backends_square'), connection.ops.quote_name('root'), connection.ops.quote_name('square'), )) with connection.cursor() as cursor: cursor.executemany(sql, [(1, 1), (2, 4)]) self.assertEqual(1, len(connection.queries)) self.assertIsInstance(connection.queries, list) self.assertIsInstance(connection.queries[0], dict) self.assertEqual(list(connection.queries[0]), ['sql', 'time']) self.assertEqual(connection.queries[0]['sql'], '2 times: %s' % sql) # Unfortunately with sqlite3 the in-memory test database cannot be closed. @skipUnlessDBFeature('test_db_allows_multiple_connections') @override_settings(DEBUG=True) def test_queries_limit(self): """ The backend doesn't store an unlimited number of queries (#12581). """ old_queries_limit = BaseDatabaseWrapper.queries_limit BaseDatabaseWrapper.queries_limit = 3 new_connection = connection.copy() # Initialize the connection and clear initialization statements. with new_connection.cursor(): pass new_connection.queries_log.clear() try: with new_connection.cursor() as cursor: cursor.execute("SELECT 1" + new_connection.features.bare_select_suffix) cursor.execute("SELECT 2" + new_connection.features.bare_select_suffix) with warnings.catch_warnings(record=True) as w: self.assertEqual(2, len(new_connection.queries)) self.assertEqual(0, len(w)) with new_connection.cursor() as cursor: cursor.execute("SELECT 3" + new_connection.features.bare_select_suffix) cursor.execute("SELECT 4" + new_connection.features.bare_select_suffix) msg = "Limit for query logging exceeded, only the last 3 queries will be returned." with self.assertWarnsMessage(UserWarning, msg): self.assertEqual(3, len(new_connection.queries)) finally: BaseDatabaseWrapper.queries_limit = old_queries_limit new_connection.close() def test_timezone_none_use_tz_false(self): connection.ensure_connection() with self.settings(TIME_ZONE=None, USE_TZ=False): connection.init_connection_state() # These tests aren't conditional because it would require differentiating # between MySQL+InnoDB and MySQL+MYISAM (something we currently can't do). class FkConstraintsTests(TransactionTestCase): available_apps = ['backends'] def setUp(self): # Create a Reporter. self.r = Reporter.objects.create(first_name='John', last_name='Smith') def test_integrity_checks_on_creation(self): """ Try to create a model instance that violates a FK constraint. If it fails it should fail with IntegrityError. """ a1 = Article(headline="This is a test", pub_date=datetime.datetime(2005, 7, 27), reporter_id=30) try: a1.save() except IntegrityError: pass else: self.skipTest("This backend does not support integrity checks.") # Now that we know this backend supports integrity checks we make sure # constraints are also enforced for proxy Refs #17519 a2 = Article( headline='This is another test', reporter=self.r, pub_date=datetime.datetime(2012, 8, 3), reporter_proxy_id=30, ) with self.assertRaises(IntegrityError): a2.save() def test_integrity_checks_on_update(self): """ Try to update a model instance introducing a FK constraint violation. If it fails it should fail with IntegrityError. """ # Create an Article. Article.objects.create(headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r) # Retrieve it from the DB a1 = Article.objects.get(headline="Test article") a1.reporter_id = 30 try: a1.save() except IntegrityError: pass else: self.skipTest("This backend does not support integrity checks.") # Now that we know this backend supports integrity checks we make sure # constraints are also enforced for proxy Refs #17519 # Create another article r_proxy = ReporterProxy.objects.get(pk=self.r.pk) Article.objects.create( headline='Another article', pub_date=datetime.datetime(1988, 5, 15), reporter=self.r, reporter_proxy=r_proxy, ) # Retrieve the second article from the DB a2 = Article.objects.get(headline='Another article') a2.reporter_proxy_id = 30 with self.assertRaises(IntegrityError): a2.save() def test_disable_constraint_checks_manually(self): """ When constraint checks are disabled, should be able to write bad data without IntegrityErrors. """ with transaction.atomic(): # Create an Article. Article.objects.create( headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r, ) # Retrieve it from the DB a = Article.objects.get(headline="Test article") a.reporter_id = 30 try: connection.disable_constraint_checking() a.save() connection.enable_constraint_checking() except IntegrityError: self.fail("IntegrityError should not have occurred.") transaction.set_rollback(True) def test_disable_constraint_checks_context_manager(self): """ When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors. """ with transaction.atomic(): # Create an Article. Article.objects.create( headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r, ) # Retrieve it from the DB a = Article.objects.get(headline="Test article") a.reporter_id = 30 try: with connection.constraint_checks_disabled(): a.save() except IntegrityError: self.fail("IntegrityError should not have occurred.") transaction.set_rollback(True) def test_check_constraints(self): """ Constraint checks should raise an IntegrityError when bad data is in the DB. """ with transaction.atomic(): # Create an Article. Article.objects.create( headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r, ) # Retrieve it from the DB a = Article.objects.get(headline="Test article") a.reporter_id = 30 with connection.constraint_checks_disabled(): a.save() with self.assertRaises(IntegrityError): connection.check_constraints() transaction.set_rollback(True) class ThreadTests(TransactionTestCase): available_apps = ['backends'] def test_default_connection_thread_local(self): """ The default connection (i.e. django.db.connection) is different for each thread (#17258). """ # Map connections by id because connections with identical aliases # have the same hash. connections_dict = {} connection.cursor() connections_dict[id(connection)] = connection def runner(): # Passing django.db.connection between threads doesn't work while # connections[DEFAULT_DB_ALIAS] does. from django.db import connections connection = connections[DEFAULT_DB_ALIAS] # Allow thread sharing so the connection can be closed by the # main thread. connection.inc_thread_sharing() connection.cursor() connections_dict[id(connection)] = connection try: for x in range(2): t = threading.Thread(target=runner) t.start() t.join() # Each created connection got different inner connection. self.assertEqual(len({conn.connection for conn in connections_dict.values()}), 3) finally: # Finish by closing the connections opened by the other threads # (the connection opened in the main thread will automatically be # closed on teardown). for conn in connections_dict.values(): if conn is not connection: if conn.allow_thread_sharing: conn.close() conn.dec_thread_sharing() def test_connections_thread_local(self): """ The connections are different for each thread (#17258). """ # Map connections by id because connections with identical aliases # have the same hash. connections_dict = {} for conn in connections.all(): connections_dict[id(conn)] = conn def runner(): from django.db import connections for conn in connections.all(): # Allow thread sharing so the connection can be closed by the # main thread. conn.inc_thread_sharing() connections_dict[id(conn)] = conn try: for x in range(2): t = threading.Thread(target=runner) t.start() t.join() self.assertEqual(len(connections_dict), 6) finally: # Finish by closing the connections opened by the other threads # (the connection opened in the main thread will automatically be # closed on teardown). for conn in connections_dict.values(): if conn is not connection: if conn.allow_thread_sharing: conn.close() conn.dec_thread_sharing() def test_pass_connection_between_threads(self): """ A connection can be passed from one thread to the other (#17258). """ Person.objects.create(first_name="John", last_name="Doe") def do_thread(): def runner(main_thread_connection): from django.db import connections connections['default'] = main_thread_connection try: Person.objects.get(first_name="John", last_name="Doe") except Exception as e: exceptions.append(e) t = threading.Thread(target=runner, args=[connections['default']]) t.start() t.join() # Without touching thread sharing, which should be False by default. exceptions = [] do_thread() # Forbidden! self.assertIsInstance(exceptions[0], DatabaseError) # After calling inc_thread_sharing() on the connection. connections['default'].inc_thread_sharing() try: exceptions = [] do_thread() # All good self.assertEqual(exceptions, []) finally: connections['default'].dec_thread_sharing() def test_closing_non_shared_connections(self): """ A connection that is not explicitly shareable cannot be closed by another thread (#17258). """ # First, without explicitly enabling the connection for sharing. exceptions = set() def runner1(): def runner2(other_thread_connection): try: other_thread_connection.close() except DatabaseError as e: exceptions.add(e) t2 = threading.Thread(target=runner2, args=[connections['default']]) t2.start() t2.join() t1 = threading.Thread(target=runner1) t1.start() t1.join() # The exception was raised self.assertEqual(len(exceptions), 1) # Then, with explicitly enabling the connection for sharing. exceptions = set() def runner1(): def runner2(other_thread_connection): try: other_thread_connection.close() except DatabaseError as e: exceptions.add(e) # Enable thread sharing connections['default'].inc_thread_sharing() try: t2 = threading.Thread(target=runner2, args=[connections['default']]) t2.start() t2.join() finally: connections['default'].dec_thread_sharing() t1 = threading.Thread(target=runner1) t1.start() t1.join() # No exception was raised self.assertEqual(len(exceptions), 0) def test_thread_sharing_count(self): self.assertIs(connection.allow_thread_sharing, False) connection.inc_thread_sharing() self.assertIs(connection.allow_thread_sharing, True) connection.inc_thread_sharing() self.assertIs(connection.allow_thread_sharing, True) connection.dec_thread_sharing() self.assertIs(connection.allow_thread_sharing, True) connection.dec_thread_sharing() self.assertIs(connection.allow_thread_sharing, False) msg = 'Cannot decrement the thread sharing count below zero.' with self.assertRaisesMessage(RuntimeError, msg): connection.dec_thread_sharing() class MySQLPKZeroTests(TestCase): """ Zero as id for AutoField should raise exception in MySQL, because MySQL does not allow zero for autoincrement primary key. """ @skipIfDBFeature('allows_auto_pk_0') def test_zero_as_autoval(self): with self.assertRaises(ValueError): Square.objects.create(id=0, root=0, square=1) class DBConstraintTestCase(TestCase): def test_can_reference_existent(self): obj = Object.objects.create() ref = ObjectReference.objects.create(obj=obj) self.assertEqual(ref.obj, obj) ref = ObjectReference.objects.get(obj=obj) self.assertEqual(ref.obj, obj) def test_can_reference_non_existent(self): self.assertFalse(Object.objects.filter(id=12345).exists()) ref = ObjectReference.objects.create(obj_id=12345) ref_new = ObjectReference.objects.get(obj_id=12345) self.assertEqual(ref, ref_new) with self.assertRaises(Object.DoesNotExist): ref.obj def test_many_to_many(self): obj = Object.objects.create() obj.related_objects.create() self.assertEqual(Object.objects.count(), 2) self.assertEqual(obj.related_objects.count(), 1) intermediary_model = Object._meta.get_field("related_objects").remote_field.through intermediary_model.objects.create(from_object_id=obj.id, to_object_id=12345) self.assertEqual(obj.related_objects.count(), 1) self.assertEqual(intermediary_model.objects.count(), 2)
e7e405af5907acc3e814f1de2b007a0f17e5308ff07b1c3a8f593d83b7c01bdd
from django.db import models from django.template import Context, Template from django.test import SimpleTestCase, TestCase, override_settings from django.test.utils import isolate_apps from .models import ( AbstractBase1, AbstractBase2, AbstractBase3, Child1, Child2, Child3, Child4, Child5, Child6, Child7, RelatedModel, RelationModel, ) class ManagersRegressionTests(TestCase): def test_managers(self): Child1.objects.create(name='fred', data='a1') Child1.objects.create(name='barney', data='a2') Child2.objects.create(name='fred', data='b1', value=1) Child2.objects.create(name='barney', data='b2', value=42) Child3.objects.create(name='fred', data='c1', comment='yes') Child3.objects.create(name='barney', data='c2', comment='no') Child4.objects.create(name='fred', data='d1') Child4.objects.create(name='barney', data='d2') Child5.objects.create(name='fred', comment='yes') Child5.objects.create(name='barney', comment='no') Child6.objects.create(name='fred', data='f1', value=42) Child6.objects.create(name='barney', data='f2', value=42) Child7.objects.create(name='fred') Child7.objects.create(name='barney') self.assertQuerysetEqual(Child1.manager1.all(), ["<Child1: a1>"]) self.assertQuerysetEqual(Child1.manager2.all(), ["<Child1: a2>"]) self.assertQuerysetEqual(Child1._default_manager.all(), ["<Child1: a1>"]) self.assertQuerysetEqual(Child2._default_manager.all(), ["<Child2: b1>"]) self.assertQuerysetEqual(Child2.restricted.all(), ["<Child2: b2>"]) self.assertQuerysetEqual(Child3._default_manager.all(), ["<Child3: c1>"]) self.assertQuerysetEqual(Child3.manager1.all(), ["<Child3: c1>"]) self.assertQuerysetEqual(Child3.manager2.all(), ["<Child3: c2>"]) # Since Child6 inherits from Child4, the corresponding rows from f1 and # f2 also appear here. This is the expected result. self.assertQuerysetEqual(Child4._default_manager.order_by('data'), [ "<Child4: d1>", "<Child4: d2>", "<Child4: f1>", "<Child4: f2>", ]) self.assertQuerysetEqual(Child4.manager1.all(), ["<Child4: d1>", "<Child4: f1>"], ordered=False) self.assertQuerysetEqual(Child5._default_manager.all(), ["<Child5: fred>"]) self.assertQuerysetEqual(Child6._default_manager.all(), ["<Child6: f1>", "<Child6: f2>"], ordered=False) self.assertQuerysetEqual( Child7._default_manager.order_by('name'), ["<Child7: barney>", "<Child7: fred>"] ) def test_abstract_manager(self): # Accessing the manager on an abstract model should # raise an attribute error with an appropriate message. # This error message isn't ideal, but if the model is abstract and # a lot of the class instantiation logic isn't invoked; if the # manager is implied, then we don't get a hook to install the # error-raising manager. msg = "type object 'AbstractBase3' has no attribute 'objects'" with self.assertRaisesMessage(AttributeError, msg): AbstractBase3.objects.all() def test_custom_abstract_manager(self): # Accessing the manager on an abstract model with a custom # manager should raise an attribute error with an appropriate # message. msg = "Manager isn't available; AbstractBase2 is abstract" with self.assertRaisesMessage(AttributeError, msg): AbstractBase2.restricted.all() def test_explicit_abstract_manager(self): # Accessing the manager on an abstract model with an explicit # manager should raise an attribute error with an appropriate # message. msg = "Manager isn't available; AbstractBase1 is abstract" with self.assertRaisesMessage(AttributeError, msg): AbstractBase1.objects.all() @override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent') @isolate_apps('managers_regress') def test_swappable_manager(self): class SwappableModel(models.Model): class Meta: swappable = 'TEST_SWAPPABLE_MODEL' # Accessing the manager on a swappable model should # raise an attribute error with a helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'" ) with self.assertRaisesMessage(AttributeError, msg): SwappableModel.objects.all() @override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent') @isolate_apps('managers_regress') def test_custom_swappable_manager(self): class SwappableModel(models.Model): stuff = models.Manager() class Meta: swappable = 'TEST_SWAPPABLE_MODEL' # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'" ) with self.assertRaisesMessage(AttributeError, msg): SwappableModel.stuff.all() @override_settings(TEST_SWAPPABLE_MODEL='managers_regress.Parent') @isolate_apps('managers_regress') def test_explicit_swappable_manager(self): class SwappableModel(models.Model): objects = models.Manager() class Meta: swappable = 'TEST_SWAPPABLE_MODEL' # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'" ) with self.assertRaisesMessage(AttributeError, msg): SwappableModel.objects.all() def test_regress_3871(self): related = RelatedModel.objects.create() relation = RelationModel() relation.fk = related relation.gfk = related relation.save() relation.m2m.add(related) t = Template('{{ related.test_fk.all.0 }}{{ related.test_gfk.all.0 }}{{ related.test_m2m.all.0 }}') self.assertEqual( t.render(Context({'related': related})), ''.join([str(relation.pk)] * 3), ) def test_field_can_be_called_exact(self): # Make sure related managers core filters don't include an # explicit `__exact` lookup that could be interpreted as a # reference to a foreign `exact` field. refs #23940. related = RelatedModel.objects.create(exact=False) relation = related.test_fk.create() self.assertEqual(related.test_fk.get(), relation) @isolate_apps('managers_regress') class TestManagerInheritance(SimpleTestCase): def test_implicit_inheritance(self): class CustomManager(models.Manager): pass class AbstractModel(models.Model): custom_manager = CustomManager() class Meta: abstract = True class PlainModel(models.Model): custom_manager = CustomManager() self.assertIsInstance(PlainModel._base_manager, models.Manager) self.assertIsInstance(PlainModel._default_manager, CustomManager) class ModelWithAbstractParent(AbstractModel): pass self.assertIsInstance(ModelWithAbstractParent._base_manager, models.Manager) self.assertIsInstance(ModelWithAbstractParent._default_manager, CustomManager) class ProxyModel(PlainModel): class Meta: proxy = True self.assertIsInstance(ProxyModel._base_manager, models.Manager) self.assertIsInstance(ProxyModel._default_manager, CustomManager) class MTIModel(PlainModel): pass self.assertIsInstance(MTIModel._base_manager, models.Manager) self.assertIsInstance(MTIModel._default_manager, CustomManager) def test_default_manager_inheritance(self): class CustomManager(models.Manager): pass class AbstractModel(models.Model): another_manager = models.Manager() custom_manager = CustomManager() class Meta: default_manager_name = 'custom_manager' abstract = True class PlainModel(models.Model): another_manager = models.Manager() custom_manager = CustomManager() class Meta: default_manager_name = 'custom_manager' self.assertIsInstance(PlainModel._default_manager, CustomManager) class ModelWithAbstractParent(AbstractModel): pass self.assertIsInstance(ModelWithAbstractParent._default_manager, CustomManager) class ProxyModel(PlainModel): class Meta: proxy = True self.assertIsInstance(ProxyModel._default_manager, CustomManager) class MTIModel(PlainModel): pass self.assertIsInstance(MTIModel._default_manager, CustomManager) def test_base_manager_inheritance(self): class CustomManager(models.Manager): pass class AbstractModel(models.Model): another_manager = models.Manager() custom_manager = CustomManager() class Meta: base_manager_name = 'custom_manager' abstract = True class PlainModel(models.Model): another_manager = models.Manager() custom_manager = CustomManager() class Meta: base_manager_name = 'custom_manager' self.assertIsInstance(PlainModel._base_manager, CustomManager) class ModelWithAbstractParent(AbstractModel): pass self.assertIsInstance(ModelWithAbstractParent._base_manager, CustomManager) class ProxyModel(PlainModel): class Meta: proxy = True self.assertIsInstance(ProxyModel._base_manager, CustomManager) class MTIModel(PlainModel): pass self.assertIsInstance(MTIModel._base_manager, CustomManager) def test_manager_no_duplicates(self): class CustomManager(models.Manager): pass class AbstractModel(models.Model): custom_manager = models.Manager() class Meta: abstract = True class TestModel(AbstractModel): custom_manager = CustomManager() self.assertEqual(TestModel._meta.managers, (TestModel.custom_manager,)) self.assertEqual(TestModel._meta.managers_map, {'custom_manager': TestModel.custom_manager})
91994522daa20642d5f33984b212aa75ce5b523e15817499cd9e5c97c69d153c
import datetime import itertools import unittest from copy import copy from unittest import mock from django.core.management.color import no_style from django.db import ( DatabaseError, IntegrityError, OperationalError, connection, ) from django.db.models import Model, Q from django.db.models.constraints import CheckConstraint, UniqueConstraint from django.db.models.deletion import CASCADE, PROTECT from django.db.models.fields import ( AutoField, BigAutoField, BigIntegerField, BinaryField, BooleanField, CharField, DateField, DateTimeField, IntegerField, PositiveIntegerField, SlugField, TextField, TimeField, UUIDField, ) from django.db.models.fields.related import ( ForeignKey, ForeignObject, ManyToManyField, OneToOneField, ) from django.db.models.indexes import Index from django.db.transaction import TransactionManagementError, atomic from django.db.utils import DataError from django.test import ( TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import CaptureQueriesContext, isolate_apps from django.utils import timezone from .fields import ( CustomManyToManyField, InheritedManyToManyField, MediumBlobField, ) from .models import ( Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex, AuthorWithDefaultHeight, AuthorWithEvenLongerName, AuthorWithIndexedName, AuthorWithIndexedNameAndBirthday, AuthorWithUniqueName, AuthorWithUniqueNameAndBirthday, Book, BookForeignObj, BookWeak, BookWithLongName, BookWithO2O, BookWithoutAuthor, BookWithSlug, IntegerPK, Node, Note, NoteRename, Tag, TagIndexed, TagM2MTest, TagUniqueRename, Thing, UniqueTest, new_apps, ) class SchemaTests(TransactionTestCase): """ Tests for the schema-alteration code. Be aware that these tests are more liable than most to false results, as sometimes the code to check if a test has worked is almost as complex as the code it is testing. """ available_apps = [] models = [ Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex, AuthorWithDefaultHeight, AuthorWithEvenLongerName, Book, BookWeak, BookWithLongName, BookWithO2O, BookWithSlug, IntegerPK, Node, Note, Tag, TagIndexed, TagM2MTest, TagUniqueRename, Thing, UniqueTest, ] # Utility functions def setUp(self): # local_models should contain test dependent model classes that will be # automatically removed from the app cache on test tear down. self.local_models = [] # isolated_local_models contains models that are in test methods # decorated with @isolate_apps. self.isolated_local_models = [] def tearDown(self): # Delete any tables made for our models self.delete_tables() new_apps.clear_cache() for model in new_apps.get_models(): model._meta._expire_cache() if 'schema' in new_apps.all_models: for model in self.local_models: for many_to_many in model._meta.many_to_many: through = many_to_many.remote_field.through if through and through._meta.auto_created: del new_apps.all_models['schema'][through._meta.model_name] del new_apps.all_models['schema'][model._meta.model_name] if self.isolated_local_models: with connection.schema_editor() as editor: for model in self.isolated_local_models: editor.delete_model(model) def delete_tables(self): "Deletes all model tables for our models for a clean test environment" converter = connection.introspection.identifier_converter with connection.schema_editor() as editor: connection.disable_constraint_checking() table_names = connection.introspection.table_names() for model in itertools.chain(SchemaTests.models, self.local_models): tbl = converter(model._meta.db_table) if tbl in table_names: editor.delete_model(model) table_names.remove(tbl) connection.enable_constraint_checking() def column_classes(self, model): with connection.cursor() as cursor: columns = { d[0]: (connection.introspection.get_field_type(d[1], d), d) for d in connection.introspection.get_table_description( cursor, model._meta.db_table, ) } # SQLite has a different format for field_type for name, (type, desc) in columns.items(): if isinstance(type, tuple): columns[name] = (type[0], desc) # SQLite also doesn't error properly if not columns: raise DatabaseError("Table does not exist (empty pragma)") return columns def get_primary_key(self, table): with connection.cursor() as cursor: return connection.introspection.get_primary_key_column(cursor, table) def get_indexes(self, table): """ Get the indexes on the table using a new cursor. """ with connection.cursor() as cursor: return [ c['columns'][0] for c in connection.introspection.get_constraints(cursor, table).values() if c['index'] and len(c['columns']) == 1 ] def get_uniques(self, table): with connection.cursor() as cursor: return [ c['columns'][0] for c in connection.introspection.get_constraints(cursor, table).values() if c['unique'] and len(c['columns']) == 1 ] def get_constraints(self, table): """ Get the constraints on a table using a new cursor. """ with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def get_constraints_for_column(self, model, column_name): constraints = self.get_constraints(model._meta.db_table) constraints_for_column = [] for name, details in constraints.items(): if details['columns'] == [column_name]: constraints_for_column.append(name) return sorted(constraints_for_column) def check_added_field_default(self, schema_editor, model, field, field_name, expected_default, cast_function=None): with connection.cursor() as cursor: schema_editor.add_field(model, field) cursor.execute("SELECT {} FROM {};".format(field_name, model._meta.db_table)) database_default = cursor.fetchall()[0][0] if cast_function and not type(database_default) == type(expected_default): database_default = cast_function(database_default) self.assertEqual(database_default, expected_default) def get_constraints_count(self, table, column, fk_to): """ Return a dict with keys 'fks', 'uniques, and 'indexes' indicating the number of foreign keys, unique constraints, and indexes on `table`.`column`. The `fk_to` argument is a 2-tuple specifying the expected foreign key relationship's (table, column). """ with connection.cursor() as cursor: constraints = connection.introspection.get_constraints(cursor, table) counts = {'fks': 0, 'uniques': 0, 'indexes': 0} for c in constraints.values(): if c['columns'] == [column]: if c['foreign_key'] == fk_to: counts['fks'] += 1 if c['unique']: counts['uniques'] += 1 elif c['index']: counts['indexes'] += 1 return counts def assertIndexOrder(self, table, index, order): constraints = self.get_constraints(table) self.assertIn(index, constraints) index_orders = constraints[index]['orders'] self.assertTrue(all(val == expected for val, expected in zip(index_orders, order))) def assertForeignKeyExists(self, model, column, expected_fk_table, field='id'): """ Fail if the FK constraint on `model.Meta.db_table`.`column` to `expected_fk_table`.id doesn't exist. """ constraints = self.get_constraints(model._meta.db_table) constraint_fk = None for details in constraints.values(): if details['columns'] == [column] and details['foreign_key']: constraint_fk = details['foreign_key'] break self.assertEqual(constraint_fk, (expected_fk_table, field)) def assertForeignKeyNotExists(self, model, column, expected_fk_table): with self.assertRaises(AssertionError): self.assertForeignKeyExists(model, column, expected_fk_table) # Tests def test_creation_deletion(self): """ Tries creating a model's table, and then deleting it. """ with connection.schema_editor() as editor: # Create the table editor.create_model(Author) # The table is there list(Author.objects.all()) # Clean up that table editor.delete_model(Author) # No deferred SQL should be left over. self.assertEqual(editor.deferred_sql, []) # The table is gone with self.assertRaises(DatabaseError): list(Author.objects.all()) @skipUnlessDBFeature('supports_foreign_keys') def test_fk(self): "Creating tables out of FK order, then repointing, works" # Create the table with connection.schema_editor() as editor: editor.create_model(Book) editor.create_model(Author) editor.create_model(Tag) # Initial tables are there list(Author.objects.all()) list(Book.objects.all()) # Make sure the FK constraint is present with self.assertRaises(IntegrityError): Book.objects.create( author_id=1, title="Much Ado About Foreign Keys", pub_date=datetime.datetime.now(), ) # Repoint the FK constraint old_field = Book._meta.get_field("author") new_field = ForeignKey(Tag, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) self.assertForeignKeyExists(Book, 'author_id', 'schema_tag') @skipUnlessDBFeature('can_create_inline_fk') def test_inline_fk(self): # Create some tables. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) editor.create_model(Note) self.assertForeignKeyNotExists(Note, 'book_id', 'schema_book') # Add a foreign key from one to the other. with connection.schema_editor() as editor: new_field = ForeignKey(Book, CASCADE) new_field.set_attributes_from_name('book') editor.add_field(Note, new_field) self.assertForeignKeyExists(Note, 'book_id', 'schema_book') # Creating a FK field with a constraint uses a single statement without # a deferred ALTER TABLE. self.assertFalse([ sql for sql in (str(statement) for statement in editor.deferred_sql) if sql.startswith('ALTER TABLE') and 'ADD CONSTRAINT' in sql ]) @skipUnlessDBFeature('supports_foreign_keys') def test_char_field_with_db_index_to_fk(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorCharFieldWithIndex) # Change CharField to FK old_field = AuthorCharFieldWithIndex._meta.get_field('char_field') new_field = ForeignKey(Author, CASCADE, blank=True) new_field.set_attributes_from_name('char_field') with connection.schema_editor() as editor: editor.alter_field(AuthorCharFieldWithIndex, old_field, new_field, strict=True) self.assertForeignKeyExists(AuthorCharFieldWithIndex, 'char_field_id', 'schema_author') @skipUnlessDBFeature('supports_foreign_keys') @skipUnlessDBFeature('supports_index_on_text_field') def test_text_field_with_db_index_to_fk(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorTextFieldWithIndex) # Change TextField to FK old_field = AuthorTextFieldWithIndex._meta.get_field('text_field') new_field = ForeignKey(Author, CASCADE, blank=True) new_field.set_attributes_from_name('text_field') with connection.schema_editor() as editor: editor.alter_field(AuthorTextFieldWithIndex, old_field, new_field, strict=True) self.assertForeignKeyExists(AuthorTextFieldWithIndex, 'text_field_id', 'schema_author') @skipUnlessDBFeature('supports_foreign_keys') def test_fk_to_proxy(self): "Creating a FK to a proxy model creates database constraints." class AuthorProxy(Author): class Meta: app_label = 'schema' apps = new_apps proxy = True class AuthorRef(Model): author = ForeignKey(AuthorProxy, on_delete=CASCADE) class Meta: app_label = 'schema' apps = new_apps self.local_models = [AuthorProxy, AuthorRef] # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorRef) self.assertForeignKeyExists(AuthorRef, 'author_id', 'schema_author') @skipUnlessDBFeature('supports_foreign_keys') def test_fk_db_constraint(self): "The db_constraint parameter is respected" # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Author) editor.create_model(BookWeak) # Initial tables are there list(Author.objects.all()) list(Tag.objects.all()) list(BookWeak.objects.all()) self.assertForeignKeyNotExists(BookWeak, 'author_id', 'schema_author') # Make a db_constraint=False FK new_field = ForeignKey(Tag, CASCADE, db_constraint=False) new_field.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.add_field(Author, new_field) self.assertForeignKeyNotExists(Author, 'tag_id', 'schema_tag') # Alter to one with a constraint new_field2 = ForeignKey(Tag, CASCADE) new_field2.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) self.assertForeignKeyExists(Author, 'tag_id', 'schema_tag') # Alter to one without a constraint again new_field2 = ForeignKey(Tag, CASCADE) new_field2.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.alter_field(Author, new_field2, new_field, strict=True) self.assertForeignKeyNotExists(Author, 'tag_id', 'schema_tag') @isolate_apps('schema') def test_no_db_constraint_added_during_primary_key_change(self): """ When a primary key that's pointed to by a ForeignKey with db_constraint=False is altered, a foreign key constraint isn't added. """ class Author(Model): class Meta: app_label = 'schema' class BookWeak(Model): author = ForeignKey(Author, CASCADE, db_constraint=False) class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWeak) self.assertForeignKeyNotExists(BookWeak, 'author_id', 'schema_author') old_field = Author._meta.get_field('id') new_field = BigAutoField(primary_key=True) new_field.model = Author new_field.set_attributes_from_name('id') # @isolate_apps() and inner models are needed to have the model # relations populated, otherwise this doesn't act as a regression test. self.assertEqual(len(new_field.model._meta.related_objects), 1) with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertForeignKeyNotExists(BookWeak, 'author_id', 'schema_author') def _test_m2m_db_constraint(self, M2MFieldClass): class LocalAuthorWithM2M(Model): name = CharField(max_length=255) class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalAuthorWithM2M] # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(LocalAuthorWithM2M) # Initial tables are there list(LocalAuthorWithM2M.objects.all()) list(Tag.objects.all()) # Make a db_constraint=False FK new_field = M2MFieldClass(Tag, related_name="authors", db_constraint=False) new_field.contribute_to_class(LocalAuthorWithM2M, "tags") # Add the field with connection.schema_editor() as editor: editor.add_field(LocalAuthorWithM2M, new_field) self.assertForeignKeyNotExists(new_field.remote_field.through, 'tag_id', 'schema_tag') @skipUnlessDBFeature('supports_foreign_keys') def test_m2m_db_constraint(self): self._test_m2m_db_constraint(ManyToManyField) @skipUnlessDBFeature('supports_foreign_keys') def test_m2m_db_constraint_custom(self): self._test_m2m_db_constraint(CustomManyToManyField) @skipUnlessDBFeature('supports_foreign_keys') def test_m2m_db_constraint_inherited(self): self._test_m2m_db_constraint(InheritedManyToManyField) def test_add_field(self): """ Tests adding fields to models """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add the new field new_field = IntegerField(null=True) new_field.set_attributes_from_name("age") with CaptureQueriesContext(connection) as ctx, connection.schema_editor() as editor: editor.add_field(Author, new_field) drop_default_sql = editor.sql_alter_column_no_default % { 'column': editor.quote_name(new_field.name), } self.assertFalse(any(drop_default_sql in query['sql'] for query in ctx.captured_queries)) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns['age'][0], "IntegerField") self.assertEqual(columns['age'][1][6], True) def test_add_field_remove_field(self): """ Adding a field and removing it removes all deferred sql referring to it. """ with connection.schema_editor() as editor: # Create a table with a unique constraint on the slug field. editor.create_model(Tag) # Remove the slug column. editor.remove_field(Tag, Tag._meta.get_field('slug')) self.assertEqual(editor.deferred_sql, []) def test_add_field_temp_default(self): """ Tests adding fields to models with a temporary default """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = CharField(max_length=30, default="Godwin") new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns['surname'][0], "CharField") self.assertEqual(columns['surname'][1][6], connection.features.interprets_empty_strings_as_nulls) def test_add_field_temp_default_boolean(self): """ Tests adding fields to models with a temporary default where the default is False. (#21783) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = BooleanField(default=False) new_field.set_attributes_from_name("awesome") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure the field is right afterwards columns = self.column_classes(Author) # BooleanField are stored as TINYINT(1) on MySQL. field_type = columns['awesome'][0] self.assertEqual(field_type, connection.features.introspected_boolean_field_type) def test_add_field_default_transform(self): """ Tests adding fields to models with a default that is not directly valid in the database (#22581) """ class TestTransformField(IntegerField): # Weird field that saves the count of items in its value def get_default(self): return self.default def get_prep_value(self, value): if value is None: return 0 return len(value) # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add the field with a default it needs to cast (to string in this case) new_field = TestTransformField(default={1: 2}) new_field.set_attributes_from_name("thing") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure the field is there columns = self.column_classes(Author) field_type, field_info = columns['thing'] self.assertEqual(field_type, 'IntegerField') # Make sure the values were transformed correctly self.assertEqual(Author.objects.extra(where=["thing = 1"]).count(), 2) def test_add_field_binary(self): """ Tests binary fields get a sane default (#22851) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add the new field new_field = BinaryField(blank=True) new_field.set_attributes_from_name("bits") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure the field is right afterwards columns = self.column_classes(Author) # MySQL annoyingly uses the same backend, so it'll come back as one of # these two types. self.assertIn(columns['bits'][0], ("BinaryField", "TextField")) @unittest.skipUnless(connection.vendor == 'mysql', "MySQL specific") def test_add_binaryfield_mediumblob(self): """ Test adding a custom-sized binary field on MySQL (#24846). """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add the new field with default new_field = MediumBlobField(blank=True, default=b'123') new_field.set_attributes_from_name('bits') with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) # Introspection treats BLOBs as TextFields self.assertEqual(columns['bits'][0], "TextField") def test_alter(self): """ Tests simple altering of fields """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "CharField") self.assertEqual(bool(columns['name'][1][6]), bool(connection.features.interprets_empty_strings_as_nulls)) # Alter the name field to a TextField old_field = Author._meta.get_field("name") new_field = TextField(null=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "TextField") self.assertEqual(columns['name'][1][6], True) # Change nullability again new_field2 = TextField(null=False) new_field2.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "TextField") self.assertEqual(bool(columns['name'][1][6]), bool(connection.features.interprets_empty_strings_as_nulls)) def test_alter_auto_field_to_integer_field(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change AutoField to IntegerField old_field = Author._meta.get_field('id') new_field = IntegerField(primary_key=True) new_field.set_attributes_from_name('id') new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) def test_alter_auto_field_to_char_field(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change AutoField to CharField old_field = Author._meta.get_field('id') new_field = CharField(primary_key=True, max_length=50) new_field.set_attributes_from_name('id') new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) def test_alter_not_unique_field_to_primary_key(self): # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) # Change UUIDField to primary key. old_field = Author._meta.get_field('uuid') new_field = UUIDField(primary_key=True) new_field.set_attributes_from_name('uuid') new_field.model = Author with connection.schema_editor() as editor: editor.remove_field(Author, Author._meta.get_field('id')) editor.alter_field(Author, old_field, new_field, strict=True) def test_alter_text_field(self): # Regression for "BLOB/TEXT column 'info' can't have a default value") # on MySQL. # Create the table with connection.schema_editor() as editor: editor.create_model(Note) old_field = Note._meta.get_field("info") new_field = TextField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) @skipUnlessDBFeature('can_defer_constraint_checks', 'can_rollback_ddl') def test_alter_fk_checks_deferred_constraints(self): """ #25492 - Altering a foreign key's structure and data in the same transaction. """ with connection.schema_editor() as editor: editor.create_model(Node) old_field = Node._meta.get_field('parent') new_field = ForeignKey(Node, CASCADE) new_field.set_attributes_from_name('parent') parent = Node.objects.create() with connection.schema_editor() as editor: # Update the parent FK to create a deferred constraint check. Node.objects.update(parent=parent) editor.alter_field(Node, old_field, new_field, strict=True) def test_alter_text_field_to_date_field(self): """ #25002 - Test conversion of text field to date field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info='1988-05-05') old_field = Note._meta.get_field('info') new_field = DateField(blank=True) new_field.set_attributes_from_name('info') with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns['info'][1][6]) def test_alter_text_field_to_datetime_field(self): """ #25002 - Test conversion of text field to datetime field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info='1988-05-05 3:16:17.4567') old_field = Note._meta.get_field('info') new_field = DateTimeField(blank=True) new_field.set_attributes_from_name('info') with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns['info'][1][6]) def test_alter_text_field_to_time_field(self): """ #25002 - Test conversion of text field to time field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info='3:16:17.4567') old_field = Note._meta.get_field('info') new_field = TimeField(blank=True) new_field.set_attributes_from_name('info') with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns['info'][1][6]) @skipIfDBFeature('interprets_empty_strings_as_nulls') def test_alter_textual_field_keep_null_status(self): """ Changing a field type shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(Note) with self.assertRaises(IntegrityError): Note.objects.create(info=None) old_field = Note._meta.get_field("info") new_field = CharField(max_length=50) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) with self.assertRaises(IntegrityError): Note.objects.create(info=None) def test_alter_numeric_field_keep_null_status(self): """ Changing a field type shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(UniqueTest) with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=None, slug='aaa') old_field = UniqueTest._meta.get_field("year") new_field = BigIntegerField() new_field.set_attributes_from_name("year") with connection.schema_editor() as editor: editor.alter_field(UniqueTest, old_field, new_field, strict=True) with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=None, slug='bbb') def test_alter_null_to_not_null(self): """ #23609 - Tests handling of default values when altering from NULL to NOT NULL. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertTrue(columns['height'][1][6]) # Create some test data Author.objects.create(name='Not null author', height=12) Author.objects.create(name='Null author') # Verify null value self.assertEqual(Author.objects.get(name='Not null author').height, 12) self.assertIsNone(Author.objects.get(name='Null author').height) # Alter the height field to NOT NULL with default old_field = Author._meta.get_field("height") new_field = PositiveIntegerField(default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertFalse(columns['height'][1][6]) # Verify default value self.assertEqual(Author.objects.get(name='Not null author').height, 12) self.assertEqual(Author.objects.get(name='Null author').height, 42) def test_alter_charfield_to_null(self): """ #24307 - Should skip an alter statement on databases with interprets_empty_strings_as_null when changing a CharField to null. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change the CharField to null old_field = Author._meta.get_field('name') new_field = copy(old_field) new_field.null = True with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) @unittest.skipUnless(connection.vendor == 'postgresql', 'PostgreSQL specific') def test_alter_char_field_decrease_length(self): # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) Author.objects.create(name='x' * 255) # Change max_length of CharField. old_field = Author._meta.get_field('name') new_field = CharField(max_length=254) new_field.set_attributes_from_name('name') with connection.schema_editor() as editor: msg = 'value too long for type character varying(254)' with self.assertRaisesMessage(DataError, msg): editor.alter_field(Author, old_field, new_field, strict=True) def test_alter_textfield_to_null(self): """ #24307 - Should skip an alter statement on databases with interprets_empty_strings_as_null when changing a TextField to null. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Note) # Change the TextField to null old_field = Note._meta.get_field('info') new_field = copy(old_field) new_field.null = True with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) @skipUnlessDBFeature('supports_combined_alters') def test_alter_null_to_not_null_keeping_default(self): """ #23738 - Can change a nullable field with default to non-nullable with the same default. """ # Create the table with connection.schema_editor() as editor: editor.create_model(AuthorWithDefaultHeight) # Ensure the field is right to begin with columns = self.column_classes(AuthorWithDefaultHeight) self.assertTrue(columns['height'][1][6]) # Alter the height field to NOT NULL keeping the previous default old_field = AuthorWithDefaultHeight._meta.get_field("height") new_field = PositiveIntegerField(default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(AuthorWithDefaultHeight, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(AuthorWithDefaultHeight) self.assertFalse(columns['height'][1][6]) @skipUnlessDBFeature('supports_foreign_keys') def test_alter_fk(self): """ Tests altering of FKs """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the field is right to begin with columns = self.column_classes(Book) self.assertEqual(columns['author_id'][0], "IntegerField") self.assertForeignKeyExists(Book, 'author_id', 'schema_author') # Alter the FK old_field = Book._meta.get_field("author") new_field = ForeignKey(Author, CASCADE, editable=False) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Book) self.assertEqual(columns['author_id'][0], "IntegerField") self.assertForeignKeyExists(Book, 'author_id', 'schema_author') @skipUnlessDBFeature('supports_foreign_keys') def test_alter_to_fk(self): """ #24447 - Tests adding a FK constraint for an existing column """ class LocalBook(Model): author = IntegerField() title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalBook] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalBook) # Ensure no FK constraint exists constraints = self.get_constraints(LocalBook._meta.db_table) for details in constraints.values(): if details['foreign_key']: self.fail('Found an unexpected FK constraint to %s' % details['columns']) old_field = LocalBook._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(LocalBook, old_field, new_field, strict=True) self.assertForeignKeyExists(LocalBook, 'author_id', 'schema_author') @skipUnlessDBFeature('supports_foreign_keys') def test_alter_o2o_to_fk(self): """ #24163 - Tests altering of OneToOneField to ForeignKey """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) # Ensure the field is right to begin with columns = self.column_classes(BookWithO2O) self.assertEqual(columns['author_id'][0], "IntegerField") # Ensure the field is unique author = Author.objects.create(name="Joe") BookWithO2O.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now()) with self.assertRaises(IntegrityError): BookWithO2O.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now()) BookWithO2O.objects.all().delete() self.assertForeignKeyExists(BookWithO2O, 'author_id', 'schema_author') # Alter the OneToOneField to ForeignKey old_field = BookWithO2O._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Book) self.assertEqual(columns['author_id'][0], "IntegerField") # Ensure the field is not unique anymore Book.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now()) Book.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now()) self.assertForeignKeyExists(Book, 'author_id', 'schema_author') @skipUnlessDBFeature('supports_foreign_keys') def test_alter_fk_to_o2o(self): """ #24163 - Tests altering of ForeignKey to OneToOneField """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the field is right to begin with columns = self.column_classes(Book) self.assertEqual(columns['author_id'][0], "IntegerField") # Ensure the field is not unique author = Author.objects.create(name="Joe") Book.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now()) Book.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now()) Book.objects.all().delete() self.assertForeignKeyExists(Book, 'author_id', 'schema_author') # Alter the ForeignKey to OneToOneField old_field = Book._meta.get_field("author") new_field = OneToOneField(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(BookWithO2O) self.assertEqual(columns['author_id'][0], "IntegerField") # Ensure the field is unique now BookWithO2O.objects.create(author=author, title="Django 1", pub_date=datetime.datetime.now()) with self.assertRaises(IntegrityError): BookWithO2O.objects.create(author=author, title="Django 2", pub_date=datetime.datetime.now()) self.assertForeignKeyExists(BookWithO2O, 'author_id', 'schema_author') def test_alter_field_fk_to_o2o(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) expected_fks = 1 if connection.features.supports_foreign_keys else 0 # Check the index is right to begin with. counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1}) old_field = Book._meta.get_field('author') new_field = OneToOneField(Author, CASCADE) new_field.set_attributes_from_name('author') with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) # The index on ForeignKey is replaced with a unique constraint for OneToOneField. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0}) def test_alter_field_fk_keeps_index(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) expected_fks = 1 if connection.features.supports_foreign_keys else 0 # Check the index is right to begin with. counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1}) old_field = Book._meta.get_field('author') # on_delete changed from CASCADE. new_field = ForeignKey(Author, PROTECT) new_field.set_attributes_from_name('author') with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) # The index remains. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1}) def test_alter_field_o2o_to_fk(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) expected_fks = 1 if connection.features.supports_foreign_keys else 0 # Check the unique constraint is right to begin with. counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0}) old_field = BookWithO2O._meta.get_field('author') new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name('author') with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) # The unique constraint on OneToOneField is replaced with an index for ForeignKey. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 0, 'indexes': 1}) def test_alter_field_o2o_keeps_unique(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) expected_fks = 1 if connection.features.supports_foreign_keys else 0 # Check the unique constraint is right to begin with. counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0}) old_field = BookWithO2O._meta.get_field('author') # on_delete changed from CASCADE. new_field = OneToOneField(Author, PROTECT) new_field.set_attributes_from_name('author') with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field('author').column, (Author._meta.db_table, Author._meta.pk.column), ) # The unique constraint remains. self.assertEqual(counts, {'fks': expected_fks, 'uniques': 1, 'indexes': 0}) def test_alter_db_table_case(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Alter the case of the table old_table_name = Author._meta.db_table with connection.schema_editor() as editor: editor.alter_db_table(Author, old_table_name, old_table_name.upper()) def test_alter_implicit_id_to_explicit(self): """ Should be able to convert an implicit "id" field to an explicit "id" primary key field. """ with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # This will fail if DROP DEFAULT is inadvertently executed on this # field which drops the id sequence, at least on PostgreSQL. Author.objects.create(name='Foo') Author.objects.create(name='Bar') def test_alter_autofield_pk_to_bigautofield_pk_sequence_owner(self): """ Converting an implicit PK to BigAutoField(primary_key=True) should keep a sequence owner on PostgreSQL. """ with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field('id') new_field = BigAutoField(primary_key=True) new_field.set_attributes_from_name('id') new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) Author.objects.create(name='Foo', pk=1) with connection.cursor() as cursor: sequence_reset_sqls = connection.ops.sequence_reset_sql(no_style(), [Author]) if sequence_reset_sqls: cursor.execute(sequence_reset_sqls[0]) # Fail on PostgreSQL if sequence is missing an owner. self.assertIsNotNone(Author.objects.create(name='Bar')) def test_alter_int_pk_to_autofield_pk(self): """ Should be able to rename an IntegerField(primary_key=True) to AutoField(primary_key=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) old_field = IntegerPK._meta.get_field('i') new_field = AutoField(primary_key=True) new_field.model = IntegerPK new_field.set_attributes_from_name('i') with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) def test_alter_int_pk_to_bigautofield_pk(self): """ Should be able to rename an IntegerField(primary_key=True) to BigAutoField(primary_key=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) old_field = IntegerPK._meta.get_field('i') new_field = BigAutoField(primary_key=True) new_field.model = IntegerPK new_field.set_attributes_from_name('i') with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) def test_alter_int_pk_to_int_unique(self): """ Should be able to rename an IntegerField(primary_key=True) to IntegerField(unique=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) # Delete the old PK old_field = IntegerPK._meta.get_field('i') new_field = IntegerField(unique=True) new_field.model = IntegerPK new_field.set_attributes_from_name('i') with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) # The primary key constraint is gone. Result depends on database: # 'id' for SQLite, None for others (must not be 'i'). self.assertIn(self.get_primary_key(IntegerPK._meta.db_table), ('id', None)) # Set up a model class as it currently stands. The original IntegerPK # class is now out of date and some backends make use of the whole # model class when modifying a field (such as sqlite3 when remaking a # table) so an outdated model class leads to incorrect results. class Transitional(Model): i = IntegerField(unique=True) j = IntegerField(unique=True) class Meta: app_label = 'schema' apps = new_apps db_table = 'INTEGERPK' # model requires a new PK old_field = Transitional._meta.get_field('j') new_field = IntegerField(primary_key=True) new_field.model = Transitional new_field.set_attributes_from_name('j') with connection.schema_editor() as editor: editor.alter_field(Transitional, old_field, new_field, strict=True) # Create a model class representing the updated model. class IntegerUnique(Model): i = IntegerField(unique=True) j = IntegerField(primary_key=True) class Meta: app_label = 'schema' apps = new_apps db_table = 'INTEGERPK' # Ensure unique constraint works. IntegerUnique.objects.create(i=1, j=1) with self.assertRaises(IntegrityError): IntegerUnique.objects.create(i=1, j=2) def test_rename(self): """ Tests simple altering of fields """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "CharField") self.assertNotIn("display_name", columns) # Alter the name field's name old_field = Author._meta.get_field("name") new_field = CharField(max_length=254) new_field.set_attributes_from_name("display_name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # Ensure the field is right afterwards columns = self.column_classes(Author) self.assertEqual(columns['display_name'][0], "CharField") self.assertNotIn("name", columns) @isolate_apps('schema') def test_rename_referenced_field(self): class Author(Model): name = CharField(max_length=255, unique=True) class Meta: app_label = 'schema' class Book(Model): author = ForeignKey(Author, CASCADE, to_field='name') class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name('renamed') with connection.schema_editor(atomic=connection.features.supports_atomic_references_rename) as editor: editor.alter_field(Author, Author._meta.get_field('name'), new_field) # Ensure the foreign key reference was updated. self.assertForeignKeyExists(Book, 'author_id', 'schema_author', 'renamed') @skipIfDBFeature('interprets_empty_strings_as_nulls') def test_rename_keep_null_status(self): """ Renaming a field shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(Note) with self.assertRaises(IntegrityError): Note.objects.create(info=None) old_field = Note._meta.get_field("info") new_field = TextField() new_field.set_attributes_from_name("detail_info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) columns = self.column_classes(Note) self.assertEqual(columns['detail_info'][0], "TextField") self.assertNotIn("info", columns) with self.assertRaises(IntegrityError): NoteRename.objects.create(detail_info=None) def _test_m2m_create(self, M2MFieldClass): """ Tests M2M fields on models during creation """ class LocalBookWithM2M(Model): author = ForeignKey(Author, CASCADE) title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() tags = M2MFieldClass("TagM2MTest", related_name="books") class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalBookWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(TagM2MTest) editor.create_model(LocalBookWithM2M) # Ensure there is now an m2m table there columns = self.column_classes(LocalBookWithM2M._meta.get_field("tags").remote_field.through) self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField") def test_m2m_create(self): self._test_m2m_create(ManyToManyField) def test_m2m_create_custom(self): self._test_m2m_create(CustomManyToManyField) def test_m2m_create_inherited(self): self._test_m2m_create(InheritedManyToManyField) def _test_m2m_create_through(self, M2MFieldClass): """ Tests M2M fields on models during creation with through models """ class LocalTagThrough(Model): book = ForeignKey("schema.LocalBookWithM2MThrough", CASCADE) tag = ForeignKey("schema.TagM2MTest", CASCADE) class Meta: app_label = 'schema' apps = new_apps class LocalBookWithM2MThrough(Model): tags = M2MFieldClass("TagM2MTest", related_name="books", through=LocalTagThrough) class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalTagThrough, LocalBookWithM2MThrough] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalTagThrough) editor.create_model(TagM2MTest) editor.create_model(LocalBookWithM2MThrough) # Ensure there is now an m2m table there columns = self.column_classes(LocalTagThrough) self.assertEqual(columns['book_id'][0], "IntegerField") self.assertEqual(columns['tag_id'][0], "IntegerField") def test_m2m_create_through(self): self._test_m2m_create_through(ManyToManyField) def test_m2m_create_through_custom(self): self._test_m2m_create_through(CustomManyToManyField) def test_m2m_create_through_inherited(self): self._test_m2m_create_through(InheritedManyToManyField) def _test_m2m(self, M2MFieldClass): """ Tests adding/removing M2M fields on models """ class LocalAuthorWithM2M(Model): name = CharField(max_length=255) class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalAuthorWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalAuthorWithM2M) editor.create_model(TagM2MTest) # Create an M2M field new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors") new_field.contribute_to_class(LocalAuthorWithM2M, "tags") # Ensure there's no m2m table there with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Add the field with connection.schema_editor() as editor: editor.add_field(LocalAuthorWithM2M, new_field) # Ensure there is now an m2m table there columns = self.column_classes(new_field.remote_field.through) self.assertEqual(columns['tagm2mtest_id'][0], "IntegerField") # "Alter" the field. This should not rename the DB table to itself. with connection.schema_editor() as editor: editor.alter_field(LocalAuthorWithM2M, new_field, new_field, strict=True) # Remove the M2M table again with connection.schema_editor() as editor: editor.remove_field(LocalAuthorWithM2M, new_field) # Ensure there's no m2m table there with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Make sure the model state is coherent with the table one now that # we've removed the tags field. opts = LocalAuthorWithM2M._meta opts.local_many_to_many.remove(new_field) del new_apps.all_models['schema'][new_field.remote_field.through._meta.model_name] opts._expire_cache() def test_m2m(self): self._test_m2m(ManyToManyField) def test_m2m_custom(self): self._test_m2m(CustomManyToManyField) def test_m2m_inherited(self): self._test_m2m(InheritedManyToManyField) def _test_m2m_through_alter(self, M2MFieldClass): """ Tests altering M2Ms with explicit through models (should no-op) """ class LocalAuthorTag(Model): author = ForeignKey("schema.LocalAuthorWithM2MThrough", CASCADE) tag = ForeignKey("schema.TagM2MTest", CASCADE) class Meta: app_label = 'schema' apps = new_apps class LocalAuthorWithM2MThrough(Model): name = CharField(max_length=255) tags = M2MFieldClass("schema.TagM2MTest", related_name="authors", through=LocalAuthorTag) class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalAuthorTag, LocalAuthorWithM2MThrough] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalAuthorTag) editor.create_model(LocalAuthorWithM2MThrough) editor.create_model(TagM2MTest) # Ensure the m2m table is there self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3) # "Alter" the field's blankness. This should not actually do anything. old_field = LocalAuthorWithM2MThrough._meta.get_field("tags") new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors", through=LocalAuthorTag) new_field.contribute_to_class(LocalAuthorWithM2MThrough, "tags") with connection.schema_editor() as editor: editor.alter_field(LocalAuthorWithM2MThrough, old_field, new_field, strict=True) # Ensure the m2m table is still there self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3) def test_m2m_through_alter(self): self._test_m2m_through_alter(ManyToManyField) def test_m2m_through_alter_custom(self): self._test_m2m_through_alter(CustomManyToManyField) def test_m2m_through_alter_inherited(self): self._test_m2m_through_alter(InheritedManyToManyField) def _test_m2m_repoint(self, M2MFieldClass): """ Tests repointing M2M fields """ class LocalBookWithM2M(Model): author = ForeignKey(Author, CASCADE) title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() tags = M2MFieldClass("TagM2MTest", related_name="books") class Meta: app_label = 'schema' apps = new_apps self.local_models = [LocalBookWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalBookWithM2M) editor.create_model(TagM2MTest) editor.create_model(UniqueTest) # Ensure the M2M exists and points to TagM2MTest if connection.features.supports_foreign_keys: self.assertForeignKeyExists( LocalBookWithM2M._meta.get_field("tags").remote_field.through, 'tagm2mtest_id', 'schema_tagm2mtest', ) # Repoint the M2M old_field = LocalBookWithM2M._meta.get_field("tags") new_field = M2MFieldClass(UniqueTest) new_field.contribute_to_class(LocalBookWithM2M, "uniques") with connection.schema_editor() as editor: editor.alter_field(LocalBookWithM2M, old_field, new_field, strict=True) # Ensure old M2M is gone with self.assertRaises(DatabaseError): self.column_classes(LocalBookWithM2M._meta.get_field("tags").remote_field.through) # This model looks like the new model and is used for teardown. opts = LocalBookWithM2M._meta opts.local_many_to_many.remove(old_field) # Ensure the new M2M exists and points to UniqueTest if connection.features.supports_foreign_keys: self.assertForeignKeyExists(new_field.remote_field.through, 'uniquetest_id', 'schema_uniquetest') def test_m2m_repoint(self): self._test_m2m_repoint(ManyToManyField) def test_m2m_repoint_custom(self): self._test_m2m_repoint(CustomManyToManyField) def test_m2m_repoint_inherited(self): self._test_m2m_repoint(InheritedManyToManyField) @isolate_apps('schema') def test_m2m_rename_field_in_target_model(self): class LocalTagM2MTest(Model): title = CharField(max_length=255) class Meta: app_label = 'schema' class LocalM2M(Model): tags = ManyToManyField(LocalTagM2MTest) class Meta: app_label = 'schema' # Create the tables. with connection.schema_editor() as editor: editor.create_model(LocalM2M) editor.create_model(LocalTagM2MTest) self.isolated_local_models = [LocalM2M, LocalTagM2MTest] # Ensure the m2m table is there. self.assertEqual(len(self.column_classes(LocalM2M)), 1) # Alter a field in LocalTagM2MTest. old_field = LocalTagM2MTest._meta.get_field('title') new_field = CharField(max_length=254) new_field.contribute_to_class(LocalTagM2MTest, 'title1') # @isolate_apps() and inner models are needed to have the model # relations populated, otherwise this doesn't act as a regression test. self.assertEqual(len(new_field.model._meta.related_objects), 1) with connection.schema_editor() as editor: editor.alter_field(LocalTagM2MTest, old_field, new_field, strict=True) # Ensure the m2m table is still there. self.assertEqual(len(self.column_classes(LocalM2M)), 1) @skipUnlessDBFeature('supports_column_check_constraints') def test_check_constraints(self): """ Tests creating/deleting CHECK constraints """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the constraint exists constraints = self.get_constraints(Author._meta.db_table) if not any(details['columns'] == ['height'] and details['check'] for details in constraints.values()): self.fail("No check constraint for height found") # Alter the column to remove it old_field = Author._meta.get_field("height") new_field = IntegerField(null=True, blank=True) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) constraints = self.get_constraints(Author._meta.db_table) for details in constraints.values(): if details['columns'] == ["height"] and details['check']: self.fail("Check constraint for height found") # Alter the column to re-add it new_field2 = Author._meta.get_field("height") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) constraints = self.get_constraints(Author._meta.db_table) if not any(details['columns'] == ['height'] and details['check'] for details in constraints.values()): self.fail("No check constraint for height found") @skipUnlessDBFeature('supports_column_check_constraints') def test_remove_field_check_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add the custom check constraint constraint = CheckConstraint(check=Q(height__gte=0), name='author_height_gte_0_check') custom_constraint_name = constraint.name Author._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) # Ensure the constraints exist constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['height'] and details['check'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Alter the column to remove field check old_field = Author._meta.get_field('height') new_field = IntegerField(null=True, blank=True) new_field.set_attributes_from_name('height') with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['height'] and details['check'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Alter the column to re-add field check new_field2 = Author._meta.get_field('height') with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['height'] and details['check'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the check constraint with connection.schema_editor() as editor: Author._meta.constraints = [] editor.remove_constraint(Author, constraint) def test_unique(self): """ Tests removing and adding unique constraints to a single column. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure the field is unique to begin with Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Alter the slug field to be non-unique old_field = Tag._meta.get_field("slug") new_field = SlugField(unique=False) new_field.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, old_field, new_field, strict=True) # Ensure the field is no longer unique Tag.objects.create(title="foo", slug="foo") Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Alter the slug field to be unique new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field, new_field2, strict=True) # Ensure the field is unique again Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Rename the field new_field3 = SlugField(unique=True) new_field3.set_attributes_from_name("slug2") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field2, new_field3, strict=True) # Ensure the field is still unique TagUniqueRename.objects.create(title="foo", slug2="foo") with self.assertRaises(IntegrityError): TagUniqueRename.objects.create(title="bar", slug2="foo") Tag.objects.all().delete() def test_unique_name_quoting(self): old_table_name = TagUniqueRename._meta.db_table try: with connection.schema_editor() as editor: editor.create_model(TagUniqueRename) editor.alter_db_table(TagUniqueRename, old_table_name, 'unique-table') TagUniqueRename._meta.db_table = 'unique-table' # This fails if the unique index name isn't quoted. editor.alter_unique_together(TagUniqueRename, [], (('title', 'slug2'),)) finally: TagUniqueRename._meta.db_table = old_table_name @isolate_apps('schema') @unittest.skipIf(connection.vendor == 'sqlite', 'SQLite naively remakes the table on field alteration.') @skipUnlessDBFeature('supports_foreign_keys') def test_unique_no_unnecessary_fk_drops(self): """ If AlterField isn't selective about dropping foreign key constraints when modifying a field with a unique constraint, the AlterField incorrectly drops and recreates the Book.author foreign key even though it doesn't restrict the field being changed (#29193). """ class Author(Model): name = CharField(max_length=254, unique=True) class Meta: app_label = 'schema' class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) new_field = CharField(max_length=255, unique=True) new_field.model = Author new_field.set_attributes_from_name('name') with self.assertLogs('django.db.backends.schema', 'DEBUG') as cm: with connection.schema_editor() as editor: editor.alter_field(Author, Author._meta.get_field('name'), new_field) # One SQL statement is executed to alter the field. self.assertEqual(len(cm.records), 1) @isolate_apps('schema') @unittest.skipIf(connection.vendor == 'sqlite', 'SQLite remakes the table on field alteration.') def test_unique_and_reverse_m2m(self): """ AlterField can modify a unique field when there's a reverse M2M relation on the model. """ class Tag(Model): title = CharField(max_length=255) slug = SlugField(unique=True) class Meta: app_label = 'schema' class Book(Model): tags = ManyToManyField(Tag, related_name='books') class Meta: app_label = 'schema' self.isolated_local_models = [Book._meta.get_field('tags').remote_field.through] with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Book) new_field = SlugField(max_length=75, unique=True) new_field.model = Tag new_field.set_attributes_from_name('slug') with self.assertLogs('django.db.backends.schema', 'DEBUG') as cm: with connection.schema_editor() as editor: editor.alter_field(Tag, Tag._meta.get_field('slug'), new_field) # One SQL statement is executed to alter the field. self.assertEqual(len(cm.records), 1) # Ensure that the field is still unique. Tag.objects.create(title='foo', slug='foo') with self.assertRaises(IntegrityError): Tag.objects.create(title='bar', slug='foo') @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields') def test_remove_field_unique_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithUniqueName) # Add the custom unique constraint constraint = UniqueConstraint(fields=['name'], name='author_name_uniq') custom_constraint_name = constraint.name AuthorWithUniqueName._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(AuthorWithUniqueName, constraint) # Ensure the constraints exist constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Alter the column to remove field uniqueness old_field = AuthorWithUniqueName._meta.get_field('name') new_field = CharField(max_length=255) new_field.set_attributes_from_name('name') with connection.schema_editor() as editor: editor.alter_field(AuthorWithUniqueName, old_field, new_field, strict=True) constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Alter the column to re-add field uniqueness new_field2 = AuthorWithUniqueName._meta.get_field('name') with connection.schema_editor() as editor: editor.alter_field(AuthorWithUniqueName, new_field, new_field2, strict=True) constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the unique constraint with connection.schema_editor() as editor: AuthorWithUniqueName._meta.constraints = [] editor.remove_constraint(AuthorWithUniqueName, constraint) def test_unique_together(self): """ Tests removing and adding unique_together constraints on a model. """ # Create the table with connection.schema_editor() as editor: editor.create_model(UniqueTest) # Ensure the fields are unique to begin with UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2011, slug="foo") UniqueTest.objects.create(year=2011, slug="bar") with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() # Alter the model to its non-unique-together companion with connection.schema_editor() as editor: editor.alter_unique_together(UniqueTest, UniqueTest._meta.unique_together, []) # Ensure the fields are no longer unique UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() # Alter it back new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_unique_together(UniqueTest, [], UniqueTest._meta.unique_together) # Ensure the fields are unique again UniqueTest.objects.create(year=2012, slug="foo") with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() def test_unique_together_with_fk(self): """ Tests removing and adding unique_together constraints that include a foreign key. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the fields are unique to begin with self.assertEqual(Book._meta.unique_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_unique_together(Book, [], [['author', 'title']]) # Alter it back with connection.schema_editor() as editor: editor.alter_unique_together(Book, [['author', 'title']], []) def test_unique_together_with_fk_with_existing_index(self): """ Tests removing and adding unique_together constraints that include a foreign key, where the foreign key is added after the model is created. """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithoutAuthor) new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name('author') editor.add_field(BookWithoutAuthor, new_field) # Ensure the fields aren't unique to begin with self.assertEqual(Book._meta.unique_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_unique_together(Book, [], [['author', 'title']]) # Alter it back with connection.schema_editor() as editor: editor.alter_unique_together(Book, [['author', 'title']], []) @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields') def test_remove_unique_together_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithUniqueNameAndBirthday) # Add the custom unique constraint constraint = UniqueConstraint(fields=['name', 'birthday'], name='author_name_birthday_uniq') custom_constraint_name = constraint.name AuthorWithUniqueNameAndBirthday._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(AuthorWithUniqueNameAndBirthday, constraint) # Ensure the constraints exist constraints = self.get_constraints(AuthorWithUniqueNameAndBirthday._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Remove unique together unique_together = AuthorWithUniqueNameAndBirthday._meta.unique_together with connection.schema_editor() as editor: editor.alter_unique_together(AuthorWithUniqueNameAndBirthday, unique_together, []) constraints = self.get_constraints(AuthorWithUniqueNameAndBirthday._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Re-add unique together with connection.schema_editor() as editor: editor.alter_unique_together(AuthorWithUniqueNameAndBirthday, [], unique_together) constraints = self.get_constraints(AuthorWithUniqueNameAndBirthday._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['unique'] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the unique constraint with connection.schema_editor() as editor: AuthorWithUniqueNameAndBirthday._meta.constraints = [] editor.remove_constraint(AuthorWithUniqueNameAndBirthday, constraint) def test_index_together(self): """ Tests removing and adding index_together constraints on a model. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure there's no index on the year/slug columns first self.assertEqual( False, any( c["index"] for c in self.get_constraints("schema_tag").values() if c['columns'] == ["slug", "title"] ), ) # Alter the model to add an index with connection.schema_editor() as editor: editor.alter_index_together(Tag, [], [("slug", "title")]) # Ensure there is now an index self.assertEqual( True, any( c["index"] for c in self.get_constraints("schema_tag").values() if c['columns'] == ["slug", "title"] ), ) # Alter it back new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_index_together(Tag, [("slug", "title")], []) # Ensure there's no index self.assertEqual( False, any( c["index"] for c in self.get_constraints("schema_tag").values() if c['columns'] == ["slug", "title"] ), ) def test_index_together_with_fk(self): """ Tests removing and adding index_together constraints that include a foreign key. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the fields are unique to begin with self.assertEqual(Book._meta.index_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_index_together(Book, [], [['author', 'title']]) # Alter it back with connection.schema_editor() as editor: editor.alter_index_together(Book, [['author', 'title']], []) def test_create_index_together(self): """ Tests creating models with index_together already defined """ # Create the table with connection.schema_editor() as editor: editor.create_model(TagIndexed) # Ensure there is an index self.assertEqual( True, any( c["index"] for c in self.get_constraints("schema_tagindexed").values() if c['columns'] == ["slug", "title"] ), ) @skipUnlessDBFeature('allows_multiple_constraints_on_same_fields') def test_remove_index_together_does_not_remove_meta_indexes(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithIndexedNameAndBirthday) # Add the custom index index = Index(fields=['name', 'birthday'], name='author_name_birthday_idx') custom_index_name = index.name AuthorWithIndexedNameAndBirthday._meta.indexes = [index] with connection.schema_editor() as editor: editor.add_index(AuthorWithIndexedNameAndBirthday, index) # Ensure the indexes exist constraints = self.get_constraints(AuthorWithIndexedNameAndBirthday._meta.db_table) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['index'] and name != custom_index_name ] self.assertEqual(len(other_constraints), 1) # Remove index together index_together = AuthorWithIndexedNameAndBirthday._meta.index_together with connection.schema_editor() as editor: editor.alter_index_together(AuthorWithIndexedNameAndBirthday, index_together, []) constraints = self.get_constraints(AuthorWithIndexedNameAndBirthday._meta.db_table) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['index'] and name != custom_index_name ] self.assertEqual(len(other_constraints), 0) # Re-add index together with connection.schema_editor() as editor: editor.alter_index_together(AuthorWithIndexedNameAndBirthday, [], index_together) constraints = self.get_constraints(AuthorWithIndexedNameAndBirthday._meta.db_table) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details['columns'] == ['name', 'birthday'] and details['index'] and name != custom_index_name ] self.assertEqual(len(other_constraints), 1) # Drop the index with connection.schema_editor() as editor: AuthorWithIndexedNameAndBirthday._meta.indexes = [] editor.remove_index(AuthorWithIndexedNameAndBirthday, index) @isolate_apps('schema') def test_db_table(self): """ Tests renaming of the table """ class Author(Model): name = CharField(max_length=255) class Meta: app_label = 'schema' class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = 'schema' # Create the table and one referring it. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the table is there to begin with columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "CharField") # Alter the table with connection.schema_editor(atomic=connection.features.supports_atomic_references_rename) as editor: editor.alter_db_table(Author, "schema_author", "schema_otherauthor") # Ensure the table is there afterwards Author._meta.db_table = "schema_otherauthor" columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "CharField") # Ensure the foreign key reference was updated self.assertForeignKeyExists(Book, "author_id", "schema_otherauthor") # Alter the table again with connection.schema_editor(atomic=connection.features.supports_atomic_references_rename) as editor: editor.alter_db_table(Author, "schema_otherauthor", "schema_author") # Ensure the table is still there Author._meta.db_table = "schema_author" columns = self.column_classes(Author) self.assertEqual(columns['name'][0], "CharField") def test_add_remove_index(self): """ Tests index addition and removal """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the table is there and has no index self.assertNotIn('title', self.get_indexes(Author._meta.db_table)) # Add the index index = Index(fields=['name'], name='author_title_idx') with connection.schema_editor() as editor: editor.add_index(Author, index) self.assertIn('name', self.get_indexes(Author._meta.db_table)) # Drop the index with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn('name', self.get_indexes(Author._meta.db_table)) def test_remove_db_index_doesnt_remove_custom_indexes(self): """ Changing db_index to False doesn't remove indexes from Meta.indexes. """ with connection.schema_editor() as editor: editor.create_model(AuthorWithIndexedName) # Ensure the table has its index self.assertIn('name', self.get_indexes(AuthorWithIndexedName._meta.db_table)) # Add the custom index index = Index(fields=['-name'], name='author_name_idx') author_index_name = index.name with connection.schema_editor() as editor: db_index_name = editor._create_index_name( table_name=AuthorWithIndexedName._meta.db_table, column_names=('name',), ) try: AuthorWithIndexedName._meta.indexes = [index] with connection.schema_editor() as editor: editor.add_index(AuthorWithIndexedName, index) old_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table) self.assertIn(author_index_name, old_constraints) self.assertIn(db_index_name, old_constraints) # Change name field to db_index=False old_field = AuthorWithIndexedName._meta.get_field('name') new_field = CharField(max_length=255) new_field.set_attributes_from_name('name') with connection.schema_editor() as editor: editor.alter_field(AuthorWithIndexedName, old_field, new_field, strict=True) new_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table) self.assertNotIn(db_index_name, new_constraints) # The index from Meta.indexes is still in the database. self.assertIn(author_index_name, new_constraints) # Drop the index with connection.schema_editor() as editor: editor.remove_index(AuthorWithIndexedName, index) finally: AuthorWithIndexedName._meta.indexes = [] def test_order_index(self): """ Indexes defined with ordering (ASC/DESC) defined on column """ with connection.schema_editor() as editor: editor.create_model(Author) # The table doesn't have an index self.assertNotIn('title', self.get_indexes(Author._meta.db_table)) index_name = 'author_name_idx' # Add the index index = Index(fields=['name', '-weight'], name=index_name) with connection.schema_editor() as editor: editor.add_index(Author, index) if connection.features.supports_index_column_ordering: self.assertIndexOrder(Author._meta.db_table, index_name, ['ASC', 'DESC']) # Drop the index with connection.schema_editor() as editor: editor.remove_index(Author, index) def test_indexes(self): """ Tests creation/altering of indexes """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the table is there and has the right index self.assertIn( "title", self.get_indexes(Book._meta.db_table), ) # Alter to remove the index old_field = Book._meta.get_field("title") new_field = CharField(max_length=100, db_index=False) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) # Ensure the table is there and has no index self.assertNotIn( "title", self.get_indexes(Book._meta.db_table), ) # Alter to re-add the index new_field2 = Book._meta.get_field("title") with connection.schema_editor() as editor: editor.alter_field(Book, new_field, new_field2, strict=True) # Ensure the table is there and has the index again self.assertIn( "title", self.get_indexes(Book._meta.db_table), ) # Add a unique column, verify that creates an implicit index new_field3 = BookWithSlug._meta.get_field("slug") with connection.schema_editor() as editor: editor.add_field(Book, new_field3) self.assertIn( "slug", self.get_uniques(Book._meta.db_table), ) # Remove the unique, check the index goes with it new_field4 = CharField(max_length=20, unique=False) new_field4.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(BookWithSlug, new_field3, new_field4, strict=True) self.assertNotIn( "slug", self.get_uniques(Book._meta.db_table), ) def test_text_field_with_db_index(self): with connection.schema_editor() as editor: editor.create_model(AuthorTextFieldWithIndex) # The text_field index is present if the database supports it. assertion = self.assertIn if connection.features.supports_index_on_text_field else self.assertNotIn assertion('text_field', self.get_indexes(AuthorTextFieldWithIndex._meta.db_table)) def test_primary_key(self): """ Tests altering of the primary key """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure the table is there and has the right PK self.assertEqual(self.get_primary_key(Tag._meta.db_table), 'id') # Alter to change the PK id_field = Tag._meta.get_field("id") old_field = Tag._meta.get_field("slug") new_field = SlugField(primary_key=True) new_field.set_attributes_from_name("slug") new_field.model = Tag with connection.schema_editor() as editor: editor.remove_field(Tag, id_field) editor.alter_field(Tag, old_field, new_field) # Ensure the PK changed self.assertNotIn( 'id', self.get_indexes(Tag._meta.db_table), ) self.assertEqual(self.get_primary_key(Tag._meta.db_table), 'slug') def test_context_manager_exit(self): """ Ensures transaction is correctly closed when an error occurs inside a SchemaEditor context. """ class SomeError(Exception): pass try: with connection.schema_editor(): raise SomeError except SomeError: self.assertFalse(connection.in_atomic_block) @skipIfDBFeature('can_rollback_ddl') def test_unsupported_transactional_ddl_disallowed(self): message = ( "Executing DDL statements while in a transaction on databases " "that can't perform a rollback is prohibited." ) with atomic(), connection.schema_editor() as editor: with self.assertRaisesMessage(TransactionManagementError, message): editor.execute(editor.sql_create_table % {'table': 'foo', 'definition': ''}) @skipUnlessDBFeature('supports_foreign_keys') def test_foreign_key_index_long_names_regression(self): """ Regression test for #21497. Only affects databases that supports foreign keys. """ # Create the table with connection.schema_editor() as editor: editor.create_model(AuthorWithEvenLongerName) editor.create_model(BookWithLongName) # Find the properly shortened column name column_name = connection.ops.quote_name("author_foreign_key_with_really_long_field_name_id") column_name = column_name[1:-1].lower() # unquote, and, for Oracle, un-upcase # Ensure the table is there and has an index on the column self.assertIn( column_name, self.get_indexes(BookWithLongName._meta.db_table), ) @skipUnlessDBFeature('supports_foreign_keys') def test_add_foreign_key_long_names(self): """ Regression test for #23009. Only affects databases that supports foreign keys. """ # Create the initial tables with connection.schema_editor() as editor: editor.create_model(AuthorWithEvenLongerName) editor.create_model(BookWithLongName) # Add a second FK, this would fail due to long ref name before the fix new_field = ForeignKey(AuthorWithEvenLongerName, CASCADE, related_name="something") new_field.set_attributes_from_name("author_other_really_long_named_i_mean_so_long_fk") with connection.schema_editor() as editor: editor.add_field(BookWithLongName, new_field) @isolate_apps('schema') @skipUnlessDBFeature('supports_foreign_keys') def test_add_foreign_key_quoted_db_table(self): class Author(Model): class Meta: db_table = '"table_author_double_quoted"' app_label = 'schema' class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = 'schema' with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) if connection.vendor == 'mysql': self.assertForeignKeyExists(Book, 'author_id', '"table_author_double_quoted"') else: self.assertForeignKeyExists(Book, 'author_id', 'table_author_double_quoted') def test_add_foreign_object(self): with connection.schema_editor() as editor: editor.create_model(BookForeignObj) new_field = ForeignObject(Author, on_delete=CASCADE, from_fields=['author_id'], to_fields=['id']) new_field.set_attributes_from_name('author') with connection.schema_editor() as editor: editor.add_field(BookForeignObj, new_field) def test_creation_deletion_reserved_names(self): """ Tries creating a model's table, and then deleting it when it has a SQL reserved name. """ # Create the table with connection.schema_editor() as editor: try: editor.create_model(Thing) except OperationalError as e: self.fail("Errors when applying initial migration for a model " "with a table named after an SQL reserved word: %s" % e) # The table is there list(Thing.objects.all()) # Clean up that table with connection.schema_editor() as editor: editor.delete_model(Thing) # The table is gone with self.assertRaises(DatabaseError): list(Thing.objects.all()) def test_remove_constraints_capital_letters(self): """ #23065 - Constraint names must be quoted if they contain capital letters. """ def get_field(*args, field_class=IntegerField, **kwargs): kwargs['db_column'] = "CamelCase" field = field_class(*args, **kwargs) field.set_attributes_from_name("CamelCase") return field model = Author field = get_field() table = model._meta.db_table column = field.column identifier_converter = connection.introspection.identifier_converter with connection.schema_editor() as editor: editor.create_model(model) editor.add_field(model, field) constraint_name = 'CamelCaseIndex' expected_constraint_name = identifier_converter(constraint_name) editor.execute( editor.sql_create_index % { "table": editor.quote_name(table), "name": editor.quote_name(constraint_name), "using": "", "columns": editor.quote_name(column), "extra": "", "condition": "", } ) self.assertIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) editor.alter_field(model, get_field(db_index=True), field, strict=True) self.assertNotIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) constraint_name = 'CamelCaseUniqConstraint' expected_constraint_name = identifier_converter(constraint_name) editor.execute(editor._create_unique_sql(model, [field.column], constraint_name)) self.assertIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) editor.alter_field(model, get_field(unique=True), field, strict=True) self.assertNotIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) if editor.sql_create_fk: constraint_name = 'CamelCaseFKConstraint' expected_constraint_name = identifier_converter(constraint_name) editor.execute( editor.sql_create_fk % { "table": editor.quote_name(table), "name": editor.quote_name(constraint_name), "column": editor.quote_name(column), "to_table": editor.quote_name(table), "to_column": editor.quote_name(model._meta.auto_field.column), "deferrable": connection.ops.deferrable_sql(), } ) self.assertIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) editor.alter_field(model, get_field(Author, CASCADE, field_class=ForeignKey), field, strict=True) self.assertNotIn(expected_constraint_name, self.get_constraints(model._meta.db_table)) def test_add_field_use_effective_default(self): """ #23987 - effective_default() should be used as the field default when adding a new field. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no surname field columns = self.column_classes(Author) self.assertNotIn("surname", columns) # Create a row Author.objects.create(name='Anonymous1') # Add new CharField to ensure default will be used from effective_default new_field = CharField(max_length=15, blank=True) new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure field was added with the right default with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertEqual(item[0], None if connection.features.interprets_empty_strings_as_nulls else '') def test_add_field_default_dropped(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no surname field columns = self.column_classes(Author) self.assertNotIn("surname", columns) # Create a row Author.objects.create(name='Anonymous1') # Add new CharField with a default new_field = CharField(max_length=15, blank=True, default='surname default') new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure field was added with the right default with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertEqual(item[0], 'surname default') # And that the default is no longer set in the database. field = next( f for f in connection.introspection.get_table_description(cursor, "schema_author") if f.name == "surname" ) if connection.features.can_introspect_default: self.assertIsNone(field.default) def test_alter_field_default_dropped(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Create a row Author.objects.create(name='Anonymous1') self.assertIsNone(Author.objects.get().height) old_field = Author._meta.get_field('height') # The default from the new field is used in updating existing rows. new_field = IntegerField(blank=True, default=42) new_field.set_attributes_from_name('height') with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual(Author.objects.get().height, 42) # The database default should be removed. with connection.cursor() as cursor: field = next( f for f in connection.introspection.get_table_description(cursor, "schema_author") if f.name == "height" ) if connection.features.can_introspect_default: self.assertIsNone(field.default) @unittest.skipIf(connection.vendor == 'sqlite', 'SQLite naively remakes the table on field alteration.') def test_alter_field_default_doesnt_perfom_queries(self): """ No queries are performed if a field default changes and the field's not changing from null to non-null. """ with connection.schema_editor() as editor: editor.create_model(AuthorWithDefaultHeight) old_field = AuthorWithDefaultHeight._meta.get_field('height') new_default = old_field.default * 2 new_field = PositiveIntegerField(null=True, blank=True, default=new_default) new_field.set_attributes_from_name('height') with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(AuthorWithDefaultHeight, old_field, new_field, strict=True) def test_add_textfield_unhashable_default(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Create a row Author.objects.create(name='Anonymous1') # Create a field that has an unhashable default new_field = TextField(default={}) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.add_field(Author, new_field) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_add_indexed_charfield(self): field = CharField(max_length=255, db_index=True) field.set_attributes_from_name('nom_de_plume') with connection.schema_editor() as editor: editor.create_model(Author) editor.add_field(Author, field) # Should create two indexes; one for like operator. self.assertEqual( self.get_constraints_for_column(Author, 'nom_de_plume'), ['schema_author_nom_de_plume_7570a851', 'schema_author_nom_de_plume_7570a851_like'], ) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_add_unique_charfield(self): field = CharField(max_length=255, unique=True) field.set_attributes_from_name('nom_de_plume') with connection.schema_editor() as editor: editor.create_model(Author) editor.add_field(Author, field) # Should create two indexes; one for like operator. self.assertEqual( self.get_constraints_for_column(Author, 'nom_de_plume'), ['schema_author_nom_de_plume_7570a851_like', 'schema_author_nom_de_plume_key'] ) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_add_index_to_charfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, 'name'), []) # Alter to add db_index=True and create 2 indexes. old_field = Author._meta.get_field('name') new_field = CharField(max_length=255, db_index=True) new_field.set_attributes_from_name('name') with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, 'name'), ['schema_author_name_1fbc5617', 'schema_author_name_1fbc5617_like'] ) # Remove db_index=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, 'name'), []) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_add_unique_to_charfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, 'name'), []) # Alter to add unique=True and create 2 indexes. old_field = Author._meta.get_field('name') new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name('name') with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, 'name'), ['schema_author_name_1fbc5617_like', 'schema_author_name_1fbc5617_uniq'] ) # Remove unique=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, 'name'), []) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_add_index_to_textfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Note) self.assertEqual(self.get_constraints_for_column(Note, 'info'), []) # Alter to add db_index=True and create 2 indexes. old_field = Note._meta.get_field('info') new_field = TextField(db_index=True) new_field.set_attributes_from_name('info') with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Note, 'info'), ['schema_note_info_4b0ea695', 'schema_note_info_4b0ea695_like'] ) # Remove db_index=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Note, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Note, 'info'), []) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_add_unique_to_charfield_with_db_index(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like'] ) # Alter to add unique=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field('title') new_field = CharField(max_length=100, db_index=True, unique=True) new_field.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff_like', 'schema_book_title_2dfb2dff_uniq'] ) # Alter to remove unique=True (should drop unique index) new_field2 = CharField(max_length=100, db_index=True) new_field2.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like'] ) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_remove_unique_and_db_index_from_charfield(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like'] ) # Alter to add unique=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field('title') new_field = CharField(max_length=100, db_index=True, unique=True) new_field.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff_like', 'schema_book_title_2dfb2dff_uniq'] ) # Alter to remove both unique=True and db_index=True (should drop all indexes) new_field2 = CharField(max_length=100) new_field2.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual(self.get_constraints_for_column(BookWithoutAuthor, 'title'), []) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_swap_unique_and_db_index_with_charfield(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like'] ) # Alter to set unique=True and remove db_index=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field('title') new_field = CharField(max_length=100, unique=True) new_field.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff_like', 'schema_book_title_2dfb2dff_uniq'] ) # Alter to set db_index=True and remove unique=True (should restore index) new_field2 = CharField(max_length=100, db_index=True) new_field2.set_attributes_from_name('title') with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, 'title'), ['schema_book_title_2dfb2dff', 'schema_book_title_2dfb2dff_like'] ) @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific") def test_alter_field_add_db_index_to_charfield_with_unique(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(Tag) self.assertEqual( self.get_constraints_for_column(Tag, 'slug'), ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key'] ) # Alter to add db_index=True old_field = Tag._meta.get_field('slug') new_field = SlugField(db_index=True, unique=True) new_field.set_attributes_from_name('slug') with connection.schema_editor() as editor: editor.alter_field(Tag, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Tag, 'slug'), ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key'] ) # Alter to remove db_index=True new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name('slug') with connection.schema_editor() as editor: editor.alter_field(Tag, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(Tag, 'slug'), ['schema_tag_slug_2c418ba3_like', 'schema_tag_slug_key'] ) def test_alter_field_add_index_to_integerfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, 'weight'), []) # Alter to add db_index=True and create index. old_field = Author._meta.get_field('weight') new_field = IntegerField(null=True, db_index=True) new_field.set_attributes_from_name('weight') with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, 'weight'), ['schema_author_weight_587740f9']) # Remove db_index=True to drop index. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, 'weight'), []) def test_alter_pk_with_self_referential_field(self): """ Changing the primary key field name of a model with a self-referential foreign key (#26384). """ with connection.schema_editor() as editor: editor.create_model(Node) old_field = Node._meta.get_field('node_id') new_field = AutoField(primary_key=True) new_field.set_attributes_from_name('id') with connection.schema_editor() as editor: editor.alter_field(Node, old_field, new_field, strict=True) self.assertForeignKeyExists(Node, 'parent_id', Node._meta.db_table) @mock.patch('django.db.backends.base.schema.datetime') @mock.patch('django.db.backends.base.schema.timezone') def test_add_datefield_and_datetimefield_use_effective_default(self, mocked_datetime, mocked_tz): """ effective_default() should be used for DateField, DateTimeField, and TimeField if auto_now or auto_add_now is set (#25005). """ now = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1) now_tz = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1, tzinfo=timezone.utc) mocked_datetime.now = mock.MagicMock(return_value=now) mocked_tz.now = mock.MagicMock(return_value=now_tz) # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Check auto_now/auto_now_add attributes are not defined columns = self.column_classes(Author) self.assertNotIn("dob_auto_now", columns) self.assertNotIn("dob_auto_now_add", columns) self.assertNotIn("dtob_auto_now", columns) self.assertNotIn("dtob_auto_now_add", columns) self.assertNotIn("tob_auto_now", columns) self.assertNotIn("tob_auto_now_add", columns) # Create a row Author.objects.create(name='Anonymous1') # Ensure fields were added with the correct defaults dob_auto_now = DateField(auto_now=True) dob_auto_now.set_attributes_from_name('dob_auto_now') self.check_added_field_default( editor, Author, dob_auto_now, 'dob_auto_now', now.date(), cast_function=lambda x: x.date(), ) dob_auto_now_add = DateField(auto_now_add=True) dob_auto_now_add.set_attributes_from_name('dob_auto_now_add') self.check_added_field_default( editor, Author, dob_auto_now_add, 'dob_auto_now_add', now.date(), cast_function=lambda x: x.date(), ) dtob_auto_now = DateTimeField(auto_now=True) dtob_auto_now.set_attributes_from_name('dtob_auto_now') self.check_added_field_default( editor, Author, dtob_auto_now, 'dtob_auto_now', now, ) dt_tm_of_birth_auto_now_add = DateTimeField(auto_now_add=True) dt_tm_of_birth_auto_now_add.set_attributes_from_name('dtob_auto_now_add') self.check_added_field_default( editor, Author, dt_tm_of_birth_auto_now_add, 'dtob_auto_now_add', now, ) tob_auto_now = TimeField(auto_now=True) tob_auto_now.set_attributes_from_name('tob_auto_now') self.check_added_field_default( editor, Author, tob_auto_now, 'tob_auto_now', now.time(), cast_function=lambda x: x.time(), ) tob_auto_now_add = TimeField(auto_now_add=True) tob_auto_now_add.set_attributes_from_name('tob_auto_now_add') self.check_added_field_default( editor, Author, tob_auto_now_add, 'tob_auto_now_add', now.time(), cast_function=lambda x: x.time(), ) def test_namespaced_db_table_create_index_name(self): """ Table names are stripped of their namespace/schema before being used to generate index names. """ with connection.schema_editor() as editor: max_name_length = connection.ops.max_name_length() or 200 namespace = 'n' * max_name_length table_name = 't' * max_name_length namespaced_table_name = '"%s"."%s"' % (namespace, table_name) self.assertEqual( editor._create_index_name(table_name, []), editor._create_index_name(namespaced_table_name, []), ) @unittest.skipUnless(connection.vendor == 'oracle', 'Oracle specific db_table syntax') def test_creation_with_db_table_double_quotes(self): oracle_user = connection.creation._test_database_user() class Student(Model): name = CharField(max_length=30) class Meta: app_label = 'schema' apps = new_apps db_table = '"%s"."DJANGO_STUDENT_TABLE"' % oracle_user class Document(Model): name = CharField(max_length=30) students = ManyToManyField(Student) class Meta: app_label = 'schema' apps = new_apps db_table = '"%s"."DJANGO_DOCUMENT_TABLE"' % oracle_user self.local_models = [Student, Document] with connection.schema_editor() as editor: editor.create_model(Student) editor.create_model(Document) doc = Document.objects.create(name='Test Name') student = Student.objects.create(name='Some man') doc.students.add(student) def test_rename_table_renames_deferred_sql_references(self): atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: editor.create_model(Author) editor.create_model(Book) editor.alter_db_table(Author, 'schema_author', 'schema_renamed_author') editor.alter_db_table(Author, 'schema_book', 'schema_renamed_book') self.assertGreater(len(editor.deferred_sql), 0) for statement in editor.deferred_sql: self.assertIs(statement.references_table('schema_author'), False) self.assertIs(statement.references_table('schema_book'), False) @unittest.skipIf(connection.vendor == 'sqlite', 'SQLite naively remakes the table on field alteration.') def test_rename_column_renames_deferred_sql_references(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) old_title = Book._meta.get_field('title') new_title = CharField(max_length=100, db_index=True) new_title.set_attributes_from_name('renamed_title') editor.alter_field(Book, old_title, new_title) old_author = Book._meta.get_field('author') new_author = ForeignKey(Author, CASCADE) new_author.set_attributes_from_name('renamed_author') editor.alter_field(Book, old_author, new_author) self.assertGreater(len(editor.deferred_sql), 0) for statement in editor.deferred_sql: self.assertIs(statement.references_column('book', 'title'), False) self.assertIs(statement.references_column('book', 'author_id'), False) @isolate_apps('schema') def test_referenced_field_without_constraint_rename_inside_atomic_block(self): """ Foreign keys without database level constraint don't prevent the field they reference from being renamed in an atomic block. """ class Foo(Model): field = CharField(max_length=255, unique=True) class Meta: app_label = 'schema' class Bar(Model): foo = ForeignKey(Foo, CASCADE, to_field='field', db_constraint=False) class Meta: app_label = 'schema' self.isolated_local_models = [Foo, Bar] with connection.schema_editor() as editor: editor.create_model(Foo) editor.create_model(Bar) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name('renamed') with connection.schema_editor(atomic=True) as editor: editor.alter_field(Foo, Foo._meta.get_field('field'), new_field) @isolate_apps('schema') def test_referenced_table_without_constraint_rename_inside_atomic_block(self): """ Foreign keys without database level constraint don't prevent the table they reference from being renamed in an atomic block. """ class Foo(Model): field = CharField(max_length=255, unique=True) class Meta: app_label = 'schema' class Bar(Model): foo = ForeignKey(Foo, CASCADE, to_field='field', db_constraint=False) class Meta: app_label = 'schema' self.isolated_local_models = [Foo, Bar] with connection.schema_editor() as editor: editor.create_model(Foo) editor.create_model(Bar) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name('renamed') with connection.schema_editor(atomic=True) as editor: editor.alter_db_table(Foo, Foo._meta.db_table, 'renamed_table') Foo._meta.db_table = 'renamed_table'
364a8cbd6c1f6a97845782ad0c1ad24c347489db1dfe4f5e483f97248d26c7f3
from django.apps.registry import Apps from django.db import models # Because we want to test creation and deletion of these as separate things, # these models are all inserted into a separate Apps so the main test # runner doesn't migrate them. new_apps = Apps() class Author(models.Model): name = models.CharField(max_length=255) height = models.PositiveIntegerField(null=True, blank=True) weight = models.IntegerField(null=True, blank=True) uuid = models.UUIDField(null=True) class Meta: apps = new_apps class AuthorCharFieldWithIndex(models.Model): char_field = models.CharField(max_length=31, db_index=True) class Meta: apps = new_apps class AuthorTextFieldWithIndex(models.Model): text_field = models.TextField(db_index=True) class Meta: apps = new_apps class AuthorWithDefaultHeight(models.Model): name = models.CharField(max_length=255) height = models.PositiveIntegerField(null=True, blank=True, default=42) class Meta: apps = new_apps class AuthorWithEvenLongerName(models.Model): name = models.CharField(max_length=255) height = models.PositiveIntegerField(null=True, blank=True) class Meta: apps = new_apps class AuthorWithIndexedName(models.Model): name = models.CharField(max_length=255, db_index=True) class Meta: apps = new_apps class AuthorWithUniqueName(models.Model): name = models.CharField(max_length=255, unique=True) class Meta: apps = new_apps class AuthorWithIndexedNameAndBirthday(models.Model): name = models.CharField(max_length=255) birthday = models.DateField() class Meta: apps = new_apps index_together = [['name', 'birthday']] class AuthorWithUniqueNameAndBirthday(models.Model): name = models.CharField(max_length=255) birthday = models.DateField() class Meta: apps = new_apps unique_together = [['name', 'birthday']] class Book(models.Model): author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() # tags = models.ManyToManyField("Tag", related_name="books") class Meta: apps = new_apps class BookWeak(models.Model): author = models.ForeignKey(Author, models.CASCADE, db_constraint=False) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() class Meta: apps = new_apps class BookWithLongName(models.Model): author_foreign_key_with_really_long_field_name = models.ForeignKey( AuthorWithEvenLongerName, models.CASCADE, ) class Meta: apps = new_apps class BookWithO2O(models.Model): author = models.OneToOneField(Author, models.CASCADE) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() class Meta: apps = new_apps db_table = "schema_book" class BookWithSlug(models.Model): author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() slug = models.CharField(max_length=20, unique=True) class Meta: apps = new_apps db_table = "schema_book" class BookWithoutAuthor(models.Model): title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() class Meta: apps = new_apps db_table = "schema_book" class BookForeignObj(models.Model): title = models.CharField(max_length=100, db_index=True) author_id = models.IntegerField() class Meta: apps = new_apps class IntegerPK(models.Model): i = models.IntegerField(primary_key=True) j = models.IntegerField(unique=True) class Meta: apps = new_apps db_table = "INTEGERPK" # uppercase to ensure proper quoting class Note(models.Model): info = models.TextField() class Meta: apps = new_apps class NoteRename(models.Model): detail_info = models.TextField() class Meta: apps = new_apps db_table = "schema_note" class Tag(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) class Meta: apps = new_apps class TagIndexed(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) class Meta: apps = new_apps index_together = [["slug", "title"]] class TagM2MTest(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) class Meta: apps = new_apps class TagUniqueRename(models.Model): title = models.CharField(max_length=255) slug2 = models.SlugField(unique=True) class Meta: apps = new_apps db_table = "schema_tag" # Based on tests/reserved_names/models.py class Thing(models.Model): when = models.CharField(max_length=1, primary_key=True) class Meta: db_table = 'drop' def __str__(self): return self.when class UniqueTest(models.Model): year = models.IntegerField() slug = models.SlugField(unique=False) class Meta: apps = new_apps unique_together = ["year", "slug"] class Node(models.Model): node_id = models.AutoField(primary_key=True) parent = models.ForeignKey('self', models.CASCADE, null=True, blank=True) class Meta: apps = new_apps
61b54736ca1bbc3c775db559f9cdbee393b2a9f876357f8d8ae1b8eedaf3a70b
from django.contrib.admin import ModelAdmin, TabularInline from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import RequestFactory, TestCase, override_settings from django.urls import reverse from .admin import InnerInline, site as admin_site from .models import ( Author, BinaryTree, Book, Chapter, Child, ChildModel1, ChildModel2, Fashionista, FootNote, Holder, Holder2, Holder3, Holder4, Inner, Inner2, Inner3, Inner4Stacked, Inner4Tabular, Novel, OutfitItem, Parent, ParentModelWithCustomPk, Person, Poll, Profile, ProfileCollection, Question, Sighting, SomeChildModel, SomeParentModel, Teacher, ) INLINE_CHANGELINK_HTML = 'class="inlinechangelink">Change</a>' class TestDataMixin: @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser(username='super', email='[email protected]', password='secret') @override_settings(ROOT_URLCONF='admin_inlines.urls') class TestInline(TestDataMixin, TestCase): factory = RequestFactory() @classmethod def setUpTestData(cls): super().setUpTestData() cls.holder = Holder.objects.create(dummy=13) Inner.objects.create(dummy=42, holder=cls.holder) def setUp(self): self.client.force_login(self.superuser) def test_can_delete(self): """ can_delete should be passed to inlineformset factory. """ response = self.client.get( reverse('admin:admin_inlines_holder_change', args=(self.holder.id,)) ) inner_formset = response.context['inline_admin_formsets'][0].formset expected = InnerInline.can_delete actual = inner_formset.can_delete self.assertEqual(expected, actual, 'can_delete must be equal') def test_readonly_stacked_inline_label(self): """Bug #13174.""" holder = Holder.objects.create(dummy=42) Inner.objects.create(holder=holder, dummy=42, readonly='') response = self.client.get( reverse('admin:admin_inlines_holder_change', args=(holder.id,)) ) self.assertContains(response, '<label>Inner readonly label:</label>') def test_many_to_many_inlines(self): "Autogenerated many-to-many inlines are displayed correctly (#13407)" response = self.client.get(reverse('admin:admin_inlines_author_add')) # The heading for the m2m inline block uses the right text self.assertContains(response, '<h2>Author-book relationships</h2>') # The "add another" label is correct self.assertContains(response, 'Add another Author-book relationship') # The '+' is dropped from the autogenerated form prefix (Author_books+) self.assertContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_primary(self): person = Person.objects.create(firstname='Imelda') item = OutfitItem.objects.create(name='Shoes') # Imelda likes shoes, but can't carry her own bags. data = { 'shoppingweakness_set-TOTAL_FORMS': 1, 'shoppingweakness_set-INITIAL_FORMS': 0, 'shoppingweakness_set-MAX_NUM_FORMS': 0, '_save': 'Save', 'person': person.id, 'max_weight': 0, 'shoppingweakness_set-0-item': item.id, } response = self.client.post(reverse('admin:admin_inlines_fashionista_add'), data) self.assertEqual(response.status_code, 302) self.assertEqual(len(Fashionista.objects.filter(person__firstname='Imelda')), 1) def test_tabular_inline_column_css_class(self): """ Field names are included in the context to output a field-specific CSS class name in the column headers. """ response = self.client.get(reverse('admin:admin_inlines_poll_add')) text_field, call_me_field = list(response.context['inline_admin_formset'].fields()) # Editable field. self.assertEqual(text_field['name'], 'text') self.assertContains(response, '<th class="column-text required">') # Read-only field. self.assertEqual(call_me_field['name'], 'call_me') self.assertContains(response, '<th class="column-call_me">') def test_custom_form_tabular_inline_label(self): """ A model form with a form field specified (TitleForm.title1) should have its label rendered in the tabular inline. """ response = self.client.get(reverse('admin:admin_inlines_titlecollection_add')) self.assertContains(response, '<th class="column-title1 required">Title1</th>', html=True) def test_custom_form_tabular_inline_extra_field_label(self): response = self.client.get(reverse('admin:admin_inlines_outfititem_add')) _, extra_field = list(response.context['inline_admin_formset'].fields()) self.assertEqual(extra_field['label'], 'Extra field') def test_non_editable_custom_form_tabular_inline_extra_field_label(self): response = self.client.get(reverse('admin:admin_inlines_chapter_add')) _, extra_field = list(response.context['inline_admin_formset'].fields()) self.assertEqual(extra_field['label'], 'Extra field') def test_custom_form_tabular_inline_overridden_label(self): """ SomeChildModelForm.__init__() overrides the label of a form field. That label is displayed in the TabularInline. """ response = self.client.get(reverse('admin:admin_inlines_someparentmodel_add')) field = list(response.context['inline_admin_formset'].fields())[0] self.assertEqual(field['label'], 'new label') self.assertContains(response, '<th class="column-name required">New label</th>', html=True) def test_tabular_non_field_errors(self): """ non_field_errors are displayed correctly, including the correct value for colspan. """ data = { 'title_set-TOTAL_FORMS': 1, 'title_set-INITIAL_FORMS': 0, 'title_set-MAX_NUM_FORMS': 0, '_save': 'Save', 'title_set-0-title1': 'a title', 'title_set-0-title2': 'a different title', } response = self.client.post(reverse('admin:admin_inlines_titlecollection_add'), data) # Here colspan is "4": two fields (title1 and title2), one hidden field and the delete checkbox. self.assertContains( response, '<tr><td colspan="4"><ul class="errorlist nonfield">' '<li>The two titles must be the same</li></ul></td></tr>' ) def test_no_parent_callable_lookup(self): """Admin inline `readonly_field` shouldn't invoke parent ModelAdmin callable""" # Identically named callable isn't present in the parent ModelAdmin, # rendering of the add view shouldn't explode response = self.client.get(reverse('admin:admin_inlines_novel_add')) self.assertEqual(response.status_code, 200) # View should have the child inlines section self.assertContains( response, '<div class="js-inline-admin-formset inline-group" id="chapter_set-group"' ) def test_callable_lookup(self): """Admin inline should invoke local callable when its name is listed in readonly_fields""" response = self.client.get(reverse('admin:admin_inlines_poll_add')) self.assertEqual(response.status_code, 200) # Add parent object view should have the child inlines section self.assertContains( response, '<div class="js-inline-admin-formset inline-group" id="question_set-group"' ) # The right callable should be used for the inline readonly_fields # column cells self.assertContains(response, '<p>Callable in QuestionInline</p>') def test_help_text(self): """ The inlines' model field help texts are displayed when using both the stacked and tabular layouts. """ response = self.client.get(reverse('admin:admin_inlines_holder4_add')) self.assertContains(response, '<div class="help">Awesome stacked help text is awesome.</div>', 4) self.assertContains( response, '<img src="/static/admin/img/icon-unknown.svg" ' 'class="help help-tooltip" width="10" height="10" ' 'alt="(Awesome tabular help text is awesome.)" ' 'title="Awesome tabular help text is awesome.">', 1 ) # ReadOnly fields response = self.client.get(reverse('admin:admin_inlines_capofamiglia_add')) self.assertContains( response, '<img src="/static/admin/img/icon-unknown.svg" ' 'class="help help-tooltip" width="10" height="10" ' 'alt="(Help text for ReadOnlyInline)" ' 'title="Help text for ReadOnlyInline">', 1 ) def test_tabular_model_form_meta_readonly_field(self): """ Tabular inlines use ModelForm.Meta.help_texts and labels for read-only fields. """ response = self.client.get(reverse('admin:admin_inlines_someparentmodel_add')) self.assertContains( response, '<img src="/static/admin/img/icon-unknown.svg" ' 'class="help help-tooltip" width="10" height="10" ' 'alt="(Help text from ModelForm.Meta)" ' 'title="Help text from ModelForm.Meta">' ) self.assertContains(response, 'Label from ModelForm.Meta') def test_inline_hidden_field_no_column(self): """#18263 -- Make sure hidden fields don't get a column in tabular inlines""" parent = SomeParentModel.objects.create(name='a') SomeChildModel.objects.create(name='b', position='0', parent=parent) SomeChildModel.objects.create(name='c', position='1', parent=parent) response = self.client.get(reverse('admin:admin_inlines_someparentmodel_change', args=(parent.pk,))) self.assertNotContains(response, '<td class="field-position">') self.assertInHTML( '<input id="id_somechildmodel_set-1-position" ' 'name="somechildmodel_set-1-position" type="hidden" value="1">', response.rendered_content, ) def test_non_related_name_inline(self): """ Multiple inlines with related_name='+' have correct form prefixes. """ response = self.client.get(reverse('admin:admin_inlines_capofamiglia_add')) self.assertContains(response, '<input type="hidden" name="-1-0-id" id="id_-1-0-id">', html=True) self.assertContains( response, '<input type="hidden" name="-1-0-capo_famiglia" id="id_-1-0-capo_famiglia">', html=True ) self.assertContains( response, '<input id="id_-1-0-name" type="text" class="vTextField" name="-1-0-name" maxlength="100">', html=True ) self.assertContains(response, '<input type="hidden" name="-2-0-id" id="id_-2-0-id">', html=True) self.assertContains( response, '<input type="hidden" name="-2-0-capo_famiglia" id="id_-2-0-capo_famiglia">', html=True ) self.assertContains( response, '<input id="id_-2-0-name" type="text" class="vTextField" name="-2-0-name" maxlength="100">', html=True ) @override_settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True) def test_localize_pk_shortcut(self): """ The "View on Site" link is correct for locales that use thousand separators. """ holder = Holder.objects.create(pk=123456789, dummy=42) inner = Inner.objects.create(pk=987654321, holder=holder, dummy=42, readonly='') response = self.client.get(reverse('admin:admin_inlines_holder_change', args=(holder.id,))) inner_shortcut = 'r/%s/%s/' % (ContentType.objects.get_for_model(inner).pk, inner.pk) self.assertContains(response, inner_shortcut) def test_custom_pk_shortcut(self): """ The "View on Site" link is correct for models with a custom primary key field. """ parent = ParentModelWithCustomPk.objects.create(my_own_pk="foo", name="Foo") child1 = ChildModel1.objects.create(my_own_pk="bar", name="Bar", parent=parent) child2 = ChildModel2.objects.create(my_own_pk="baz", name="Baz", parent=parent) response = self.client.get(reverse('admin:admin_inlines_parentmodelwithcustompk_change', args=('foo',))) child1_shortcut = 'r/%s/%s/' % (ContentType.objects.get_for_model(child1).pk, child1.pk) child2_shortcut = 'r/%s/%s/' % (ContentType.objects.get_for_model(child2).pk, child2.pk) self.assertContains(response, child1_shortcut) self.assertContains(response, child2_shortcut) def test_create_inlines_on_inherited_model(self): """ An object can be created with inlines when it inherits another class. """ data = { 'name': 'Martian', 'sighting_set-TOTAL_FORMS': 1, 'sighting_set-INITIAL_FORMS': 0, 'sighting_set-MAX_NUM_FORMS': 0, 'sighting_set-0-place': 'Zone 51', '_save': 'Save', } response = self.client.post(reverse('admin:admin_inlines_extraterrestrial_add'), data) self.assertEqual(response.status_code, 302) self.assertEqual(Sighting.objects.filter(et__name='Martian').count(), 1) def test_custom_get_extra_form(self): bt_head = BinaryTree.objects.create(name="Tree Head") BinaryTree.objects.create(name="First Child", parent=bt_head) # The maximum number of forms should respect 'get_max_num' on the # ModelAdmin max_forms_input = ( '<input id="id_binarytree_set-MAX_NUM_FORMS" ' 'name="binarytree_set-MAX_NUM_FORMS" type="hidden" value="%d">' ) # The total number of forms will remain the same in either case total_forms_hidden = ( '<input id="id_binarytree_set-TOTAL_FORMS" ' 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="2">' ) response = self.client.get(reverse('admin:admin_inlines_binarytree_add')) self.assertInHTML(max_forms_input % 3, response.rendered_content) self.assertInHTML(total_forms_hidden, response.rendered_content) response = self.client.get(reverse('admin:admin_inlines_binarytree_change', args=(bt_head.id,))) self.assertInHTML(max_forms_input % 2, response.rendered_content) self.assertInHTML(total_forms_hidden, response.rendered_content) def test_min_num(self): """ min_num and extra determine number of forms. """ class MinNumInline(TabularInline): model = BinaryTree min_num = 2 extra = 3 modeladmin = ModelAdmin(BinaryTree, admin_site) modeladmin.inlines = [MinNumInline] min_forms = ( '<input id="id_binarytree_set-MIN_NUM_FORMS" ' 'name="binarytree_set-MIN_NUM_FORMS" type="hidden" value="2">' ) total_forms = ( '<input id="id_binarytree_set-TOTAL_FORMS" ' 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="5">' ) request = self.factory.get(reverse('admin:admin_inlines_binarytree_add')) request.user = User(username='super', is_superuser=True) response = modeladmin.changeform_view(request) self.assertInHTML(min_forms, response.rendered_content) self.assertInHTML(total_forms, response.rendered_content) def test_custom_min_num(self): bt_head = BinaryTree.objects.create(name="Tree Head") BinaryTree.objects.create(name="First Child", parent=bt_head) class MinNumInline(TabularInline): model = BinaryTree extra = 3 def get_min_num(self, request, obj=None, **kwargs): if obj: return 5 return 2 modeladmin = ModelAdmin(BinaryTree, admin_site) modeladmin.inlines = [MinNumInline] min_forms = ( '<input id="id_binarytree_set-MIN_NUM_FORMS" ' 'name="binarytree_set-MIN_NUM_FORMS" type="hidden" value="%d">' ) total_forms = ( '<input id="id_binarytree_set-TOTAL_FORMS" ' 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="%d">' ) request = self.factory.get(reverse('admin:admin_inlines_binarytree_add')) request.user = User(username='super', is_superuser=True) response = modeladmin.changeform_view(request) self.assertInHTML(min_forms % 2, response.rendered_content) self.assertInHTML(total_forms % 5, response.rendered_content) request = self.factory.get(reverse('admin:admin_inlines_binarytree_change', args=(bt_head.id,))) request.user = User(username='super', is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(bt_head.id)) self.assertInHTML(min_forms % 5, response.rendered_content) self.assertInHTML(total_forms % 8, response.rendered_content) def test_inline_nonauto_noneditable_pk(self): response = self.client.get(reverse('admin:admin_inlines_author_add')) self.assertContains( response, '<input id="id_nonautopkbook_set-0-rand_pk" ' 'name="nonautopkbook_set-0-rand_pk" type="hidden">', html=True ) self.assertContains( response, '<input id="id_nonautopkbook_set-2-0-rand_pk" ' 'name="nonautopkbook_set-2-0-rand_pk" type="hidden">', html=True ) def test_inline_nonauto_noneditable_inherited_pk(self): response = self.client.get(reverse('admin:admin_inlines_author_add')) self.assertContains( response, '<input id="id_nonautopkbookchild_set-0-nonautopkbook_ptr" ' 'name="nonautopkbookchild_set-0-nonautopkbook_ptr" type="hidden">', html=True ) self.assertContains( response, '<input id="id_nonautopkbookchild_set-2-nonautopkbook_ptr" ' 'name="nonautopkbookchild_set-2-nonautopkbook_ptr" type="hidden">', html=True ) def test_inline_editable_pk(self): response = self.client.get(reverse('admin:admin_inlines_author_add')) self.assertContains( response, '<input class="vIntegerField" id="id_editablepkbook_set-0-manual_pk" ' 'name="editablepkbook_set-0-manual_pk" type="number">', html=True, count=1 ) self.assertContains( response, '<input class="vIntegerField" id="id_editablepkbook_set-2-0-manual_pk" ' 'name="editablepkbook_set-2-0-manual_pk" type="number">', html=True, count=1 ) def test_stacked_inline_edit_form_contains_has_original_class(self): holder = Holder.objects.create(dummy=1) holder.inner_set.create(dummy=1) response = self.client.get(reverse('admin:admin_inlines_holder_change', args=(holder.pk,))) self.assertContains( response, '<div class="inline-related has_original" id="inner_set-0">', count=1 ) self.assertContains( response, '<div class="inline-related" id="inner_set-1">', count=1 ) def test_inlines_show_change_link_registered(self): "Inlines `show_change_link` for registered models when enabled." holder = Holder4.objects.create(dummy=1) item1 = Inner4Stacked.objects.create(dummy=1, holder=holder) item2 = Inner4Tabular.objects.create(dummy=1, holder=holder) items = ( ('inner4stacked', item1.pk), ('inner4tabular', item2.pk), ) response = self.client.get(reverse('admin:admin_inlines_holder4_change', args=(holder.pk,))) self.assertTrue(response.context['inline_admin_formset'].opts.has_registered_model) for model, pk in items: url = reverse('admin:admin_inlines_%s_change' % model, args=(pk,)) self.assertContains(response, '<a href="%s" %s' % (url, INLINE_CHANGELINK_HTML)) def test_inlines_show_change_link_unregistered(self): "Inlines `show_change_link` disabled for unregistered models." parent = ParentModelWithCustomPk.objects.create(my_own_pk="foo", name="Foo") ChildModel1.objects.create(my_own_pk="bar", name="Bar", parent=parent) ChildModel2.objects.create(my_own_pk="baz", name="Baz", parent=parent) response = self.client.get(reverse('admin:admin_inlines_parentmodelwithcustompk_change', args=('foo',))) self.assertFalse(response.context['inline_admin_formset'].opts.has_registered_model) self.assertNotContains(response, INLINE_CHANGELINK_HTML) def test_tabular_inline_show_change_link_false_registered(self): "Inlines `show_change_link` disabled by default." poll = Poll.objects.create(name="New poll") Question.objects.create(poll=poll) response = self.client.get(reverse('admin:admin_inlines_poll_change', args=(poll.pk,))) self.assertTrue(response.context['inline_admin_formset'].opts.has_registered_model) self.assertNotContains(response, INLINE_CHANGELINK_HTML) def test_noneditable_inline_has_field_inputs(self): """Inlines without change permission shows field inputs on add form.""" response = self.client.get(reverse('admin:admin_inlines_novelreadonlychapter_add')) self.assertContains( response, '<input type="text" name="chapter_set-0-name" ' 'class="vTextField" maxlength="40" id="id_chapter_set-0-name">', html=True ) @override_settings(ROOT_URLCONF='admin_inlines.urls') class TestInlineMedia(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_inline_media_only_base(self): holder = Holder(dummy=13) holder.save() Inner(dummy=42, holder=holder).save() change_url = reverse('admin:admin_inlines_holder_change', args=(holder.id,)) response = self.client.get(change_url) self.assertContains(response, 'my_awesome_admin_scripts.js') def test_inline_media_only_inline(self): holder = Holder3(dummy=13) holder.save() Inner3(dummy=42, holder=holder).save() change_url = reverse('admin:admin_inlines_holder3_change', args=(holder.id,)) response = self.client.get(change_url) self.assertEqual( response.context['inline_admin_formsets'][0].media._js, [ 'admin/js/vendor/jquery/jquery.min.js', 'my_awesome_inline_scripts.js', 'custom_number.js', 'admin/js/jquery.init.js', 'admin/js/inlines.min.js', ] ) self.assertContains(response, 'my_awesome_inline_scripts.js') def test_all_inline_media(self): holder = Holder2(dummy=13) holder.save() Inner2(dummy=42, holder=holder).save() change_url = reverse('admin:admin_inlines_holder2_change', args=(holder.id,)) response = self.client.get(change_url) self.assertContains(response, 'my_awesome_admin_scripts.js') self.assertContains(response, 'my_awesome_inline_scripts.js') @override_settings(ROOT_URLCONF='admin_inlines.urls') class TestInlineAdminForm(TestCase): def test_immutable_content_type(self): """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.""" 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_type, parent_ct) @override_settings(ROOT_URLCONF='admin_inlines.urls') class TestInlineProtectedOnDelete(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_deleting_inline_with_protected_delete_does_not_validate(self): lotr = Novel.objects.create(name='Lord of the rings') chapter = Chapter.objects.create(novel=lotr, name='Many Meetings') foot_note = FootNote.objects.create(chapter=chapter, note='yadda yadda') change_url = reverse('admin:admin_inlines_novel_change', args=(lotr.id,)) response = self.client.get(change_url) data = { 'name': lotr.name, 'chapter_set-TOTAL_FORMS': 1, 'chapter_set-INITIAL_FORMS': 1, 'chapter_set-MAX_NUM_FORMS': 1000, '_save': 'Save', 'chapter_set-0-id': chapter.id, 'chapter_set-0-name': chapter.name, 'chapter_set-0-novel': lotr.id, 'chapter_set-0-DELETE': 'on' } response = self.client.post(change_url, data) self.assertContains(response, "Deleting chapter %s would require deleting " "the following protected related objects: foot note %s" % (chapter, foot_note)) @override_settings(ROOT_URLCONF='admin_inlines.urls') class TestInlinePermissions(TestCase): """ Make sure the admin respects permissions for objects that are edited inline. Refs #8060. """ @classmethod def setUpTestData(cls): cls.user = User(username='admin', is_staff=True, is_active=True) cls.user.set_password('secret') cls.user.save() cls.author_ct = ContentType.objects.get_for_model(Author) cls.holder_ct = ContentType.objects.get_for_model(Holder2) cls.book_ct = ContentType.objects.get_for_model(Book) cls.inner_ct = ContentType.objects.get_for_model(Inner2) # User always has permissions to add and change Authors, and Holders, # the main (parent) models of the inlines. Permissions on the inlines # vary per test. permission = Permission.objects.get(codename='add_author', content_type=cls.author_ct) cls.user.user_permissions.add(permission) permission = Permission.objects.get(codename='change_author', content_type=cls.author_ct) cls.user.user_permissions.add(permission) permission = Permission.objects.get(codename='add_holder2', content_type=cls.holder_ct) cls.user.user_permissions.add(permission) permission = Permission.objects.get(codename='change_holder2', content_type=cls.holder_ct) cls.user.user_permissions.add(permission) author = Author.objects.create(pk=1, name='The Author') cls.book = author.books.create(name='The inline Book') cls.author_change_url = reverse('admin:admin_inlines_author_change', args=(author.id,)) # Get the ID of the automatically created intermediate model for the Author-Book m2m author_book_auto_m2m_intermediate = Author.books.through.objects.get(author=author, book=cls.book) cls.author_book_auto_m2m_intermediate_id = author_book_auto_m2m_intermediate.pk cls.holder = Holder2.objects.create(dummy=13) cls.inner2 = Inner2.objects.create(dummy=42, holder=cls.holder) def setUp(self): self.holder_change_url = reverse('admin:admin_inlines_holder2_change', args=(self.holder.id,)) self.client.force_login(self.user) def test_inline_add_m2m_noperm(self): response = self.client.get(reverse('admin:admin_inlines_author_add')) # No change permission on books, so no inline self.assertNotContains(response, '<h2>Author-book relationships</h2>') self.assertNotContains(response, 'Add another Author-Book Relationship') self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_add_fk_noperm(self): response = self.client.get(reverse('admin:admin_inlines_holder2_add')) # No permissions on Inner2s, so no inline self.assertNotContains(response, '<h2>Inner2s</h2>') self.assertNotContains(response, 'Add another Inner2') self.assertNotContains(response, 'id="id_inner2_set-TOTAL_FORMS"') def test_inline_change_m2m_noperm(self): response = self.client.get(self.author_change_url) # No change permission on books, so no inline self.assertNotContains(response, '<h2>Author-book relationships</h2>') self.assertNotContains(response, 'Add another Author-Book Relationship') self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_change_fk_noperm(self): response = self.client.get(self.holder_change_url) # No permissions on Inner2s, so no inline self.assertNotContains(response, '<h2>Inner2s</h2>') self.assertNotContains(response, 'Add another Inner2') self.assertNotContains(response, 'id="id_inner2_set-TOTAL_FORMS"') def test_inline_add_m2m_view_only_perm(self): permission = Permission.objects.get(codename='view_book', content_type=self.book_ct) self.user.user_permissions.add(permission) response = self.client.get(reverse('admin:admin_inlines_author_add')) # View-only inlines. (It could be nicer to hide the empty, non-editable # inlines on the add page.) self.assertIs(response.context['inline_admin_formset'].has_view_permission, True) self.assertIs(response.context['inline_admin_formset'].has_add_permission, False) self.assertIs(response.context['inline_admin_formset'].has_change_permission, False) self.assertIs(response.context['inline_admin_formset'].has_delete_permission, False) self.assertContains(response, '<h2>Author-book relationships</h2>') self.assertContains( response, '<input type="hidden" name="Author_books-TOTAL_FORMS" value="0" ' 'id="id_Author_books-TOTAL_FORMS">', html=True, ) self.assertNotContains(response, 'Add another Author-Book Relationship') def test_inline_add_m2m_add_perm(self): permission = Permission.objects.get(codename='add_book', content_type=self.book_ct) self.user.user_permissions.add(permission) response = self.client.get(reverse('admin:admin_inlines_author_add')) # No change permission on Books, so no inline self.assertNotContains(response, '<h2>Author-book relationships</h2>') self.assertNotContains(response, 'Add another Author-Book Relationship') self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_add_fk_add_perm(self): permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct) self.user.user_permissions.add(permission) response = self.client.get(reverse('admin:admin_inlines_holder2_add')) # Add permission on inner2s, so we get the inline self.assertContains(response, '<h2>Inner2s</h2>') self.assertContains(response, 'Add another Inner2') self.assertContains(response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' 'value="3" name="inner2_set-TOTAL_FORMS">', html=True) def test_inline_change_m2m_add_perm(self): permission = Permission.objects.get(codename='add_book', content_type=self.book_ct) self.user.user_permissions.add(permission) response = self.client.get(self.author_change_url) # No change permission on books, so no inline self.assertNotContains(response, '<h2>Author-book relationships</h2>') self.assertNotContains(response, 'Add another Author-Book Relationship') self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') self.assertNotContains(response, 'id="id_Author_books-0-DELETE"') def test_inline_change_m2m_view_only_perm(self): permission = Permission.objects.get(codename='view_book', content_type=self.book_ct) self.user.user_permissions.add(permission) response = self.client.get(self.author_change_url) # View-only inlines. self.assertIs(response.context['inline_admin_formset'].has_view_permission, True) self.assertIs(response.context['inline_admin_formset'].has_add_permission, False) self.assertIs(response.context['inline_admin_formset'].has_change_permission, False) self.assertIs(response.context['inline_admin_formset'].has_delete_permission, False) self.assertContains(response, '<h2>Author-book relationships</h2>') self.assertContains( response, '<input type="hidden" name="Author_books-TOTAL_FORMS" value="1" ' 'id="id_Author_books-TOTAL_FORMS">', html=True, ) # The field in the inline is read-only. self.assertContains(response, '<p>%s</p>' % self.book) self.assertNotContains( response, '<input type="checkbox" name="Author_books-0-DELETE" id="id_Author_books-0-DELETE">', html=True, ) def test_inline_change_m2m_change_perm(self): permission = Permission.objects.get(codename='change_book', content_type=self.book_ct) self.user.user_permissions.add(permission) response = self.client.get(self.author_change_url) # We have change perm on books, so we can add/change/delete inlines self.assertIs(response.context['inline_admin_formset'].has_view_permission, True) self.assertIs(response.context['inline_admin_formset'].has_add_permission, True) self.assertIs(response.context['inline_admin_formset'].has_change_permission, True) self.assertIs(response.context['inline_admin_formset'].has_delete_permission, True) self.assertContains(response, '<h2>Author-book relationships</h2>') self.assertContains(response, 'Add another Author-book relationship') self.assertContains(response, '<input type="hidden" id="id_Author_books-TOTAL_FORMS" ' 'value="4" name="Author_books-TOTAL_FORMS">', html=True) self.assertContains( response, '<input type="hidden" id="id_Author_books-0-id" value="%i" ' 'name="Author_books-0-id">' % self.author_book_auto_m2m_intermediate_id, html=True ) self.assertContains(response, 'id="id_Author_books-0-DELETE"') def test_inline_change_fk_add_perm(self): permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Add permission on inner2s, so we can add but not modify existing self.assertContains(response, '<h2>Inner2s</h2>') self.assertContains(response, 'Add another Inner2') # 3 extra forms only, not the existing instance form self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="3" ' 'name="inner2_set-TOTAL_FORMS">', html=True ) self.assertNotContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">' % self.inner2.id, html=True ) def test_inline_change_fk_change_perm(self): permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Change permission on inner2s, so we can change existing but not add new self.assertContains(response, '<h2>Inner2s</h2>', count=2) # Just the one form for existing instances self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" name="inner2_set-TOTAL_FORMS">', html=True ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">' % self.inner2.id, html=True ) # max-num 0 means we can't add new ones self.assertContains( response, '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" value="0" name="inner2_set-MAX_NUM_FORMS">', html=True ) # TabularInline self.assertContains(response, '<th class="column-dummy required">Dummy</th>', html=True) self.assertContains( response, '<input type="number" name="inner2_set-2-0-dummy" value="%s" ' 'class="vIntegerField" id="id_inner2_set-2-0-dummy">' % self.inner2.dummy, html=True, ) def test_inline_change_fk_add_change_perm(self): permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct) self.user.user_permissions.add(permission) permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Add/change perm, so we can add new and change existing self.assertContains(response, '<h2>Inner2s</h2>') # One form for existing instance and three extra for new self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" name="inner2_set-TOTAL_FORMS">', html=True ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">' % self.inner2.id, html=True ) def test_inline_change_fk_change_del_perm(self): permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) self.user.user_permissions.add(permission) permission = Permission.objects.get(codename='delete_inner2', content_type=self.inner_ct) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Change/delete perm on inner2s, so we can change/delete existing self.assertContains(response, '<h2>Inner2s</h2>') # One form for existing instance only, no new self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" name="inner2_set-TOTAL_FORMS">', html=True ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">' % self.inner2.id, html=True ) self.assertContains(response, 'id="id_inner2_set-0-DELETE"') def test_inline_change_fk_all_perms(self): permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct) self.user.user_permissions.add(permission) permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) self.user.user_permissions.add(permission) permission = Permission.objects.get(codename='delete_inner2', content_type=self.inner_ct) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # All perms on inner2s, so we can add/change/delete self.assertContains(response, '<h2>Inner2s</h2>', count=2) # One form for existing instance only, three for new self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" name="inner2_set-TOTAL_FORMS">', html=True ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" name="inner2_set-0-id">' % self.inner2.id, html=True ) self.assertContains(response, 'id="id_inner2_set-0-DELETE"') # TabularInline self.assertContains(response, '<th class="column-dummy required">Dummy</th>', html=True) self.assertContains( response, '<input type="number" name="inner2_set-2-0-dummy" value="%s" ' 'class="vIntegerField" id="id_inner2_set-2-0-dummy">' % self.inner2.dummy, html=True, ) @override_settings(ROOT_URLCONF='admin_inlines.urls') class SeleniumTests(AdminSeleniumTestCase): available_apps = ['admin_inlines'] + AdminSeleniumTestCase.available_apps def setUp(self): User.objects.create_superuser(username='super', password='secret', email='[email protected]') def test_add_stackeds(self): """ The "Add another XXX" link correctly adds items to the stacked formset. """ self.admin_login(username='super', password='secret') self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_holder4_add')) inline_id = '#inner4stacked_set-group' def rows_length(): return len(self.selenium.find_elements_by_css_selector('%s .dynamic-inner4stacked_set' % inline_id)) self.assertEqual(rows_length(), 3) add_button = self.selenium.find_element_by_link_text( 'Add another Inner4 stacked') add_button.click() self.assertEqual(rows_length(), 4) def test_delete_stackeds(self): self.admin_login(username='super', password='secret') self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_holder4_add')) inline_id = '#inner4stacked_set-group' def rows_length(): return len(self.selenium.find_elements_by_css_selector('%s .dynamic-inner4stacked_set' % inline_id)) self.assertEqual(rows_length(), 3) add_button = self.selenium.find_element_by_link_text( 'Add another Inner4 stacked') add_button.click() add_button.click() self.assertEqual(rows_length(), 5, msg="sanity check") for delete_link in self.selenium.find_elements_by_css_selector('%s .inline-deletelink' % inline_id): delete_link.click() self.assertEqual(rows_length(), 3) def test_add_inlines(self): """ The "Add another XXX" link correctly adds items to the inline form. """ self.admin_login(username='super', password='secret') self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_profilecollection_add')) # There's only one inline to start with and it has the correct ID. self.assertEqual(len(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set')), 1) self.assertEqual(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set')[0].get_attribute('id'), 'profile_set-0') self.assertEqual(len(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set#profile_set-0 input[name=profile_set-0-first_name]')), 1) self.assertEqual(len(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set#profile_set-0 input[name=profile_set-0-last_name]')), 1) # Add an inline self.selenium.find_element_by_link_text('Add another Profile').click() # The inline has been added, it has the right id, and it contains the # correct fields. self.assertEqual(len(self.selenium.find_elements_by_css_selector('.dynamic-profile_set')), 2) self.assertEqual(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set')[1].get_attribute('id'), 'profile_set-1') self.assertEqual(len(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set#profile_set-1 input[name=profile_set-1-first_name]')), 1) self.assertEqual(len(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set#profile_set-1 input[name=profile_set-1-last_name]')), 1) # Let's add another one to be sure self.selenium.find_element_by_link_text('Add another Profile').click() self.assertEqual(len(self.selenium.find_elements_by_css_selector('.dynamic-profile_set')), 3) self.assertEqual(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set')[2].get_attribute('id'), 'profile_set-2') self.assertEqual(len(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set#profile_set-2 input[name=profile_set-2-first_name]')), 1) self.assertEqual(len(self.selenium.find_elements_by_css_selector( '.dynamic-profile_set#profile_set-2 input[name=profile_set-2-last_name]')), 1) # Enter some data and click 'Save' self.selenium.find_element_by_name('profile_set-0-first_name').send_keys('0 first name 1') self.selenium.find_element_by_name('profile_set-0-last_name').send_keys('0 last name 2') self.selenium.find_element_by_name('profile_set-1-first_name').send_keys('1 first name 1') self.selenium.find_element_by_name('profile_set-1-last_name').send_keys('1 last name 2') self.selenium.find_element_by_name('profile_set-2-first_name').send_keys('2 first name 1') self.selenium.find_element_by_name('profile_set-2-last_name').send_keys('2 last name 2') self.selenium.find_element_by_xpath('//input[@value="Save"]').click() self.wait_page_loaded() # The objects have been created in the database self.assertEqual(ProfileCollection.objects.all().count(), 1) self.assertEqual(Profile.objects.all().count(), 3) def test_delete_inlines(self): self.admin_login(username='super', password='secret') self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_profilecollection_add')) # Add a few inlines self.selenium.find_element_by_link_text('Add another Profile').click() self.selenium.find_element_by_link_text('Add another Profile').click() self.selenium.find_element_by_link_text('Add another Profile').click() self.selenium.find_element_by_link_text('Add another Profile').click() self.assertEqual(len(self.selenium.find_elements_by_css_selector( '#profile_set-group table tr.dynamic-profile_set')), 5) self.assertEqual(len(self.selenium.find_elements_by_css_selector( 'form#profilecollection_form tr.dynamic-profile_set#profile_set-0')), 1) self.assertEqual(len(self.selenium.find_elements_by_css_selector( 'form#profilecollection_form tr.dynamic-profile_set#profile_set-1')), 1) self.assertEqual(len(self.selenium.find_elements_by_css_selector( 'form#profilecollection_form tr.dynamic-profile_set#profile_set-2')), 1) self.assertEqual(len(self.selenium.find_elements_by_css_selector( 'form#profilecollection_form tr.dynamic-profile_set#profile_set-3')), 1) self.assertEqual(len(self.selenium.find_elements_by_css_selector( 'form#profilecollection_form tr.dynamic-profile_set#profile_set-4')), 1) # Click on a few delete buttons self.selenium.find_element_by_css_selector( 'form#profilecollection_form tr.dynamic-profile_set#profile_set-1 td.delete a').click() self.selenium.find_element_by_css_selector( 'form#profilecollection_form tr.dynamic-profile_set#profile_set-2 td.delete a').click() # The rows are gone and the IDs have been re-sequenced self.assertEqual(len(self.selenium.find_elements_by_css_selector( '#profile_set-group table tr.dynamic-profile_set')), 3) self.assertEqual(len(self.selenium.find_elements_by_css_selector( 'form#profilecollection_form tr.dynamic-profile_set#profile_set-0')), 1) self.assertEqual(len(self.selenium.find_elements_by_css_selector( 'form#profilecollection_form tr.dynamic-profile_set#profile_set-1')), 1) self.assertEqual(len(self.selenium.find_elements_by_css_selector( 'form#profilecollection_form tr.dynamic-profile_set#profile_set-2')), 1) def test_alternating_rows(self): self.admin_login(username='super', password='secret') self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_profilecollection_add')) # Add a few inlines self.selenium.find_element_by_link_text('Add another Profile').click() self.selenium.find_element_by_link_text('Add another Profile').click() row_selector = 'form#profilecollection_form tr.dynamic-profile_set' self.assertEqual(len(self.selenium.find_elements_by_css_selector( "%s.row1" % row_selector)), 2, msg="Expect two row1 styled rows") self.assertEqual(len(self.selenium.find_elements_by_css_selector( "%s.row2" % row_selector)), 1, msg="Expect one row2 styled row") def test_collapsed_inlines(self): # Collapsed inlines have SHOW/HIDE links. self.admin_login(username='super', password='secret') self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_author_add')) # One field is in a stacked inline, other in a tabular one. test_fields = ['#id_nonautopkbook_set-0-title', '#id_nonautopkbook_set-2-0-title'] show_links = self.selenium.find_elements_by_link_text('SHOW') self.assertEqual(len(show_links), 3) for show_index, field_name in enumerate(test_fields, 0): self.wait_until_invisible(field_name) show_links[show_index].click() self.wait_until_visible(field_name) hide_links = self.selenium.find_elements_by_link_text('HIDE') self.assertEqual(len(hide_links), 2) for hide_index, field_name in enumerate(test_fields, 0): self.wait_until_visible(field_name) hide_links[hide_index].click() self.wait_until_invisible(field_name) def test_added_stacked_inline_with_collapsed_fields(self): self.admin_login(username='super', password='secret') self.selenium.get(self.live_server_url + reverse('admin:admin_inlines_teacher_add')) self.selenium.find_element_by_link_text('Add another Child').click() test_fields = ['#id_child_set-0-name', '#id_child_set-1-name'] show_links = self.selenium.find_elements_by_link_text('SHOW') self.assertEqual(len(show_links), 2) for show_index, field_name in enumerate(test_fields, 0): self.wait_until_invisible(field_name) show_links[show_index].click() self.wait_until_visible(field_name) hide_links = self.selenium.find_elements_by_link_text('HIDE') self.assertEqual(len(hide_links), 2) for hide_index, field_name in enumerate(test_fields, 0): self.wait_until_visible(field_name) hide_links[hide_index].click() self.wait_until_invisible(field_name)
03a804b340a8c37ce056b018faad8825bea51b16312a8e3b12f2d4267677097c
""" Testing of admin inline formsets. """ import random from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Parent(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Child(models.Model): name = models.CharField(max_length=50) teacher = models.ForeignKey(Teacher, models.CASCADE) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() parent = GenericForeignKey() def __str__(self): return 'I am %s, a child of %s' % (self.name, self.parent) class Book(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=50) books = models.ManyToManyField(Book) class NonAutoPKBook(models.Model): rand_pk = models.IntegerField(primary_key=True, editable=False) author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=50) def save(self, *args, **kwargs): while not self.rand_pk: test_pk = random.randint(1, 99999) if not NonAutoPKBook.objects.filter(rand_pk=test_pk).exists(): self.rand_pk = test_pk super().save(*args, **kwargs) class NonAutoPKBookChild(NonAutoPKBook): pass class EditablePKBook(models.Model): manual_pk = models.IntegerField(primary_key=True) author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=50) class Holder(models.Model): dummy = models.IntegerField() class Inner(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder, models.CASCADE) readonly = models.CharField("Inner readonly label", max_length=1) def get_absolute_url(self): return '/inner/' class Holder2(models.Model): dummy = models.IntegerField() class Inner2(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder2, models.CASCADE) class Holder3(models.Model): dummy = models.IntegerField() class Inner3(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder3, models.CASCADE) # Models for ticket #8190 class Holder4(models.Model): dummy = models.IntegerField() class Inner4Stacked(models.Model): dummy = models.IntegerField(help_text="Awesome stacked help text is awesome.") holder = models.ForeignKey(Holder4, models.CASCADE) class Inner4Tabular(models.Model): dummy = models.IntegerField(help_text="Awesome tabular help text is awesome.") holder = models.ForeignKey(Holder4, models.CASCADE) # Models for #12749 class Person(models.Model): firstname = models.CharField(max_length=15) class OutfitItem(models.Model): name = models.CharField(max_length=15) class Fashionista(models.Model): person = models.OneToOneField(Person, models.CASCADE, primary_key=True) weaknesses = models.ManyToManyField(OutfitItem, through='ShoppingWeakness', blank=True) class ShoppingWeakness(models.Model): fashionista = models.ForeignKey(Fashionista, models.CASCADE) item = models.ForeignKey(OutfitItem, models.CASCADE) # Models for #13510 class TitleCollection(models.Model): pass class Title(models.Model): collection = models.ForeignKey(TitleCollection, models.SET_NULL, blank=True, null=True) title1 = models.CharField(max_length=100) title2 = models.CharField(max_length=100) # Models for #15424 class Poll(models.Model): name = models.CharField(max_length=40) class Question(models.Model): text = models.CharField(max_length=40) poll = models.ForeignKey(Poll, models.CASCADE) class Novel(models.Model): name = models.CharField(max_length=40) class NovelReadonlyChapter(Novel): class Meta: proxy = True class Chapter(models.Model): name = models.CharField(max_length=40) novel = models.ForeignKey(Novel, models.CASCADE) class FootNote(models.Model): """ Model added for ticket 19838 """ chapter = models.ForeignKey(Chapter, models.PROTECT) note = models.CharField(max_length=40) # Models for #16838 class CapoFamiglia(models.Model): name = models.CharField(max_length=100) class Consigliere(models.Model): name = models.CharField(max_length=100, help_text='Help text for Consigliere') capo_famiglia = models.ForeignKey(CapoFamiglia, models.CASCADE, related_name='+') class SottoCapo(models.Model): name = models.CharField(max_length=100) capo_famiglia = models.ForeignKey(CapoFamiglia, models.CASCADE, related_name='+') class ReadOnlyInline(models.Model): name = models.CharField(max_length=100, help_text='Help text for ReadOnlyInline') capo_famiglia = models.ForeignKey(CapoFamiglia, models.CASCADE) # Models for #18433 class ParentModelWithCustomPk(models.Model): my_own_pk = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=100) class ChildModel1(models.Model): my_own_pk = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=100) parent = models.ForeignKey(ParentModelWithCustomPk, models.CASCADE) def get_absolute_url(self): return '/child_model1/' class ChildModel2(models.Model): my_own_pk = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=100) parent = models.ForeignKey(ParentModelWithCustomPk, models.CASCADE) def get_absolute_url(self): return '/child_model2/' # Models for #19425 class BinaryTree(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey('self', models.SET_NULL, null=True, blank=True) # Models for #19524 class LifeForm(models.Model): pass class ExtraTerrestrial(LifeForm): name = models.CharField(max_length=100) class Sighting(models.Model): et = models.ForeignKey(ExtraTerrestrial, models.CASCADE) place = models.CharField(max_length=100) # Models for #18263 class SomeParentModel(models.Model): name = models.CharField(max_length=1) class SomeChildModel(models.Model): name = models.CharField(max_length=1) position = models.PositiveIntegerField() parent = models.ForeignKey(SomeParentModel, models.CASCADE) readonly_field = models.CharField(max_length=1) # Other models class ProfileCollection(models.Model): pass class Profile(models.Model): collection = models.ForeignKey(ProfileCollection, models.SET_NULL, blank=True, null=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100)
11702e38be38b9ebbbbe80e819484234d2e6e2cec1d6633ab04d3b639bdad041
from django import forms from django.contrib import admin from django.db import models from .models import ( Author, BinaryTree, CapoFamiglia, Chapter, Child, ChildModel1, ChildModel2, Consigliere, EditablePKBook, ExtraTerrestrial, Fashionista, FootNote, Holder, Holder2, Holder3, Holder4, Inner, Inner2, Inner3, Inner4Stacked, Inner4Tabular, NonAutoPKBook, NonAutoPKBookChild, Novel, NovelReadonlyChapter, OutfitItem, ParentModelWithCustomPk, Poll, Profile, ProfileCollection, Question, ReadOnlyInline, ShoppingWeakness, Sighting, SomeChildModel, SomeParentModel, SottoCapo, Teacher, Title, TitleCollection, ) site = admin.AdminSite(name="admin") class BookInline(admin.TabularInline): model = Author.books.through class NonAutoPKBookTabularInline(admin.TabularInline): model = NonAutoPKBook classes = ('collapse',) class NonAutoPKBookChildTabularInline(admin.TabularInline): model = NonAutoPKBookChild classes = ('collapse',) class NonAutoPKBookStackedInline(admin.StackedInline): model = NonAutoPKBook classes = ('collapse',) class EditablePKBookTabularInline(admin.TabularInline): model = EditablePKBook class EditablePKBookStackedInline(admin.StackedInline): model = EditablePKBook class AuthorAdmin(admin.ModelAdmin): inlines = [ BookInline, NonAutoPKBookTabularInline, NonAutoPKBookStackedInline, EditablePKBookTabularInline, EditablePKBookStackedInline, NonAutoPKBookChildTabularInline, ] class InnerInline(admin.StackedInline): model = Inner can_delete = False readonly_fields = ('readonly',) # For bug #13174 tests. class HolderAdmin(admin.ModelAdmin): class Media: js = ('my_awesome_admin_scripts.js',) class ReadOnlyInlineInline(admin.TabularInline): model = ReadOnlyInline readonly_fields = ['name'] class InnerInline2(admin.StackedInline): model = Inner2 class Media: js = ('my_awesome_inline_scripts.js',) class InnerInline2Tabular(admin.TabularInline): model = Inner2 class CustomNumberWidget(forms.NumberInput): class Media: js = ('custom_number.js',) class InnerInline3(admin.StackedInline): model = Inner3 formfield_overrides = { models.IntegerField: {'widget': CustomNumberWidget}, } class Media: js = ('my_awesome_inline_scripts.js',) class TitleForm(forms.ModelForm): title1 = forms.CharField(max_length=100) def clean(self): cleaned_data = self.cleaned_data title1 = cleaned_data.get("title1") title2 = cleaned_data.get("title2") if title1 != title2: raise forms.ValidationError("The two titles must be the same") return cleaned_data class TitleInline(admin.TabularInline): model = Title form = TitleForm extra = 1 class Inner4StackedInline(admin.StackedInline): model = Inner4Stacked show_change_link = True class Inner4TabularInline(admin.TabularInline): model = Inner4Tabular show_change_link = True class Holder4Admin(admin.ModelAdmin): inlines = [Inner4StackedInline, Inner4TabularInline] class InlineWeakness(admin.TabularInline): model = ShoppingWeakness extra = 1 class WeaknessForm(forms.ModelForm): extra_field = forms.CharField() class Meta: model = ShoppingWeakness fields = '__all__' class WeaknessInlineCustomForm(admin.TabularInline): model = ShoppingWeakness form = WeaknessForm class FootNoteForm(forms.ModelForm): extra_field = forms.CharField() class Meta: model = FootNote fields = '__all__' class FootNoteNonEditableInlineCustomForm(admin.TabularInline): model = FootNote form = FootNoteForm def has_change_permission(self, request, obj=None): return False class QuestionInline(admin.TabularInline): model = Question readonly_fields = ['call_me'] def call_me(self, obj): return 'Callable in QuestionInline' class PollAdmin(admin.ModelAdmin): inlines = [QuestionInline] def call_me(self, obj): return 'Callable in PollAdmin' class ChapterInline(admin.TabularInline): model = Chapter readonly_fields = ['call_me'] def call_me(self, obj): return 'Callable in ChapterInline' class NovelAdmin(admin.ModelAdmin): inlines = [ChapterInline] class ReadOnlyChapterInline(admin.TabularInline): model = Chapter def has_change_permission(self, request, obj=None): return False class NovelReadonlyChapterAdmin(admin.ModelAdmin): inlines = [ReadOnlyChapterInline] class ConsigliereInline(admin.TabularInline): model = Consigliere class SottoCapoInline(admin.TabularInline): model = SottoCapo class ProfileInline(admin.TabularInline): model = Profile extra = 1 # admin for #18433 class ChildModel1Inline(admin.TabularInline): model = ChildModel1 class ChildModel2Inline(admin.StackedInline): model = ChildModel2 # admin for #19425 and #18388 class BinaryTreeAdmin(admin.TabularInline): model = BinaryTree def get_extra(self, request, obj=None, **kwargs): extra = 2 if obj: return extra - obj.binarytree_set.count() return extra def get_max_num(self, request, obj=None, **kwargs): max_num = 3 if obj: return max_num - obj.binarytree_set.count() return max_num # admin for #19524 class SightingInline(admin.TabularInline): model = Sighting # admin and form for #18263 class SomeChildModelForm(forms.ModelForm): class Meta: fields = '__all__' model = SomeChildModel widgets = { 'position': forms.HiddenInput, } labels = {'readonly_field': 'Label from ModelForm.Meta'} help_texts = {'readonly_field': 'Help text from ModelForm.Meta'} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name'].label = 'new label' class SomeChildModelInline(admin.TabularInline): model = SomeChildModel form = SomeChildModelForm readonly_fields = ('readonly_field',) class StudentInline(admin.StackedInline): model = Child extra = 1 fieldsets = [ ('Name', {'fields': ('name',), 'classes': ('collapse',)}), ] class TeacherAdmin(admin.ModelAdmin): inlines = [StudentInline] site.register(TitleCollection, inlines=[TitleInline]) # Test bug #12561 and #12778 # only ModelAdmin media site.register(Holder, HolderAdmin, inlines=[InnerInline]) # ModelAdmin and Inline media site.register(Holder2, HolderAdmin, inlines=[InnerInline2, InnerInline2Tabular]) # only Inline media site.register(Holder3, inlines=[InnerInline3]) site.register(Poll, PollAdmin) site.register(Novel, NovelAdmin) site.register(NovelReadonlyChapter, NovelReadonlyChapterAdmin) site.register(Fashionista, inlines=[InlineWeakness]) site.register(Holder4, Holder4Admin) site.register(Author, AuthorAdmin) site.register(CapoFamiglia, inlines=[ConsigliereInline, SottoCapoInline, ReadOnlyInlineInline]) site.register(ProfileCollection, inlines=[ProfileInline]) site.register(ParentModelWithCustomPk, inlines=[ChildModel1Inline, ChildModel2Inline]) site.register(BinaryTree, inlines=[BinaryTreeAdmin]) site.register(ExtraTerrestrial, inlines=[SightingInline]) site.register(SomeParentModel, inlines=[SomeChildModelInline]) site.register([Question, Inner4Stacked, Inner4Tabular]) site.register(Teacher, TeacherAdmin) site.register(Chapter, inlines=[FootNoteNonEditableInlineCustomForm]) site.register(OutfitItem, inlines=[WeaknessInlineCustomForm])
5a3f53bebbf2ccf0813ea214d1a0e06871b7313abfb33ffd03db92013432642d
from django.urls import path from . import admin urlpatterns = [ path('admin/', admin.site.urls), ]
ca98df78a1cdf473b39195f030711009901326b98a26197e16759968141828e5
from django.db import connection from django.db.models import Max from django.test import TestCase from .models import Cash, CashModel class FromDBValueTest(TestCase): @classmethod def setUpTestData(cls): CashModel.objects.create(cash='12.50') def test_simple_load(self): instance = CashModel.objects.get() self.assertIsInstance(instance.cash, Cash) def test_values_list(self): values_list = CashModel.objects.values_list('cash', flat=True) self.assertIsInstance(values_list[0], Cash) def test_values(self): values = CashModel.objects.values('cash') self.assertIsInstance(values[0]['cash'], Cash) def test_aggregation(self): maximum = CashModel.objects.aggregate(m=Max('cash'))['m'] self.assertIsInstance(maximum, Cash) def test_defer(self): instance = CashModel.objects.defer('cash').get() self.assertIsInstance(instance.cash, Cash) def test_connection(self): instance = CashModel.objects.get() self.assertEqual(instance.cash.vendor, connection.vendor)
29ed9c398331612b83692211d421c0df3412d17281b171e2f5018b6f7fa0e022
import decimal from django.db import models class Cash(decimal.Decimal): currency = 'USD' def __str__(self): s = super().__str__(self) return '%s %s' % (s, self.currency) class CashField(models.DecimalField): def __init__(self, **kwargs): kwargs['max_digits'] = 20 kwargs['decimal_places'] = 2 super().__init__(**kwargs) def from_db_value(self, value, expression, connection): cash = Cash(value) cash.vendor = connection.vendor return cash class CashModel(models.Model): cash = CashField() def __str__(self): return str(self.cash)
63708f94dd0ba1463f320a388606b43aabb6dd7060a796bd48a0f092591866c2
from django.core import checks from django.core.checks import Error from django.db import models from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import ( isolate_apps, modify_settings, override_system_checks, ) @isolate_apps('check_framework', attr_name='apps') @override_system_checks([checks.model_checks.check_all_models]) class DuplicateDBTableTests(SimpleTestCase): def test_collision_in_same_app(self): class Model1(models.Model): class Meta: db_table = 'test_table' class Model2(models.Model): class Meta: db_table = 'test_table' self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "db_table 'test_table' is used by multiple models: " "check_framework.Model1, check_framework.Model2.", obj='test_table', id='models.E028', ) ]) @modify_settings(INSTALLED_APPS={'append': 'basic'}) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_collision_across_apps(self, apps): class Model1(models.Model): class Meta: app_label = 'basic' db_table = 'test_table' class Model2(models.Model): class Meta: app_label = 'check_framework' db_table = 'test_table' self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "db_table 'test_table' is used by multiple models: " "basic.Model1, check_framework.Model2.", obj='test_table', id='models.E028', ) ]) def test_no_collision_for_unmanaged_models(self): class Unmanaged(models.Model): class Meta: db_table = 'test_table' managed = False class Managed(models.Model): class Meta: db_table = 'test_table' self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) def test_no_collision_for_proxy_models(self): class Model(models.Model): class Meta: db_table = 'test_table' class ProxyModel(Model): class Meta: proxy = True self.assertEqual(Model._meta.db_table, ProxyModel._meta.db_table) self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) @isolate_apps('check_framework', attr_name='apps') @override_system_checks([checks.model_checks.check_all_models]) class IndexNameTests(SimpleTestCase): def test_collision_in_same_model(self): index = models.Index(fields=['id'], name='foo') class Model(models.Model): class Meta: indexes = [index, index] self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique for model check_framework.Model.", id='models.E029', ), ]) def test_collision_in_different_models(self): index = models.Index(fields=['id'], name='foo') class Model1(models.Model): class Meta: indexes = [index] class Model2(models.Model): class Meta: indexes = [index] self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique amongst models: " "check_framework.Model1, check_framework.Model2.", id='models.E030', ), ]) def test_collision_abstract_model(self): class AbstractModel(models.Model): class Meta: indexes = [models.Index(fields=['id'], name='foo')] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique amongst models: " "check_framework.Model1, check_framework.Model2.", id='models.E030', ), ]) @modify_settings(INSTALLED_APPS={'append': 'basic'}) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_collision_across_apps(self, apps): index = models.Index(fields=['id'], name='foo') class Model1(models.Model): class Meta: app_label = 'basic' indexes = [index] class Model2(models.Model): class Meta: app_label = 'check_framework' indexes = [index] self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "index name 'foo' is not unique amongst models: basic.Model1, " "check_framework.Model2.", id='models.E030', ), ]) @isolate_apps('check_framework', attr_name='apps') @override_system_checks([checks.model_checks.check_all_models]) @skipUnlessDBFeature('supports_table_check_constraints') class ConstraintNameTests(TestCase): def test_collision_in_same_model(self): class Model(models.Model): class Meta: constraints = [ models.CheckConstraint(check=models.Q(id__gt=0), name='foo'), models.CheckConstraint(check=models.Q(id__lt=100), name='foo'), ] self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique for model " "check_framework.Model.", id='models.E031', ), ]) def test_collision_in_different_models(self): constraint = models.CheckConstraint(check=models.Q(id__gt=0), name='foo') class Model1(models.Model): class Meta: constraints = [constraint] class Model2(models.Model): class Meta: constraints = [constraint] self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique amongst models: " "check_framework.Model1, check_framework.Model2.", id='models.E032', ), ]) def test_collision_abstract_model(self): class AbstractModel(models.Model): class Meta: constraints = [models.CheckConstraint(check=models.Q(id__gt=0), name='foo')] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique amongst models: " "check_framework.Model1, check_framework.Model2.", id='models.E032', ), ]) @modify_settings(INSTALLED_APPS={'append': 'basic'}) @isolate_apps('basic', 'check_framework', kwarg_name='apps') def test_collision_across_apps(self, apps): constraint = models.CheckConstraint(check=models.Q(id__gt=0), name='foo') class Model1(models.Model): class Meta: app_label = 'basic' constraints = [constraint] class Model2(models.Model): class Meta: app_label = 'check_framework' constraints = [constraint] self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique amongst models: " "basic.Model1, check_framework.Model2.", id='models.E032', ), ])
9458c9a67a055589d2fbf7f3fc738f9dd68834d0354dca72100c20122e4eff18
from unittest import mock from django.db import connections, models from django.test import SimpleTestCase from django.test.utils import isolate_apps, override_settings class TestRouter: """ Routes to the 'other' database if the model name starts with 'Other'. """ def allow_migrate(self, db, app_label, model_name=None, **hints): return db == ('other' if model_name.startswith('other') else 'default') @override_settings(DATABASE_ROUTERS=[TestRouter()]) @isolate_apps('check_framework') class TestMultiDBChecks(SimpleTestCase): def _patch_check_field_on(self, db): return mock.patch.object(connections[db].validation, 'check_field') def test_checks_called_on_the_default_database(self): class Model(models.Model): field = models.CharField(max_length=100) model = Model() with self._patch_check_field_on('default') as mock_check_field_default: with self._patch_check_field_on('other') as mock_check_field_other: model.check() self.assertTrue(mock_check_field_default.called) self.assertFalse(mock_check_field_other.called) def test_checks_called_on_the_other_database(self): class OtherModel(models.Model): field = models.CharField(max_length=100) model = OtherModel() with self._patch_check_field_on('other') as mock_check_field_other: with self._patch_check_field_on('default') as mock_check_field_default: model.check() self.assertTrue(mock_check_field_other.called) self.assertFalse(mock_check_field_default.called)
372bf8c47e7e74ca69a8a9340abbb17c5c20d18347b4aac7b8f717aafd190bb6
from django.core.checks import Error from django.core.checks.translation import ( check_language_settings_consistent, check_setting_language_code, check_setting_languages, check_setting_languages_bidi, ) from django.test import SimpleTestCase class TranslationCheckTests(SimpleTestCase): def setUp(self): self.valid_tags = ( 'en', # language 'mas', # language 'sgn-ase', # language+extlang 'fr-CA', # language+region 'es-419', # language+region 'zh-Hans', # language+script 'ca-ES-valencia', # language+region+variant # FIXME: The following should be invalid: 'sr@latin', # language+script ) self.invalid_tags = ( None, # invalid type: None. 123, # invalid type: int. b'en', # invalid type: bytes. 'eü', # non-latin characters. 'en_US', # locale format. 'en--us', # empty subtag. '-en', # leading separator. 'en-', # trailing separator. 'en-US.UTF-8', # language tag w/ locale encoding. 'en_US.UTF-8', # locale format - language w/ region and encoding. 'ca_ES@valencia', # locale format - language w/ region and variant. # FIXME: The following should be invalid: # 'sr@latin', # locale instead of language tag. ) def test_valid_language_code(self): for tag in self.valid_tags: with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): self.assertEqual(check_setting_language_code(None), []) def test_invalid_language_code(self): msg = 'You have provided an invalid value for the LANGUAGE_CODE setting: %r.' for tag in self.invalid_tags: with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): self.assertEqual(check_setting_language_code(None), [ Error(msg % tag, id='translation.E001'), ]) def test_valid_languages(self): for tag in self.valid_tags: with self.subTest(tag), self.settings(LANGUAGES=[(tag, tag)]): self.assertEqual(check_setting_languages(None), []) def test_invalid_languages(self): msg = 'You have provided an invalid language code in the LANGUAGES setting: %r.' for tag in self.invalid_tags: with self.subTest(tag), self.settings(LANGUAGES=[(tag, tag)]): self.assertEqual(check_setting_languages(None), [ Error(msg % tag, id='translation.E002'), ]) def test_valid_languages_bidi(self): for tag in self.valid_tags: with self.subTest(tag), self.settings(LANGUAGES_BIDI=[tag]): self.assertEqual(check_setting_languages_bidi(None), []) def test_invalid_languages_bidi(self): msg = 'You have provided an invalid language code in the LANGUAGES_BIDI setting: %r.' for tag in self.invalid_tags: with self.subTest(tag), self.settings(LANGUAGES_BIDI=[tag]): self.assertEqual(check_setting_languages_bidi(None), [ Error(msg % tag, id='translation.E003'), ]) def test_inconsistent_language_settings(self): msg = ( 'You have provided a value for the LANGUAGE_CODE setting that is ' 'not in the LANGUAGES setting.' ) with self.settings(LANGUAGE_CODE='fr', LANGUAGES=[('en', 'English')]): self.assertEqual(check_language_settings_consistent(None), [ Error(msg, id='translation.E004'), ])
f02ac64d927cbcbe8f8cec40e1c109d9f72ab90c5e93218ec016ae927915d113
from django.conf import settings from django.core.checks.messages import Error, Warning from django.core.checks.urls import ( E006, check_url_config, check_url_namespaces_unique, check_url_settings, get_warning_for_invalid_pattern, ) from django.test import SimpleTestCase from django.test.utils import override_settings class CheckUrlConfigTests(SimpleTestCase): @override_settings(ROOT_URLCONF='check_framework.urls.no_warnings') def test_no_warnings(self): result = check_url_config(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF='check_framework.urls.no_warnings_i18n') def test_no_warnings_i18n(self): self.assertEqual(check_url_config(None), []) @override_settings(ROOT_URLCONF='check_framework.urls.warning_in_include') def test_check_resolver_recursive(self): # The resolver is checked recursively (examining URL patterns in include()). result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, 'urls.W001') @override_settings(ROOT_URLCONF='check_framework.urls.include_with_dollar') def test_include_with_dollar(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, 'urls.W001') self.assertEqual(warning.msg, ( "Your URL pattern '^include-with-dollar$' uses include with a " "route ending with a '$'. Remove the dollar from the route to " "avoid problems including URLs." )) @override_settings(ROOT_URLCONF='check_framework.urls.contains_tuple') def test_contains_tuple_not_url_instance(self): result = check_url_config(None) warning = result[0] self.assertEqual(warning.id, 'urls.E004') self.assertRegex(warning.msg, ( r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) is " r"invalid. Ensure that urlpatterns is a list of path\(\) and/or re_path\(\) " r"instances\.$" )) @override_settings(ROOT_URLCONF='check_framework.urls.include_contains_tuple') def test_contains_included_tuple(self): result = check_url_config(None) warning = result[0] self.assertEqual(warning.id, 'urls.E004') self.assertRegex(warning.msg, ( r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) is " r"invalid. Ensure that urlpatterns is a list of path\(\) and/or re_path\(\) " r"instances\.$" )) @override_settings(ROOT_URLCONF='check_framework.urls.beginning_with_slash') def test_beginning_with_slash(self): msg = ( "Your URL pattern '%s' has a route beginning with a '/'. Remove " "this slash as it is unnecessary. If this pattern is targeted in " "an include(), ensure the include() pattern has a trailing '/'." ) warning1, warning2 = check_url_config(None) self.assertEqual(warning1.id, 'urls.W002') self.assertEqual(warning1.msg, msg % '/path-starting-with-slash/') self.assertEqual(warning2.id, 'urls.W002') self.assertEqual(warning2.msg, msg % '/url-starting-with-slash/$') @override_settings( ROOT_URLCONF='check_framework.urls.beginning_with_slash', APPEND_SLASH=False, ) def test_beginning_with_slash_append_slash(self): # It can be useful to start a URL pattern with a slash when # APPEND_SLASH=False (#27238). result = check_url_config(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF='check_framework.urls.name_with_colon') def test_name_with_colon(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, 'urls.W003') expected_msg = "Your URL pattern '^$' [name='name_with:colon'] has a name including a ':'." self.assertIn(expected_msg, warning.msg) @override_settings(ROOT_URLCONF=None) def test_no_root_urlconf_in_settings(self): delattr(settings, 'ROOT_URLCONF') result = check_url_config(None) self.assertEqual(result, []) def test_get_warning_for_invalid_pattern_string(self): warning = get_warning_for_invalid_pattern('')[0] self.assertEqual( warning.hint, "Try removing the string ''. The list of urlpatterns should " "not have a prefix string as the first element.", ) def test_get_warning_for_invalid_pattern_tuple(self): warning = get_warning_for_invalid_pattern((r'^$', lambda x: x))[0] self.assertEqual(warning.hint, "Try using path() instead of a tuple.") def test_get_warning_for_invalid_pattern_other(self): warning = get_warning_for_invalid_pattern(object())[0] self.assertIsNone(warning.hint) @override_settings(ROOT_URLCONF='check_framework.urls.non_unique_namespaces') def test_check_non_unique_namespaces(self): result = check_url_namespaces_unique(None) self.assertEqual(len(result), 2) non_unique_namespaces = ['app-ns1', 'app-1'] warning_messages = [ "URL namespace '{}' isn't unique. You may not be able to reverse " "all URLs in this namespace".format(namespace) for namespace in non_unique_namespaces ] for warning in result: self.assertIsInstance(warning, Warning) self.assertEqual('urls.W005', warning.id) self.assertIn(warning.msg, warning_messages) @override_settings(ROOT_URLCONF='check_framework.urls.unique_namespaces') def test_check_unique_namespaces(self): result = check_url_namespaces_unique(None) self.assertEqual(result, []) class UpdatedToPathTests(SimpleTestCase): @override_settings(ROOT_URLCONF='check_framework.urls.path_compatibility.contains_re_named_group') def test_contains_re_named_group(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, '2_0.W001') expected_msg = "Your URL pattern '(?P<named-group>\\d+)' has a route" self.assertIn(expected_msg, warning.msg) @override_settings(ROOT_URLCONF='check_framework.urls.path_compatibility.beginning_with_caret') def test_beginning_with_caret(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, '2_0.W001') expected_msg = "Your URL pattern '^beginning-with-caret' has a route" self.assertIn(expected_msg, warning.msg) @override_settings(ROOT_URLCONF='check_framework.urls.path_compatibility.ending_with_dollar') def test_ending_with_dollar(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, '2_0.W001') expected_msg = "Your URL pattern 'ending-with-dollar$' has a route" self.assertIn(expected_msg, warning.msg) class CheckCustomErrorHandlersTests(SimpleTestCase): @override_settings(ROOT_URLCONF='check_framework.urls.bad_error_handlers') def test_bad_handlers(self): result = check_url_config(None) self.assertEqual(len(result), 4) for code, num_params, error in zip([400, 403, 404, 500], [2, 2, 2, 1], result): with self.subTest('handler{}'.format(code)): self.assertEqual(error, Error( "The custom handler{} view " "'check_framework.urls.bad_error_handlers.bad_handler' " "does not take the correct number of arguments (request{})." .format(code, ', exception' if num_params == 2 else ''), id='urls.E007', )) @override_settings(ROOT_URLCONF='check_framework.urls.bad_error_handlers_invalid_path') def test_bad_handlers_invalid_path(self): result = check_url_config(None) paths = [ 'django.views.bad_handler', 'django.invalid_module.bad_handler', 'invalid_module.bad_handler', 'django', ] hints = [ "Could not import '{}'. View does not exist in module django.views.", "Could not import '{}'. Parent module django.invalid_module does not exist.", "No module named 'invalid_module'", "Could not import '{}'. The path must be fully qualified.", ] for code, path, hint, error in zip([400, 403, 404, 500], paths, hints, result): with self.subTest('handler{}'.format(code)): self.assertEqual(error, Error( "The custom handler{} view '{}' could not be imported.".format(code, path), hint=hint.format(path), id='urls.E008', )) @override_settings(ROOT_URLCONF='check_framework.urls.good_error_handlers') def test_good_handlers(self): result = check_url_config(None) self.assertEqual(result, []) class CheckURLSettingsTests(SimpleTestCase): @override_settings(STATIC_URL='a/', MEDIA_URL='b/') def test_slash_no_errors(self): self.assertEqual(check_url_settings(None), []) @override_settings(STATIC_URL='', MEDIA_URL='') def test_empty_string_no_errors(self): self.assertEqual(check_url_settings(None), []) @override_settings(STATIC_URL='noslash') def test_static_url_no_slash(self): self.assertEqual(check_url_settings(None), [E006('STATIC_URL')]) @override_settings(STATIC_URL='slashes//') def test_static_url_double_slash_allowed(self): # The check allows for a double slash, presuming the user knows what # they are doing. self.assertEqual(check_url_settings(None), []) @override_settings(MEDIA_URL='noslash') def test_media_url_no_slash(self): self.assertEqual(check_url_settings(None), [E006('MEDIA_URL')])
b0c4e821f7c9640f0c4399a26d409738fb165adcd34c121f97d051b0ff2451f5
import unittest from unittest import mock from django.core.checks import Tags, run_checks from django.core.checks.registry import CheckRegistry from django.db import connection from django.test import TestCase class DatabaseCheckTests(TestCase): databases = {'default', 'other'} @property def func(self): from django.core.checks.database import check_database_backends return check_database_backends def test_database_checks_not_run_by_default(self): """ `database` checks are only run when their tag is specified. """ def f1(**kwargs): return [5] registry = CheckRegistry() registry.register(Tags.database)(f1) errors = registry.run_checks() self.assertEqual(errors, []) errors2 = registry.run_checks(tags=[Tags.database]) self.assertEqual(errors2, [5]) def test_database_checks_called(self): with mock.patch('django.db.backends.base.validation.BaseDatabaseValidation.check') as mocked_check: run_checks(tags=[Tags.database]) self.assertTrue(mocked_check.called) @unittest.skipUnless(connection.vendor == 'mysql', 'Test only for MySQL') def test_mysql_strict_mode(self): good_sql_modes = [ 'STRICT_TRANS_TABLES,STRICT_ALL_TABLES', 'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', ] for response in good_sql_modes: with mock.patch( 'django.db.backends.utils.CursorWrapper.fetchone', create=True, return_value=(response,) ): self.assertEqual(self.func(None), []) bad_sql_modes = ['', 'WHATEVER'] for response in bad_sql_modes: with mock.patch( 'django.db.backends.utils.CursorWrapper.fetchone', create=True, return_value=(response,) ): # One warning for each database alias result = self.func(None) self.assertEqual(len(result), 2) self.assertEqual([r.id for r in result], ['mysql.W002', 'mysql.W002'])
fea378d0da0342d9cc3680f80f9ba1138ccfee61577a8cec511f5ff72bbfc633
import datetime from decimal import Decimal from django.contrib.humanize.templatetags import humanize from django.template import Context, Template, defaultfilters from django.test import SimpleTestCase, modify_settings, override_settings from django.utils import translation from django.utils.html import escape from django.utils.timezone import get_fixed_timezone, utc from django.utils.translation import gettext as _ # Mock out datetime in some tests so they don't fail occasionally when they # run too slow. Use a fixed datetime for datetime.now(). DST change in # America/Chicago (the default time zone) happened on March 11th in 2012. now = datetime.datetime(2012, 3, 9, 22, 30) class MockDateTime(datetime.datetime): @classmethod def now(cls, tz=None): if tz is None or tz.utcoffset(now) is None: return now else: # equals now.replace(tzinfo=utc) return now.replace(tzinfo=tz) + tz.utcoffset(now) @modify_settings(INSTALLED_APPS={'append': 'django.contrib.humanize'}) class HumanizeTests(SimpleTestCase): def humanize_tester(self, test_list, result_list, method, normalize_result_func=escape): for test_content, result in zip(test_list, result_list): with self.subTest(test_content): t = Template('{%% load humanize %%}{{ test_content|%s }}' % method) rendered = t.render(Context(locals())).strip() self.assertEqual( rendered, normalize_result_func(result), msg="%s test failed, produced '%s', should've produced '%s'" % (method, rendered, result) ) def test_ordinal(self): test_list = ('1', '2', '3', '4', '11', '12', '13', '101', '102', '103', '111', 'something else', None) result_list = ('1st', '2nd', '3rd', '4th', '11th', '12th', '13th', '101st', '102nd', '103rd', '111th', 'something else', None) with translation.override('en'): self.humanize_tester(test_list, result_list, 'ordinal') def test_i18n_html_ordinal(self): """Allow html in output on i18n strings""" test_list = ('1', '2', '3', '4', '11', '12', '13', '101', '102', '103', '111', 'something else', None) result_list = ('1<sup>er</sup>', '2<sup>e</sup>', '3<sup>e</sup>', '4<sup>e</sup>', '11<sup>e</sup>', '12<sup>e</sup>', '13<sup>e</sup>', '101<sup>er</sup>', '102<sup>e</sup>', '103<sup>e</sup>', '111<sup>e</sup>', 'something else', 'None') with translation.override('fr-fr'): self.humanize_tester(test_list, result_list, 'ordinal', lambda x: x) def test_intcomma(self): test_list = ( 100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000', '10123', '10311', '1000000', '1234567.1234567', Decimal('1234567.1234567'), None, ) result_list = ( '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25', '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567', '1,234,567.1234567', None, ) with translation.override('en'): self.humanize_tester(test_list, result_list, 'intcomma') def test_l10n_intcomma(self): test_list = ( 100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000', '10123', '10311', '1000000', '1234567.1234567', Decimal('1234567.1234567'), None, ) result_list = ( '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.25', '100', '1,000', '10,123', '10,311', '1,000,000', '1,234,567.1234567', '1,234,567.1234567', None, ) with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=False): with translation.override('en'): self.humanize_tester(test_list, result_list, 'intcomma') def test_intcomma_without_number_grouping(self): # Regression for #17414 with translation.override('ja'), self.settings(USE_L10N=True): self.humanize_tester([100], ['100'], 'intcomma') def test_intword(self): test_list = ( '100', '1000000', '1200000', '1290000', '1000000000', '2000000000', '6000000000000', '1300000000000000', '3500000000000000000000', '8100000000000000000000000000000000', None, ('1' + '0' * 100), ('1' + '0' * 104), ) result_list = ( '100', '1.0 million', '1.2 million', '1.3 million', '1.0 billion', '2.0 billion', '6.0 trillion', '1.3 quadrillion', '3.5 sextillion', '8.1 decillion', None, '1.0 googol', ('1' + '0' * 104), ) with translation.override('en'): self.humanize_tester(test_list, result_list, 'intword') def test_i18n_intcomma(self): test_list = (100, 1000, 10123, 10311, 1000000, 1234567.25, '100', '1000', '10123', '10311', '1000000', None) result_list = ('100', '1.000', '10.123', '10.311', '1.000.000', '1.234.567,25', '100', '1.000', '10.123', '10.311', '1.000.000', None) with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True): with translation.override('de'): self.humanize_tester(test_list, result_list, 'intcomma') def test_i18n_intword(self): test_list = ( '100', '1000000', '1200000', '1290000', '1000000000', '2000000000', '6000000000000', ) result_list = ( '100', '1,0 Million', '1,2 Millionen', '1,3 Millionen', '1,0 Milliarde', '2,0 Milliarden', '6,0 Billionen', ) with self.settings(USE_L10N=True, USE_THOUSAND_SEPARATOR=True): with translation.override('de'): self.humanize_tester(test_list, result_list, 'intword') def test_apnumber(self): test_list = [str(x) for x in range(1, 11)] test_list.append(None) result_list = ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', '10', None) with translation.override('en'): self.humanize_tester(test_list, result_list, 'apnumber') def test_naturalday(self): today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) tomorrow = today + datetime.timedelta(days=1) someday = today - datetime.timedelta(days=10) notdate = "I'm not a date value" test_list = (today, yesterday, tomorrow, someday, notdate, None) someday_result = defaultfilters.date(someday) result_list = (_('today'), _('yesterday'), _('tomorrow'), someday_result, "I'm not a date value", None) self.humanize_tester(test_list, result_list, 'naturalday') def test_naturalday_tz(self): today = datetime.date.today() tz_one = get_fixed_timezone(-720) tz_two = get_fixed_timezone(720) # Can be today or yesterday date_one = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_one) naturalday_one = humanize.naturalday(date_one) # Can be today or tomorrow date_two = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_two) naturalday_two = humanize.naturalday(date_two) # As 24h of difference they will never be the same self.assertNotEqual(naturalday_one, naturalday_two) def test_naturalday_uses_localtime(self): # Regression for #18504 # This is 2012-03-08HT19:30:00-06:00 in America/Chicago dt = datetime.datetime(2012, 3, 9, 1, 30, tzinfo=utc) orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime try: with override_settings(TIME_ZONE="America/Chicago", USE_TZ=True): with translation.override('en'): self.humanize_tester([dt], ['yesterday'], 'naturalday') finally: humanize.datetime = orig_humanize_datetime def test_naturaltime(self): class naive(datetime.tzinfo): def utcoffset(self, dt): return None test_list = [ 'test', now, now - datetime.timedelta(microseconds=1), now - datetime.timedelta(seconds=1), now - datetime.timedelta(seconds=30), now - datetime.timedelta(minutes=1, seconds=30), now - datetime.timedelta(minutes=2), now - datetime.timedelta(hours=1, minutes=30, seconds=30), now - datetime.timedelta(hours=23, minutes=50, seconds=50), now - datetime.timedelta(days=1), now - datetime.timedelta(days=500), now + datetime.timedelta(seconds=1), now + datetime.timedelta(seconds=30), now + datetime.timedelta(minutes=1, seconds=30), now + datetime.timedelta(minutes=2), now + datetime.timedelta(hours=1, minutes=30, seconds=30), now + datetime.timedelta(hours=23, minutes=50, seconds=50), now + datetime.timedelta(days=1), now + datetime.timedelta(days=2, hours=6), now + datetime.timedelta(days=500), now.replace(tzinfo=naive()), now.replace(tzinfo=utc), ] result_list = [ 'test', 'now', 'now', 'a second ago', '30\xa0seconds ago', 'a minute ago', '2\xa0minutes ago', 'an hour ago', '23\xa0hours ago', '1\xa0day ago', '1\xa0year, 4\xa0months ago', 'a second from now', '30\xa0seconds from now', 'a minute from now', '2\xa0minutes from now', 'an hour from now', '23\xa0hours from now', '1\xa0day from now', '2\xa0days, 6\xa0hours from now', '1\xa0year, 4\xa0months from now', 'now', 'now', ] # Because of the DST change, 2 days and 6 hours after the chosen # date in naive arithmetic is only 2 days and 5 hours after in # aware arithmetic. result_list_with_tz_support = result_list[:] assert result_list_with_tz_support[-4] == '2\xa0days, 6\xa0hours from now' result_list_with_tz_support[-4] == '2\xa0days, 5\xa0hours from now' orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime try: with translation.override('en'): self.humanize_tester(test_list, result_list, 'naturaltime') with override_settings(USE_TZ=True): self.humanize_tester( test_list, result_list_with_tz_support, 'naturaltime') finally: humanize.datetime = orig_humanize_datetime def test_naturaltime_as_documented(self): """ #23340 -- Verify the documented behavior of humanize.naturaltime. """ time_format = '%d %b %Y %H:%M:%S' documented_now = datetime.datetime.strptime('17 Feb 2007 16:30:00', time_format) test_data = ( ('17 Feb 2007 16:30:00', 'now'), ('17 Feb 2007 16:29:31', '29 seconds ago'), ('17 Feb 2007 16:29:00', 'a minute ago'), ('17 Feb 2007 16:25:35', '4 minutes ago'), ('17 Feb 2007 15:30:29', '59 minutes ago'), ('17 Feb 2007 15:30:01', '59 minutes ago'), ('17 Feb 2007 15:30:00', 'an hour ago'), ('17 Feb 2007 13:31:29', '2 hours ago'), ('16 Feb 2007 13:31:29', '1 day, 2 hours ago'), ('16 Feb 2007 13:30:01', '1 day, 2 hours ago'), ('16 Feb 2007 13:30:00', '1 day, 3 hours ago'), ('17 Feb 2007 16:30:30', '30 seconds from now'), ('17 Feb 2007 16:30:29', '29 seconds from now'), ('17 Feb 2007 16:31:00', 'a minute from now'), ('17 Feb 2007 16:34:35', '4 minutes from now'), ('17 Feb 2007 17:30:29', 'an hour from now'), ('17 Feb 2007 18:31:29', '2 hours from now'), ('18 Feb 2007 16:31:29', '1 day from now'), ('26 Feb 2007 18:31:29', '1 week, 2 days from now'), ) class DocumentedMockDateTime(datetime.datetime): @classmethod def now(cls, tz=None): if tz is None or tz.utcoffset(documented_now) is None: return documented_now else: return documented_now.replace(tzinfo=tz) + tz.utcoffset(now) orig_humanize_datetime = humanize.datetime humanize.datetime = DocumentedMockDateTime try: for test_time_string, expected_natural_time in test_data: with self.subTest(test_time_string): test_time = datetime.datetime.strptime(test_time_string, time_format) natural_time = humanize.naturaltime(test_time).replace('\xa0', ' ') self.assertEqual(expected_natural_time, natural_time) finally: humanize.datetime = orig_humanize_datetime def test_inflection_for_timedelta(self): """ Translation of '%d day'/'%d month'/… may differ depending on the context of the string it is inserted in. """ test_list = [ # "%(delta)s ago" translations now - datetime.timedelta(days=1), now - datetime.timedelta(days=2), now - datetime.timedelta(days=30), now - datetime.timedelta(days=60), now - datetime.timedelta(days=500), now - datetime.timedelta(days=865), # "%(delta)s from now" translations now + datetime.timedelta(days=1), now + datetime.timedelta(days=2), now + datetime.timedelta(days=30), now + datetime.timedelta(days=60), now + datetime.timedelta(days=500), now + datetime.timedelta(days=865), ] result_list = [ 'před 1\xa0dnem', 'před 2\xa0dny', 'před 1\xa0měsícem', 'před 2\xa0měsíci', 'před 1\xa0rokem, 4\xa0měsíci', 'před 2\xa0lety, 4\xa0měsíci', 'za 1\xa0den', 'za 2\xa0dny', 'za 1\xa0měsíc', 'za 2\xa0měsíce', 'za 1\xa0rok, 4\xa0měsíce', 'za 2\xa0roky, 4\xa0měsíce', ] orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime try: # Choose a language with different naturaltime-past/naturaltime-future translations with translation.override('cs'), self.settings(USE_L10N=True): self.humanize_tester(test_list, result_list, 'naturaltime') finally: humanize.datetime = orig_humanize_datetime
d34c49274d640f2eae1757325f9e2c9ad562ee9472a00bd002fbde0c920b5f1e
from functools import update_wrapper, wraps from unittest import TestCase from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import ( login_required, permission_required, user_passes_test, ) from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed from django.middleware.clickjacking import XFrameOptionsMiddleware from django.test import SimpleTestCase from django.utils.decorators import method_decorator from django.utils.functional import keep_lazy, keep_lazy_text, lazy from django.utils.safestring import mark_safe from django.views.decorators.cache import ( cache_control, cache_page, never_cache, ) from django.views.decorators.clickjacking import ( xframe_options_deny, xframe_options_exempt, xframe_options_sameorigin, ) from django.views.decorators.http import ( condition, require_GET, require_http_methods, require_POST, require_safe, ) from django.views.decorators.vary import vary_on_cookie, vary_on_headers def fully_decorated(request): """Expected __doc__""" return HttpResponse('<html><body>dummy</body></html>') fully_decorated.anything = "Expected __dict__" def compose(*functions): # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs)) functions = list(reversed(functions)) def _inner(*args, **kwargs): result = functions[0](*args, **kwargs) for f in functions[1:]: result = f(result) return result return _inner full_decorator = compose( # django.views.decorators.http require_http_methods(["GET"]), require_GET, require_POST, require_safe, condition(lambda r: None, lambda r: None), # django.views.decorators.vary vary_on_headers('Accept-language'), vary_on_cookie, # django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 user_passes_test(lambda u: True), login_required, permission_required('change_world'), # django.contrib.admin.views.decorators staff_member_required, # django.utils.functional keep_lazy(HttpResponse), keep_lazy_text, lazy, # django.utils.safestring mark_safe, ) fully_decorated = full_decorator(fully_decorated) class DecoratorsTest(TestCase): def test_attributes(self): """ Built-in decorators set certain attributes of the wrapped function. """ self.assertEqual(fully_decorated.__name__, 'fully_decorated') self.assertEqual(fully_decorated.__doc__, 'Expected __doc__') self.assertEqual(fully_decorated.__dict__['anything'], 'Expected __dict__') def test_user_passes_test_composition(self): """ The user_passes_test decorator can be applied multiple times (#9474). """ def test1(user): user.decorators_applied.append('test1') return True def test2(user): user.decorators_applied.append('test2') return True def callback(request): return request.user.decorators_applied callback = user_passes_test(test1)(callback) callback = user_passes_test(test2)(callback) class DummyUser: pass class DummyRequest: pass request = DummyRequest() request.user = DummyUser() request.user.decorators_applied = [] response = callback(request) self.assertEqual(response, ['test2', 'test1']) def test_cache_page(self): def my_view(request): return "response" my_view_cached = cache_page(123)(my_view) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = cache_page(123, key_prefix="test")(my_view) self.assertEqual(my_view_cached2(HttpRequest()), "response") def test_require_safe_accepts_only_safe_methods(self): """ Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637. """ def my_view(request): return HttpResponse("OK") my_safe_view = require_safe(my_view) request = HttpRequest() request.method = 'GET' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'HEAD' self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = 'POST' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'PUT' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = 'DELETE' self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) # For testing method_decorator, a decorator that assumes a single argument. # We will get type arguments if there is a mismatch in the number of arguments. def simple_dec(func): def wrapper(arg): return func("test:" + arg) return wraps(func)(wrapper) simple_dec_m = method_decorator(simple_dec) # For testing method_decorator, two decorators that add an attribute to the function def myattr_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr = True return wrapper myattr_dec_m = method_decorator(myattr_dec) def myattr2_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr2 = True return wrapper myattr2_dec_m = method_decorator(myattr2_dec) class ClsDec: def __init__(self, myattr): self.myattr = myattr def __call__(self, f): def wrapped(): return f() and self.myattr return update_wrapper(wrapped, f) class MethodDecoratorTests(SimpleTestCase): """ Tests for method_decorator """ def test_preserve_signature(self): class Test: @simple_dec_m def say(self, arg): return arg self.assertEqual("test:hello", Test().say("hello")) def test_preserve_attributes(self): # Sanity check myattr_dec and myattr2_dec @myattr_dec def func(): pass self.assertIs(getattr(func, 'myattr', False), True) @myattr2_dec def func(): pass self.assertIs(getattr(func, 'myattr2', False), True) @myattr_dec @myattr2_dec def func(): pass self.assertIs(getattr(func, 'myattr', False), True) self.assertIs(getattr(func, 'myattr2', False), False) # Decorate using method_decorator() on the method. class TestPlain: @myattr_dec_m @myattr2_dec_m def method(self): "A method" pass # Decorate using method_decorator() on both the class and the method. # The decorators applied to the methods are applied before the ones # applied to the class. @method_decorator(myattr_dec_m, "method") class TestMethodAndClass: @method_decorator(myattr2_dec_m) def method(self): "A method" pass # Decorate using an iterable of function decorators. @method_decorator((myattr_dec, myattr2_dec), 'method') class TestFunctionIterable: def method(self): "A method" pass # Decorate using an iterable of method decorators. decorators = (myattr_dec_m, myattr2_dec_m) @method_decorator(decorators, "method") class TestMethodIterable: def method(self): "A method" pass tests = (TestPlain, TestMethodAndClass, TestFunctionIterable, TestMethodIterable) for Test in tests: with self.subTest(Test=Test): self.assertIs(getattr(Test().method, 'myattr', False), True) self.assertIs(getattr(Test().method, 'myattr2', False), True) self.assertIs(getattr(Test.method, 'myattr', False), True) self.assertIs(getattr(Test.method, 'myattr2', False), True) self.assertEqual(Test.method.__doc__, 'A method') self.assertEqual(Test.method.__name__, 'method') def test_new_attribute(self): """A decorator that sets a new attribute on the method.""" def decorate(func): func.x = 1 return func class MyClass: @method_decorator(decorate) def method(self): return True obj = MyClass() self.assertEqual(obj.method.x, 1) self.assertIs(obj.method(), True) def test_bad_iterable(self): decorators = {myattr_dec_m, myattr2_dec_m} msg = "'set' object is not subscriptable" with self.assertRaisesMessage(TypeError, msg): @method_decorator(decorators, "method") class TestIterable: def method(self): "A method" pass # Test for argumented decorator def test_argumented(self): class Test: @method_decorator(ClsDec(False)) def method(self): return True self.assertIs(Test().method(), False) def test_descriptors(self): def original_dec(wrapped): def _wrapped(arg): return wrapped(arg) return _wrapped method_dec = method_decorator(original_dec) class bound_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __call__(self, arg): return self.wrapped(arg) def __get__(self, instance, cls=None): return self class descriptor_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __get__(self, instance, cls=None): return bound_wrapper(self.wrapped.__get__(instance, cls)) class Test: @method_dec @descriptor_wrapper def method(self, arg): return arg self.assertEqual(Test().method(1), 1) def test_class_decoration(self): """ @method_decorator can be used to decorate a class and its methods. """ def deco(func): def _wrapper(*args, **kwargs): return True return _wrapper @method_decorator(deco, name="method") class Test: def method(self): return False self.assertTrue(Test().method()) def test_tuple_of_decorators(self): """ @method_decorator can accept a tuple of decorators. """ def add_question_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "?" return _wrapper def add_exclamation_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "!" return _wrapper # The order should be consistent with the usual order in which # decorators are applied, e.g. # @add_exclamation_mark # @add_question_mark # def func(): # ... decorators = (add_exclamation_mark, add_question_mark) @method_decorator(decorators, name="method") class TestFirst: def method(self): return "hello world" class TestSecond: @method_decorator(decorators) def method(self): return "hello world" self.assertEqual(TestFirst().method(), "hello world?!") self.assertEqual(TestSecond().method(), "hello world?!") def test_invalid_non_callable_attribute_decoration(self): """ @method_decorator on a non-callable attribute raises an error. """ msg = ( "Cannot decorate 'prop' as it isn't a callable attribute of " "<class 'Test'> (1)" ) with self.assertRaisesMessage(TypeError, msg): @method_decorator(lambda: None, name="prop") class Test: prop = 1 @classmethod def __module__(cls): return "tests" def test_invalid_method_name_to_decorate(self): """ @method_decorator on a nonexistent method raises an error. """ msg = ( "The keyword argument `name` must be the name of a method of the " "decorated class: <class 'Test'>. Got 'nonexistent_method' instead" ) with self.assertRaisesMessage(ValueError, msg): @method_decorator(lambda: None, name='nonexistent_method') class Test: @classmethod def __module__(cls): return "tests" class XFrameOptionsDecoratorsTests(TestCase): """ Tests for the X-Frame-Options decorators. """ def test_deny_decorator(self): """ Ensures @xframe_options_deny properly sets the X-Frame-Options header. """ @xframe_options_deny def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r['X-Frame-Options'], 'DENY') def test_sameorigin_decorator(self): """ Ensures @xframe_options_sameorigin properly sets the X-Frame-Options header. """ @xframe_options_sameorigin def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r['X-Frame-Options'], 'SAMEORIGIN') def test_exempt_decorator(self): """ Ensures @xframe_options_exempt properly instructs the XFrameOptionsMiddleware to NOT set the header. """ @xframe_options_exempt def a_view(request): return HttpResponse() req = HttpRequest() resp = a_view(req) self.assertIsNone(resp.get('X-Frame-Options', None)) self.assertTrue(resp.xframe_options_exempt) # Since the real purpose of the exempt decorator is to suppress # the middleware's functionality, let's make sure it actually works... r = XFrameOptionsMiddleware().process_response(req, resp) self.assertIsNone(r.get('X-Frame-Options', None)) class NeverCacheDecoratorTest(TestCase): def test_never_cache_decorator(self): @never_cache def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual( set(r['Cache-Control'].split(', ')), {'max-age=0', 'no-cache', 'no-store', 'must-revalidate'}, )
ca808f9570f718fc2a01b59c4680152aed489bd7cddb7343c51c415ec3367202
import datetime from django.contrib.auth.models import User from django.test import TestCase from .models import Order, RevisionableModel, TestObject class ExtraRegressTests(TestCase): @classmethod def setUpTestData(cls): cls.u = User.objects.create_user( username="fred", password="secret", email="[email protected]" ) def test_regression_7314_7372(self): """ Regression tests for #7314 and #7372 """ 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.title, 'Second Revision') self.assertEqual(rm2.base.title, 'First Revision') self.assertNotEqual(rm2.pk, rm.pk) self.assertEqual(rm2.base.pk, rm.pk) # Queryset to match most recent revision: qs = RevisionableModel.objects.extra( where=["%(table)s.id IN (SELECT MAX(rev.id) FROM %(table)s rev GROUP BY rev.base_id)" % { 'table': RevisionableModel._meta.db_table, }] ) self.assertQuerysetEqual( qs, [('Second Revision', 'First Revision')], transform=lambda r: (r.title, r.base.title) ) # Queryset to search for string in title: qs2 = RevisionableModel.objects.filter(title__contains="Revision") self.assertQuerysetEqual( qs2, [ ('First Revision', 'First Revision'), ('Second Revision', 'First Revision'), ], transform=lambda r: (r.title, r.base.title), ordered=False ) # Following queryset should return the most recent revision: self.assertQuerysetEqual( qs & qs2, [('Second Revision', 'First Revision')], transform=lambda r: (r.title, r.base.title), ordered=False ) def test_extra_stay_tied(self): # Extra select parameters should stay tied to their corresponding # select portions. Applies when portions are updated or otherwise # moved around. qs = User.objects.extra(select={'alpha': '%s', 'beta': "2", 'gamma': '%s'}, select_params=(1, 3)) qs = qs.extra(select={"beta": 4}) qs = qs.extra(select={"alpha": "%s"}, select_params=[5]) self.assertEqual( list(qs.filter(id=self.u.id).values('alpha', 'beta', 'gamma')), [{'alpha': 5, 'beta': 4, 'gamma': 3}] ) def test_regression_7957(self): """ 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. """ 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 ) def test_regression_7961(self): """ Regression test for #7961: When not using a portion of an extra(...) in a query, remove any corresponding parameters from the query as well. """ 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] ) def test_regression_8063(self): """ Regression test for #8063: limiting a query shouldn't discard any extra() bits. """ qs = User.objects.all().extra(where=['id=%s'], params=[self.u.id]) self.assertQuerysetEqual(qs, ['<User: fred>']) self.assertQuerysetEqual(qs[:1], ['<User: fred>']) def test_regression_8039(self): """ 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 optimization. The table should still be present because of the extra() call. """ self.assertQuerysetEqual( (Order.objects .extra(where=["username=%s"], params=["fred"], tables=["auth_user"]) .order_by('created_by')), [] ) def test_regression_8819(self): """ Regression test for #8819: Fields in the extra(select=...) list should be available to extra(order_by=...). """ 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.filter(pk=self.u.id).extra(select={'extra_field': 1}, order_by=['extra_field']).distinct(), ['<User: fred>'] ) def test_dates_query(self): """ 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. """ RevisionableModel.objects.create( title='First Revision', when=datetime.datetime(2008, 9, 28, 10, 30, 0) ) self.assertSequenceEqual( RevisionableModel.objects.extra(select={"the_answer": 'id'}).datetimes('when', 'month'), [datetime.datetime(2008, 9, 1, 0, 0)], ) def test_values_with_extra(self): """ Regression test for #10256... If there is a values() clause, Extra columns are only returned if they are explicitly mentioned. """ obj = TestObject(first='first', second='second', third='third') obj.save() self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values() ), [{ 'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first' }] ) # Extra clauses after an empty values clause are still included self.assertEqual( list( TestObject.objects .values() .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) ), [{ 'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first' }] ) # Extra columns are ignored if not mentioned in the values() clause self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values('first', 'second') ), [{'second': 'second', 'first': 'first'}] ) # Extra columns after a non-empty values() clause are ignored self.assertEqual( list( TestObject.objects .values('first', 'second') .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) ), [{'second': 'second', 'first': 'first'}] ) # Extra columns can be partially returned self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values('first', 'second', 'foo') ), [{'second': 'second', 'foo': 'first', 'first': 'first'}] ) # Also works if only extra columns are included self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values('foo', 'whiz') ), [{'foo': 'first', 'whiz': 'third'}] ) # Values list works the same way # All columns are returned for an empty values_list() self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values_list() ), [('first', 'second', 'third', obj.pk, 'first', 'second', 'third')] ) # Extra columns after an empty values_list() are still included self.assertEqual( list( TestObject.objects .values_list() .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) ), [('first', 'second', 'third', obj.pk, 'first', 'second', 'third')] ) # Extra columns ignored completely if not mentioned in values_list() self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values_list('first', 'second') ), [('first', 'second')] ) # Extra columns after a non-empty values_list() clause are ignored completely self.assertEqual( list( TestObject.objects .values_list('first', 'second') .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) ), [('first', 'second')] ) self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values_list('second', flat=True) ), ['second'] ) # Only the extra columns specified in the values_list() are returned self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values_list('first', 'second', 'whiz') ), [('first', 'second', 'third')] ) # ...also works if only extra columns are included self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values_list('foo', 'whiz') ), [('first', 'third')] ) self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values_list('whiz', flat=True) ), ['third'] ) # ... and values are returned in the order they are specified self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values_list('whiz', 'foo') ), [('third', 'first')] ) self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values_list('first', 'id') ), [('first', obj.pk)] ) self.assertEqual( list( TestObject.objects .extra(select={'foo': 'first', 'bar': 'second', 'whiz': 'third'}) .values_list('whiz', 'first', 'bar', 'id') ), [('third', 'first', 'second', obj.pk)] ) def test_regression_10847(self): """ 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. """ 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') ), ['<TestObject: TestObject: first,second,third>'] ) self.assertEqual( list(TestObject.objects.values('pk').extra(select={'extra': 1})), [{'pk': obj.pk}] ) self.assertQuerysetEqual( TestObject.objects.filter( pk__in=TestObject.objects.values('pk').extra(select={'extra': 1}) ), ['<TestObject: TestObject: first,second,third>'] ) self.assertQuerysetEqual( TestObject.objects.filter(pk=obj.pk) | TestObject.objects.extra(where=["id > %s"], params=[obj.pk]), ['<TestObject: TestObject: first,second,third>'] ) def test_regression_17877(self): """ Extra WHERE clauses get correctly ANDed, even when they contain OR operations. """ # Test Case 1: should appear in queryset. t = TestObject(first='a', second='a', third='a') t.save() # Test Case 2: should appear in queryset. t = TestObject(first='b', second='a', third='a') t.save() # Test Case 3: should not appear in queryset, bug case. t = TestObject(first='a', second='a', third='b') t.save() # Test Case 4: should not appear in queryset. t = TestObject(first='b', second='a', third='b') t.save() # Test Case 5: should not appear in queryset. t = TestObject(first='b', second='b', third='a') t.save() # Test Case 6: should not appear in queryset, bug case. t = TestObject(first='a', second='b', third='b') t.save() self.assertQuerysetEqual( TestObject.objects.extra( where=["first = 'a' OR second = 'a'", "third = 'a'"], ), ['<TestObject: TestObject: a,a,a>', '<TestObject: TestObject: b,a,a>'], ordered=False ) def test_extra_values_distinct_ordering(self): t1 = TestObject.objects.create(first='a', second='a', third='a') t2 = TestObject.objects.create(first='a', second='b', third='b') qs = TestObject.objects.extra( select={'second_extra': 'second'} ).values_list('id', flat=True).distinct() self.assertSequenceEqual(qs.order_by('second_extra'), [t1.pk, t2.pk]) self.assertSequenceEqual(qs.order_by('-second_extra'), [t2.pk, t1.pk]) # Note: the extra ordering must appear in select clause, so we get two # non-distinct results here (this is on purpose, see #7070). # Extra select doesn't appear in result values. self.assertSequenceEqual(qs.order_by('-second_extra').values_list('first'), [('a',), ('a',)])
fa9d7f447873a561a352484e4e32aec81944ff0039435c69f57d3b10680bad56
from functools import update_wrapper from django.contrib import admin from django.db import models from django.http import HttpResponseRedirect from django.urls import reverse class Action(models.Model): name = models.CharField(max_length=50, primary_key=True) description = models.CharField(max_length=70) def __str__(self): return self.name class ActionAdmin(admin.ModelAdmin): """ A ModelAdmin for the Action model that changes the URL of the add_view to '<app name>/<model name>/!add/' The Action model has a CharField PK. """ list_display = ('name', 'description') def remove_url(self, name): """ Remove all entries named 'name' from the ModelAdmin instance URL patterns list """ return [url for url in super().get_urls() if url.name != name] def get_urls(self): # Add the URL of our custom 'add_view' view to the front of the URLs # list. Remove the existing one(s) first from django.urls import re_path def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = self.model._meta.app_label, self.model._meta.model_name view_name = '%s_%s_add' % info return [ re_path('^!add/$', wrap(self.add_view), name=view_name), ] + self.remove_url(view_name) class Person(models.Model): name = models.CharField(max_length=20) class PersonAdmin(admin.ModelAdmin): def response_post_save_add(self, request, obj): return HttpResponseRedirect( reverse('admin:admin_custom_urls_person_history', args=[obj.pk])) def response_post_save_change(self, request, obj): return HttpResponseRedirect( reverse('admin:admin_custom_urls_person_delete', args=[obj.pk])) class Car(models.Model): name = models.CharField(max_length=20) class CarAdmin(admin.ModelAdmin): def response_add(self, request, obj, post_url_continue=None): return super().response_add( request, obj, post_url_continue=reverse('admin:admin_custom_urls_car_history', args=[obj.pk]), ) site = admin.AdminSite(name='admin_custom_urls') site.register(Action, ActionAdmin) site.register(Person, PersonAdmin) site.register(Car, CarAdmin)
e23ed2a101a660daba64e60ab1da38ceb0f63a7e301e671478087b65198927af
from django.urls import path from .models import site urlpatterns = [ path('admin/', site.urls), ]
cd977c0d71497a6d7d82e8d07970c9321b59679482f68ad0be0b6af8d74411f3
import os import shutil import tempfile from django import conf from django.test import SimpleTestCase from django.test.utils import extend_sys_path class TestStartProjectSettings(SimpleTestCase): def setUp(self): self.temp_dir = tempfile.TemporaryDirectory() self.addCleanup(self.temp_dir.cleanup) template_settings_py = os.path.join( os.path.dirname(conf.__file__), 'project_template', 'project_name', 'settings.py-tpl', ) test_settings_py = os.path.join(self.temp_dir.name, 'test_settings.py') shutil.copyfile(template_settings_py, test_settings_py) def test_middleware_headers(self): """ Ensure headers sent by the default MIDDLEWARE don't inadvertently change. For example, we never want "Vary: Cookie" to appear in the list since it prevents the caching of responses. """ with extend_sys_path(self.temp_dir.name): from test_settings import MIDDLEWARE with self.settings( MIDDLEWARE=MIDDLEWARE, ROOT_URLCONF='project_template.urls', ): response = self.client.get('/empty/') headers = sorted(response.serialize_headers().split(b'\r\n')) self.assertEqual(headers, [ b'Content-Length: 0', b'Content-Type: text/html; charset=utf-8', b'X-Frame-Options: SAMEORIGIN', ])
de3adf972889b06a974ca5d0f559e71121ebc01a2e9981fa51d9693cfd16f75f
from django.urls import path from . import views urlpatterns = [ path('empty/', views.empty_view), ]
7ec60849512b8fd3b1ca519b9f2e725482a8cb94fe219c39187c4829d2a78505
from django.urls import path from . import views urlpatterns = [ path('condition/', views.index), path('condition/last_modified/', views.last_modified_view1), path('condition/last_modified2/', views.last_modified_view2), path('condition/etag/', views.etag_view1), path('condition/etag2/', views.etag_view2), path('condition/unquoted_etag/', views.etag_view_unquoted), path('condition/weak_etag/', views.etag_view_weak), path('condition/no_etag/', views.etag_view_none), ]
1dbb951c18955dc7dd30efc5b201f822ff8678e665eff4146b831b6fececbf33
""" A series of tests to establish that the command-line management tools work as advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE and default settings.py files. """ import os import re import shutil import socket import subprocess import sys import tempfile import unittest from io import StringIO from unittest import mock import django from django import conf, get_version from django.conf import settings from django.core.management import ( BaseCommand, CommandError, call_command, color, ) from django.core.management.commands.loaddata import Command as LoaddataCommand from django.core.management.commands.runserver import ( Command as RunserverCommand, ) from django.core.management.commands.testserver import ( Command as TestserverCommand, ) from django.db import ConnectionHandler, connection from django.db.migrations.recorder import MigrationRecorder from django.test import ( LiveServerTestCase, SimpleTestCase, TestCase, override_settings, ) custom_templates_dir = os.path.join(os.path.dirname(__file__), 'custom_templates') SYSTEM_CHECK_MSG = 'System check identified no issues' class AdminScriptTestCase(SimpleTestCase): def setUp(self): tmpdir = tempfile.TemporaryDirectory() self.addCleanup(tmpdir.cleanup) # os.path.realpath() is required for temporary directories on macOS, # where `/var` is a symlink to `/private/var`. self.test_dir = os.path.realpath(os.path.join(tmpdir.name, 'test_project')) os.mkdir(self.test_dir) with open(os.path.join(self.test_dir, '__init__.py'), 'w'): pass def write_settings(self, filename, apps=None, is_dir=False, sdict=None, extra=None): if is_dir: settings_dir = os.path.join(self.test_dir, filename) os.mkdir(settings_dir) settings_file_path = os.path.join(settings_dir, '__init__.py') else: settings_file_path = os.path.join(self.test_dir, filename) with open(settings_file_path, 'w') as settings_file: settings_file.write('# Settings file automatically generated by admin_scripts test case\n') if extra: settings_file.write("%s\n" % extra) exports = [ 'DATABASES', 'ROOT_URLCONF', 'SECRET_KEY', ] for s in exports: if hasattr(settings, s): o = getattr(settings, s) if not isinstance(o, (dict, tuple, list)): o = "'%s'" % o settings_file.write("%s = %s\n" % (s, o)) if apps is None: apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts'] settings_file.write("INSTALLED_APPS = %s\n" % apps) if sdict: for k, v in sdict.items(): settings_file.write("%s = %s\n" % (k, v)) def _ext_backend_paths(self): """ Returns the paths for any external backend packages. """ paths = [] for backend in settings.DATABASES.values(): package = backend['ENGINE'].split('.')[0] if package != 'django': backend_pkg = __import__(package) backend_dir = os.path.dirname(backend_pkg.__file__) paths.append(os.path.dirname(backend_dir)) return paths def run_test(self, script, args, settings_file=None, apps=None): base_dir = os.path.dirname(self.test_dir) # The base dir for Django's tests is one level up. tests_dir = os.path.dirname(os.path.dirname(__file__)) # The base dir for Django is one level above the test dir. We don't use # `import django` to figure that out, so we don't pick up a Django # from site-packages or similar. django_dir = os.path.dirname(tests_dir) ext_backend_base_dirs = self._ext_backend_paths() # Define a temporary environment for the subprocess test_environ = os.environ.copy() # Set the test environment if settings_file: test_environ['DJANGO_SETTINGS_MODULE'] = settings_file elif 'DJANGO_SETTINGS_MODULE' in test_environ: del test_environ['DJANGO_SETTINGS_MODULE'] python_path = [base_dir, django_dir, tests_dir] python_path.extend(ext_backend_base_dirs) test_environ['PYTHONPATH'] = os.pathsep.join(python_path) test_environ['PYTHONWARNINGS'] = '' return subprocess.Popen( [sys.executable, script] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.test_dir, env=test_environ, universal_newlines=True, ).communicate() def run_django_admin(self, args, settings_file=None): script_dir = os.path.abspath(os.path.join(os.path.dirname(django.__file__), 'bin')) return self.run_test(os.path.join(script_dir, 'django-admin.py'), args, settings_file) def run_manage(self, args, settings_file=None, manage_py=None): template_manage_py = ( os.path.join(os.path.dirname(__file__), manage_py) if manage_py else os.path.join(os.path.dirname(conf.__file__), 'project_template', 'manage.py-tpl') ) test_manage_py = os.path.join(self.test_dir, 'manage.py') shutil.copyfile(template_manage_py, test_manage_py) with open(test_manage_py) as fp: manage_py_contents = fp.read() manage_py_contents = manage_py_contents.replace( "{{ project_name }}", "test_project") with open(test_manage_py, 'w') as fp: fp.write(manage_py_contents) return self.run_test('./manage.py', args, settings_file) def assertNoOutput(self, stream): "Utility assertion: assert that the given stream is empty" self.assertEqual(len(stream), 0, "Stream should be empty: actually contains '%s'" % stream) def assertOutput(self, stream, msg, regex=False): "Utility assertion: assert that the given message exists in the output" if regex: self.assertIsNotNone( re.search(msg, stream), "'%s' does not match actual output text '%s'" % (msg, stream) ) else: self.assertIn(msg, stream, "'%s' does not match actual output text '%s'" % (msg, stream)) def assertNotInOutput(self, stream, msg): "Utility assertion: assert that the given message doesn't exist in the output" self.assertNotIn(msg, stream, "'%s' matches actual output text '%s'" % (msg, stream)) ########################################################################## # DJANGO ADMIN TESTS # This first series of test classes checks the environment processing # of the django-admin.py script ########################################################################## class DjangoAdminNoSettings(AdminScriptTestCase): "A series of tests for django-admin.py when there is no settings.py file." def test_builtin_command(self): "no settings: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_bad_settings(self): "no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_commands_with_invalid_settings(self): """" Commands that don't require settings succeed if the settings file doesn't exist. """ args = ['startproject'] out, err = self.run_django_admin(args, settings_file='bad_settings') self.assertNoOutput(out) self.assertOutput(err, "You must provide a project name", regex=True) class DjangoAdminDefaultSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings.py file that contains the test application. """ def setUp(self): super().setUp() self.write_settings('settings.py') def test_builtin_command(self): "default: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_settings(self): "default: django-admin builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "default: django-admin builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "default: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "default: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "default: django-admin can't execute user commands if it isn't provided settings" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "default: django-admin can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "default: django-admin can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings.py file that contains the test application specified using a full path. """ def setUp(self): super().setUp() self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts', 'admin_scripts.complex_app']) def test_builtin_command(self): "fulldefault: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_settings(self): "fulldefault: django-admin builtin commands succeed if a settings file is provided" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "fulldefault: django-admin builtin commands succeed if the environment contains settings" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "fulldefault: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "fulldefault: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "fulldefault: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "fulldefault: django-admin can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "fulldefault: django-admin can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminMinimalSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings.py file that doesn't contain the test application. """ def setUp(self): super().setUp() self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) def test_builtin_command(self): "minimal: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_settings(self): "minimal: django-admin builtin commands fail if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): "minimal: django-admin builtin commands fail if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): "minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "minimal: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "minimal: django-admin can't execute user commands, even if settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): "minimal: django-admin can't execute user commands, even if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class DjangoAdminAlternateSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings file with a name other than 'settings.py'. """ def setUp(self): super().setUp() self.write_settings('alternate_settings.py') def test_builtin_command(self): "alternate: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_settings(self): "alternate: django-admin builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.alternate_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "alternate: django-admin builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.alternate_settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "alternate: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "alternate: django-admin can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=test_project.alternate_settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "alternate: django-admin can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args, 'test_project.alternate_settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminMultipleSettings(AdminScriptTestCase): """A series of tests for django-admin.py when multiple settings files (including the default 'settings.py') are available. The default settings file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ def setUp(self): super().setUp() self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) self.write_settings('alternate_settings.py') def test_builtin_command(self): "alternate: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_settings(self): "alternate: django-admin builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.alternate_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "alternate: django-admin builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.alternate_settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "alternate: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "alternate: django-admin can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=test_project.alternate_settings'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "alternate: django-admin can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_django_admin(args, 'test_project.alternate_settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminSettingsDirectory(AdminScriptTestCase): """ A series of tests for django-admin.py when the settings file is in a directory. (see #9751). """ def setUp(self): super().setUp() self.write_settings('settings', is_dir=True) def test_setup_environ(self): "directory: startapp creates the correct directory" args = ['startapp', 'settings_test'] app_path = os.path.join(self.test_dir, 'settings_test') out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) with open(os.path.join(app_path, 'apps.py')) as f: content = f.read() self.assertIn("class SettingsTestConfig(AppConfig)", content) self.assertIn("name = 'settings_test'", content) def test_setup_environ_custom_template(self): "directory: startapp creates the correct directory with a custom template" template_path = os.path.join(custom_templates_dir, 'app_template') args = ['startapp', '--template', template_path, 'custom_settings_test'] app_path = os.path.join(self.test_dir, 'custom_settings_test') out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) self.assertTrue(os.path.exists(os.path.join(app_path, 'api.py'))) def test_startapp_unicode_name(self): "directory: startapp creates the correct directory with unicode characters" args = ['startapp', 'こんにちは'] app_path = os.path.join(self.test_dir, 'こんにちは') out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) with open(os.path.join(app_path, 'apps.py'), encoding='utf8') as f: content = f.read() self.assertIn("class こんにちはConfig(AppConfig)", content) self.assertIn("name = 'こんにちは'", content) def test_builtin_command(self): "directory: django-admin builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, 'settings are not configured') def test_builtin_with_bad_settings(self): "directory: django-admin builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "directory: django-admin builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "directory: django-admin can't execute user commands unless settings are provided" args = ['noargs_command'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_builtin_with_settings(self): "directory: django-admin builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "directory: django-admin builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_django_admin(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) ########################################################################## # MANAGE.PY TESTS # This next series of test classes checks the environment processing # of the generated manage.py script ########################################################################## class ManageNoSettings(AdminScriptTestCase): "A series of tests for manage.py when there is no settings.py file." def test_builtin_command(self): "no settings: manage.py builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True) def test_builtin_with_bad_settings(self): "no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "no settings: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) class ManageDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application. """ def setUp(self): super().setUp() self.write_settings('settings.py') def test_builtin_command(self): "default: manage.py builtin commands succeed when default settings are appropriate" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_settings(self): "default: manage.py builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "default: manage.py builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "default: manage.py builtin commands succeed if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "default: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "default: manage.py can execute user commands when default settings are appropriate" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_settings(self): "default: manage.py can execute user commands when settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "default: manage.py can execute user commands when settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageFullPathDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application specified using a full path. """ def setUp(self): super().setUp() self.write_settings('settings.py', ['django.contrib.auth', 'django.contrib.contenttypes', 'admin_scripts']) def test_builtin_command(self): "fulldefault: manage.py builtin commands succeed when default settings are appropriate" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_settings(self): "fulldefault: manage.py builtin commands succeed if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "fulldefault: manage.py builtin commands succeed if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "fulldefault: manage.py builtin commands succeed if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "fulldefault: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "fulldefault: manage.py can execute user commands when default settings are appropriate" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_settings(self): "fulldefault: manage.py can execute user commands when settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "fulldefault: manage.py can execute user commands when settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageMinimalSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that doesn't contain the test application. """ def setUp(self): super().setUp() self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) def test_builtin_command(self): "minimal: manage.py builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_settings(self): "minimal: manage.py builtin commands fail if settings are provided as argument" args = ['check', '--settings=test_project.settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): "minimal: manage.py builtin commands fail if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): "minimal: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "minimal: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "minimal: manage.py can't execute user commands without appropriate settings" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "minimal: manage.py can't execute user commands, even if settings are provided as argument" args = ['noargs_command', '--settings=test_project.settings'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): "minimal: manage.py can't execute user commands, even if settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args, 'test_project.settings') self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class ManageAlternateSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings file with a name other than 'settings.py'. """ def setUp(self): super().setUp() self.write_settings('alternate_settings.py') def test_builtin_command(self): "alternate: manage.py builtin commands fail with an error when no default settings provided" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True) def test_builtin_with_settings(self): "alternate: manage.py builtin commands work with settings provided as argument" args = ['check', '--settings=alternate_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertOutput(out, SYSTEM_CHECK_MSG) self.assertNoOutput(err) def test_builtin_with_environment(self): "alternate: manage.py builtin commands work if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'alternate_settings') self.assertOutput(out, SYSTEM_CHECK_MSG) self.assertNoOutput(err) def test_builtin_with_bad_settings(self): "alternate: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "alternate: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "alternate: manage.py can't execute user commands without settings" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, r"No module named '?(test_project\.)?settings'?", regex=True) def test_custom_command_with_settings(self): "alternate: manage.py can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=alternate_settings'] out, err = self.run_manage(args) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', " "'alternate_settings'), ('traceback', False), ('verbosity', 1)]" ) self.assertNoOutput(err) def test_custom_command_with_environment(self): "alternate: manage.py can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args, 'alternate_settings') self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', None), " "('traceback', False), ('verbosity', 1)]" ) self.assertNoOutput(err) def test_custom_command_output_color(self): "alternate: manage.py output syntax color can be deactivated with the `--no-color` option" args = ['noargs_command', '--no-color', '--settings=alternate_settings'] out, err = self.run_manage(args) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', True), ('pythonpath', None), ('settings', " "'alternate_settings'), ('traceback', False), ('verbosity', 1)]" ) self.assertNoOutput(err) class ManageMultipleSettings(AdminScriptTestCase): """A series of tests for manage.py when multiple settings files (including the default 'settings.py') are available. The default settings file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ def setUp(self): super().setUp() self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) self.write_settings('alternate_settings.py') def test_builtin_command(self): "multiple: manage.py builtin commands fail with an error when no settings provided" args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_settings(self): "multiple: manage.py builtin commands succeed if settings are provided as argument" args = ['check', '--settings=alternate_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): "multiple: manage.py can execute builtin commands if settings are provided in the environment" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'alternate_settings') self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): "multiple: manage.py builtin commands fail if settings file (from argument) doesn't exist" args = ['check', '--settings=bad_settings', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): "multiple: manage.py builtin commands fail if settings file (from environment) doesn't exist" args = ['check', 'admin_scripts'] out, err = self.run_manage(args, 'bad_settings') self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "multiple: manage.py can't execute user commands using default settings" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): "multiple: manage.py can execute user commands if settings are provided as argument" args = ['noargs_command', '--settings=alternate_settings'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): "multiple: manage.py can execute user commands if settings are provided in environment" args = ['noargs_command'] out, err = self.run_manage(args, 'alternate_settings') self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageSettingsWithSettingsErrors(AdminScriptTestCase): """ Tests for manage.py when using the default settings.py file containing runtime errors. """ def write_settings_with_import_error(self, filename): settings_file_path = os.path.join(self.test_dir, filename) with open(settings_file_path, 'w') as settings_file: settings_file.write('# Settings file automatically generated by admin_scripts test case\n') settings_file.write('# The next line will cause an import error:\nimport foo42bar\n') def test_import_error(self): """ import error: manage.py builtin commands shows useful diagnostic info when settings with import errors is provided (#14130). """ self.write_settings_with_import_error('settings.py') args = ['check', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named") self.assertOutput(err, "foo42bar") def test_attribute_error(self): """ manage.py builtin commands does not swallow attribute error due to bad settings (#18845). """ self.write_settings('settings.py', sdict={'BAD_VAR': 'INSTALLED_APPS.crash'}) args = ['collectstatic', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "AttributeError: 'list' object has no attribute 'crash'") def test_key_error(self): self.write_settings('settings.py', sdict={'BAD_VAR': 'DATABASES["blah"]'}) args = ['collectstatic', 'admin_scripts'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "KeyError: 'blah'") def test_help(self): """ Test listing available commands output note when only core commands are available. """ self.write_settings( 'settings.py', extra='from django.core.exceptions import ImproperlyConfigured\n' 'raise ImproperlyConfigured()', ) args = ['help'] out, err = self.run_manage(args) self.assertOutput(out, 'only Django core commands are listed') self.assertNoOutput(err) class ManageCheck(AdminScriptTestCase): def test_nonexistent_app(self): """check reports an error on a nonexistent app in INSTALLED_APPS.""" self.write_settings( 'settings.py', apps=['admin_scriptz.broken_app'], sdict={'USE_I18N': False}, ) args = ['check'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, 'ModuleNotFoundError') self.assertOutput(err, 'No module named') self.assertOutput(err, 'admin_scriptz') def test_broken_app(self): """ manage.py check reports an ImportError if an app's models.py raises one on import """ self.write_settings('settings.py', apps=['admin_scripts.broken_app']) args = ['check'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, 'ImportError') def test_complex_app(self): """ manage.py check does not raise an ImportError validating a complex app with nested calls to load_app """ self.write_settings( 'settings.py', apps=[ 'admin_scripts.complex_app', 'admin_scripts.simple_app', 'django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', ], sdict={ 'DEBUG': True, 'MIDDLEWARE': [ 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ], 'TEMPLATES': [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ], } ) args = ['check'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertEqual(out, 'System check identified no issues (0 silenced).\n') def test_app_with_import(self): """ manage.py check does not raise errors when an app imports a base class that itself has an abstract base. """ self.write_settings( 'settings.py', apps=[ 'admin_scripts.app_with_import', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sites', ], sdict={'DEBUG': True}, ) args = ['check'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertEqual(out, 'System check identified no issues (0 silenced).\n') def test_output_format(self): """ All errors/warnings should be sorted by level and by message. """ self.write_settings( 'settings.py', apps=[ 'admin_scripts.app_raising_messages', 'django.contrib.auth', 'django.contrib.contenttypes', ], sdict={'DEBUG': True}, ) args = ['check'] out, err = self.run_manage(args) expected_err = ( "SystemCheckError: System check identified some issues:\n" "\n" "ERRORS:\n" "?: An error\n" "\tHINT: Error hint\n" "\n" "WARNINGS:\n" "a: Second warning\n" "obj: First warning\n" "\tHINT: Hint\n" "\n" "System check identified 3 issues (0 silenced).\n" ) self.assertEqual(err, expected_err) self.assertNoOutput(out) def test_warning_does_not_halt(self): """ When there are only warnings or less serious messages, then Django should not prevent user from launching their project, so `check` command should not raise `CommandError` exception. In this test we also test output format. """ self.write_settings( 'settings.py', apps=[ 'admin_scripts.app_raising_warning', 'django.contrib.auth', 'django.contrib.contenttypes', ], sdict={'DEBUG': True}, ) args = ['check'] out, err = self.run_manage(args) expected_err = ( "System check identified some issues:\n" # No "CommandError: " part "\n" "WARNINGS:\n" "?: A warning\n" "\n" "System check identified 1 issue (0 silenced).\n" ) self.assertEqual(err, expected_err) self.assertNoOutput(out) class ManageRunserver(SimpleTestCase): def setUp(self): def monkey_run(*args, **options): return self.output = StringIO() self.cmd = RunserverCommand(stdout=self.output) self.cmd.run = monkey_run def assertServerSettings(self, addr, port, ipv6=False, raw_ipv6=False): self.assertEqual(self.cmd.addr, addr) self.assertEqual(self.cmd.port, port) self.assertEqual(self.cmd.use_ipv6, ipv6) self.assertEqual(self.cmd._raw_ipv6, raw_ipv6) def test_runserver_addrport(self): call_command(self.cmd) self.assertServerSettings('127.0.0.1', '8000') call_command(self.cmd, addrport="1.2.3.4:8000") self.assertServerSettings('1.2.3.4', '8000') call_command(self.cmd, addrport="7000") self.assertServerSettings('127.0.0.1', '7000') @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_addrport_ipv6(self): call_command(self.cmd, addrport="", use_ipv6=True) self.assertServerSettings('::1', '8000', ipv6=True, raw_ipv6=True) call_command(self.cmd, addrport="7000", use_ipv6=True) self.assertServerSettings('::1', '7000', ipv6=True, raw_ipv6=True) call_command(self.cmd, addrport="[2001:0db8:1234:5678::9]:7000") self.assertServerSettings('2001:0db8:1234:5678::9', '7000', ipv6=True, raw_ipv6=True) def test_runner_hostname(self): call_command(self.cmd, addrport="localhost:8000") self.assertServerSettings('localhost', '8000') call_command(self.cmd, addrport="test.domain.local:7000") self.assertServerSettings('test.domain.local', '7000') @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_hostname_ipv6(self): call_command(self.cmd, addrport="test.domain.local:7000", use_ipv6=True) self.assertServerSettings('test.domain.local', '7000', ipv6=True) def test_runner_custom_defaults(self): self.cmd.default_addr = '0.0.0.0' self.cmd.default_port = '5000' call_command(self.cmd) self.assertServerSettings('0.0.0.0', '5000') @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_custom_defaults_ipv6(self): self.cmd.default_addr_ipv6 = '::' call_command(self.cmd, use_ipv6=True) self.assertServerSettings('::', '8000', ipv6=True, raw_ipv6=True) def test_runner_ambiguous(self): # Only 4 characters, all of which could be in an ipv6 address call_command(self.cmd, addrport="beef:7654") self.assertServerSettings('beef', '7654') # Uses only characters that could be in an ipv6 address call_command(self.cmd, addrport="deadbeef:7654") self.assertServerSettings('deadbeef', '7654') def test_no_database(self): """ Ensure runserver.check_migrations doesn't choke on empty DATABASES. """ tested_connections = ConnectionHandler({}) with mock.patch('django.core.management.base.connections', new=tested_connections): self.cmd.check_migrations() def test_readonly_database(self): """ runserver.check_migrations() doesn't choke when a database is read-only. """ with mock.patch.object(MigrationRecorder, 'has_table', return_value=False): self.cmd.check_migrations() # You have # ... self.assertIn('unapplied migration(s)', self.output.getvalue()) class ManageRunserverMigrationWarning(TestCase): def setUp(self): self.stdout = StringIO() self.runserver_command = RunserverCommand(stdout=self.stdout) @override_settings(INSTALLED_APPS=["admin_scripts.app_waiting_migration"]) def test_migration_warning_one_app(self): self.runserver_command.check_migrations() output = self.stdout.getvalue() self.assertIn('You have 1 unapplied migration(s)', output) self.assertIn('apply the migrations for app(s): app_waiting_migration.', output) @override_settings( INSTALLED_APPS=[ "admin_scripts.app_waiting_migration", "admin_scripts.another_app_waiting_migration", ], ) def test_migration_warning_multiple_apps(self): self.runserver_command.check_migrations() output = self.stdout.getvalue() self.assertIn('You have 2 unapplied migration(s)', output) self.assertIn( 'apply the migrations for app(s): another_app_waiting_migration, ' 'app_waiting_migration.', output ) class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase): def setUp(self): super().setUp() self.write_settings('settings.py', sdict={ 'ALLOWED_HOSTS': [], 'DEBUG': False, }) def test_empty_allowed_hosts_error(self): out, err = self.run_manage(['runserver']) self.assertNoOutput(out) self.assertOutput(err, 'CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False.') class ManageTestserver(SimpleTestCase): @mock.patch.object(TestserverCommand, 'handle', return_value='') def test_testserver_handle_params(self, mock_handle): out = StringIO() call_command('testserver', 'blah.json', stdout=out) mock_handle.assert_called_with( 'blah.json', stdout=out, settings=None, pythonpath=None, verbosity=1, traceback=False, addrport='', no_color=False, use_ipv6=False, skip_checks=True, interactive=True, force_color=False, ) @mock.patch('django.db.connection.creation.create_test_db', return_value='test_db') @mock.patch.object(LoaddataCommand, 'handle', return_value='') @mock.patch.object(RunserverCommand, 'handle', return_value='') def test_params_to_runserver(self, mock_runserver_handle, mock_loaddata_handle, mock_create_test_db): out = StringIO() call_command('testserver', 'blah.json', stdout=out) mock_runserver_handle.assert_called_with( addrport='', force_color=False, insecure_serving=False, no_color=False, pythonpath=None, settings=None, shutdown_message=( "\nServer stopped.\nNote that the test database, 'test_db', " "has not been deleted. You can explore it on your own." ), skip_checks=True, traceback=False, use_ipv6=False, use_reloader=False, use_static_handler=True, use_threading=connection.features.test_db_allows_multiple_connections, verbosity=1, ) ########################################################################## # COMMAND PROCESSING TESTS # user-space commands are correctly handled - in particular, arguments to # the commands are correctly parsed and processed. ########################################################################## class ColorCommand(BaseCommand): requires_system_checks = False def handle(self, *args, **options): self.stdout.write('Hello, world!', self.style.ERROR) self.stderr.write('Hello, world!', self.style.ERROR) class CommandTypes(AdminScriptTestCase): "Tests for the various types of base command types that can be defined." def setUp(self): super().setUp() self.write_settings('settings.py') def test_version(self): "version is handled as a special case" args = ['version'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, get_version()) def test_version_alternative(self): "--version is equivalent to version" args1, args2 = ['version'], ['--version'] # It's possible one outputs on stderr and the other on stdout, hence the set self.assertEqual(set(self.run_manage(args1)), set(self.run_manage(args2))) def test_help(self): "help is handled as a special case" args = ['help'] out, err = self.run_manage(args) self.assertOutput(out, "Type 'manage.py help <subcommand>' for help on a specific subcommand.") self.assertOutput(out, '[django]') self.assertOutput(out, 'startapp') self.assertOutput(out, 'startproject') def test_help_commands(self): "help --commands shows the list of all available commands" args = ['help', '--commands'] out, err = self.run_manage(args) self.assertNotInOutput(out, 'usage:') self.assertNotInOutput(out, 'Options:') self.assertNotInOutput(out, '[django]') self.assertOutput(out, 'startapp') self.assertOutput(out, 'startproject') self.assertNotInOutput(out, '\n\n') def test_help_alternative(self): "--help is equivalent to help" args1, args2 = ['help'], ['--help'] self.assertEqual(self.run_manage(args1), self.run_manage(args2)) def test_help_short_altert(self): "-h is handled as a short form of --help" args1, args2 = ['--help'], ['-h'] self.assertEqual(self.run_manage(args1), self.run_manage(args2)) def test_specific_help(self): "--help can be used on a specific command" args = ['check', '--help'] out, err = self.run_manage(args) self.assertNoOutput(err) # Command-specific options like --tag appear before options common to # all commands like --version. tag_location = out.find('--tag') version_location = out.find('--version') self.assertNotEqual(tag_location, -1) self.assertNotEqual(version_location, -1) self.assertLess(tag_location, version_location) self.assertOutput(out, "Checks the entire Django project for potential problems.") def test_color_style(self): style = color.no_style() self.assertEqual(style.ERROR('Hello, world!'), 'Hello, world!') style = color.make_style('nocolor') self.assertEqual(style.ERROR('Hello, world!'), 'Hello, world!') style = color.make_style('dark') self.assertIn('Hello, world!', style.ERROR('Hello, world!')) self.assertNotEqual(style.ERROR('Hello, world!'), 'Hello, world!') # Default palette has color. style = color.make_style('') self.assertIn('Hello, world!', style.ERROR('Hello, world!')) self.assertNotEqual(style.ERROR('Hello, world!'), 'Hello, world!') def test_command_color(self): out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err) call_command(command) if color.supports_color(): self.assertIn('Hello, world!\n', out.getvalue()) self.assertIn('Hello, world!\n', err.getvalue()) self.assertNotEqual(out.getvalue(), 'Hello, world!\n') self.assertNotEqual(err.getvalue(), 'Hello, world!\n') else: self.assertEqual(out.getvalue(), 'Hello, world!\n') self.assertEqual(err.getvalue(), 'Hello, world!\n') def test_command_no_color(self): "--no-color prevent colorization of the output" out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err, no_color=True) call_command(command) self.assertEqual(out.getvalue(), 'Hello, world!\n') self.assertEqual(err.getvalue(), 'Hello, world!\n') out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err) call_command(command, no_color=True) self.assertEqual(out.getvalue(), 'Hello, world!\n') self.assertEqual(err.getvalue(), 'Hello, world!\n') def test_force_color_execute(self): out = StringIO() err = StringIO() with mock.patch.object(sys.stdout, 'isatty', lambda: False): command = ColorCommand(stdout=out, stderr=err) call_command(command, force_color=True) self.assertEqual(out.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') self.assertEqual(err.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') def test_force_color_command_init(self): out = StringIO() err = StringIO() with mock.patch.object(sys.stdout, 'isatty', lambda: False): command = ColorCommand(stdout=out, stderr=err, force_color=True) call_command(command) self.assertEqual(out.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') self.assertEqual(err.getvalue(), '\x1b[31;1mHello, world!\n\x1b[0m') def test_no_color_force_color_mutually_exclusive_execute(self): msg = "The --no-color and --force-color options can't be used together." with self.assertRaisesMessage(CommandError, msg): call_command(BaseCommand(), no_color=True, force_color=True) def test_no_color_force_color_mutually_exclusive_command_init(self): msg = "'no_color' and 'force_color' can't be used together." with self.assertRaisesMessage(CommandError, msg): call_command(BaseCommand(no_color=True, force_color=True)) def test_custom_stdout(self): class Command(BaseCommand): requires_system_checks = False def handle(self, *args, **options): self.stdout.write("Hello, World!") out = StringIO() command = Command(stdout=out) call_command(command) self.assertEqual(out.getvalue(), "Hello, World!\n") out.truncate(0) new_out = StringIO() call_command(command, stdout=new_out) self.assertEqual(out.getvalue(), "") self.assertEqual(new_out.getvalue(), "Hello, World!\n") def test_custom_stderr(self): class Command(BaseCommand): requires_system_checks = False def handle(self, *args, **options): self.stderr.write("Hello, World!") err = StringIO() command = Command(stderr=err) call_command(command) self.assertEqual(err.getvalue(), "Hello, World!\n") err.truncate(0) new_err = StringIO() call_command(command, stderr=new_err) self.assertEqual(err.getvalue(), "") self.assertEqual(new_err.getvalue(), "Hello, World!\n") def test_base_command(self): "User BaseCommands can execute when a label is provided" args = ['base_command', 'testlabel'] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels) def test_base_command_no_label(self): "User BaseCommands can execute when no labels are provided" args = ['base_command'] expected_labels = "()" self._test_base_command(args, expected_labels) def test_base_command_multiple_label(self): "User BaseCommands can execute when no labels are provided" args = ['base_command', 'testlabel', 'anotherlabel'] expected_labels = "('testlabel', 'anotherlabel')" self._test_base_command(args, expected_labels) def test_base_command_with_option(self): "User BaseCommands can execute with options when a label is provided" args = ['base_command', 'testlabel', '--option_a=x'] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels, option_a="'x'") def test_base_command_with_options(self): "User BaseCommands can execute with multiple options when a label is provided" args = ['base_command', 'testlabel', '-a', 'x', '--option_b=y'] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels, option_a="'x'", option_b="'y'") def test_base_command_with_wrong_option(self): "User BaseCommands outputs command usage when wrong option is specified" args = ['base_command', '--invalid'] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "usage: manage.py base_command") self.assertOutput(err, "error: unrecognized arguments: --invalid") def _test_base_command(self, args, labels, option_a="'1'", option_b="'2'"): out, err = self.run_manage(args) expected_out = ( "EXECUTE:BaseCommand labels=%s, " "options=[('force_color', False), ('no_color', False), " "('option_a', %s), ('option_b', %s), ('option_c', '3'), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]") % (labels, option_a, option_b) self.assertNoOutput(err) self.assertOutput(out, expected_out) def test_base_run_from_argv(self): """ Test run_from_argv properly terminates even with custom execute() (#19665) Also test proper traceback display. """ err = StringIO() command = BaseCommand(stderr=err) def raise_command_error(*args, **kwargs): raise CommandError("Custom error") command.execute = lambda args: args # This will trigger TypeError # If the Exception is not CommandError it should always # raise the original exception. with self.assertRaises(TypeError): command.run_from_argv(['', '']) # If the Exception is CommandError and --traceback is not present # this command should raise a SystemExit and don't print any # traceback to the stderr. command.execute = raise_command_error err.truncate(0) with self.assertRaises(SystemExit): command.run_from_argv(['', '']) err_message = err.getvalue() self.assertNotIn("Traceback", err_message) self.assertIn("CommandError", err_message) # If the Exception is CommandError and --traceback is present # this command should raise the original CommandError as if it # were not a CommandError. err.truncate(0) with self.assertRaises(CommandError): command.run_from_argv(['', '', '--traceback']) def test_run_from_argv_non_ascii_error(self): """ Non-ASCII message of CommandError does not raise any UnicodeDecodeError in run_from_argv. """ def raise_command_error(*args, **kwargs): raise CommandError("Erreur personnalisée") command = BaseCommand(stderr=StringIO()) command.execute = raise_command_error with self.assertRaises(SystemExit): command.run_from_argv(['', '']) def test_run_from_argv_closes_connections(self): """ A command called from the command line should close connections after being executed (#21255). """ command = BaseCommand(stderr=StringIO()) command.check = lambda: [] command.handle = lambda *args, **kwargs: args with mock.patch('django.core.management.base.connections') as mock_connections: command.run_from_argv(['', '']) # Test connections have been closed self.assertTrue(mock_connections.close_all.called) def test_noargs(self): "NoArg Commands can be executed" args = ['noargs_command'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', None), " "('traceback', False), ('verbosity', 1)]" ) def test_noargs_with_args(self): "NoArg Commands raise an error if an argument is provided" args = ['noargs_command', 'argument'] out, err = self.run_manage(args) self.assertOutput(err, "error: unrecognized arguments: argument") def test_app_command(self): "User AppCommands can execute when a single app name is provided" args = ['app_command', 'auth'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]" ) def test_app_command_no_apps(self): "User AppCommands raise an error when no app name is provided" args = ['app_command'] out, err = self.run_manage(args) self.assertOutput(err, 'error: Enter at least one application label.') def test_app_command_multiple_apps(self): "User AppCommands raise an error when multiple app names are provided" args = ['app_command', 'auth', 'contenttypes'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]" ) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.contenttypes, options=") self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]" ) def test_app_command_invalid_app_label(self): "User AppCommands can execute when a single app name is provided" args = ['app_command', 'NOT_AN_APP'] out, err = self.run_manage(args) self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.") def test_app_command_some_invalid_app_labels(self): "User AppCommands can execute when some of the provided app names are invalid" args = ['app_command', 'auth', 'NOT_AN_APP'] out, err = self.run_manage(args) self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.") def test_label_command(self): "User LabelCommands can execute when a label is provided" args = ['label_command', 'testlabel'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:LabelCommand label=testlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), ('settings', " "None), ('traceback', False), ('verbosity', 1)]" ) def test_label_command_no_label(self): "User LabelCommands raise an error if no label is provided" args = ['label_command'] out, err = self.run_manage(args) self.assertOutput(err, 'Enter at least one label') def test_label_command_multiple_label(self): "User LabelCommands are executed multiple times if multiple labels are provided" args = ['label_command', 'testlabel', 'anotherlabel'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:LabelCommand label=testlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), " "('settings', None), ('traceback', False), ('verbosity', 1)]" ) self.assertOutput( out, "EXECUTE:LabelCommand label=anotherlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), " "('settings', None), ('traceback', False), ('verbosity', 1)]" ) class Discovery(SimpleTestCase): def test_precedence(self): """ Apps listed first in INSTALLED_APPS have precedence. """ with self.settings(INSTALLED_APPS=['admin_scripts.complex_app', 'admin_scripts.simple_app', 'django.contrib.auth', 'django.contrib.contenttypes']): out = StringIO() call_command('duplicate', stdout=out) self.assertEqual(out.getvalue().strip(), 'complex_app') with self.settings(INSTALLED_APPS=['admin_scripts.simple_app', 'admin_scripts.complex_app', 'django.contrib.auth', 'django.contrib.contenttypes']): out = StringIO() call_command('duplicate', stdout=out) self.assertEqual(out.getvalue().strip(), 'simple_app') class ArgumentOrder(AdminScriptTestCase): """Tests for 2-stage argument parsing scheme. django-admin command arguments are parsed in 2 parts; the core arguments (--settings, --traceback and --pythonpath) are parsed using a basic parser, ignoring any unknown options. Then the full settings are passed to the command parser, which extracts commands of interest to the individual command. """ def setUp(self): super().setUp() self.write_settings('settings.py', apps=['django.contrib.auth', 'django.contrib.contenttypes']) self.write_settings('alternate_settings.py') def test_setting_then_option(self): """ Options passed after settings are correctly handled. """ args = ['base_command', 'testlabel', '--settings=alternate_settings', '--option_a=x'] self._test(args) def test_setting_then_short_option(self): """ Short options passed after settings are correctly handled. """ args = ['base_command', 'testlabel', '--settings=alternate_settings', '-a', 'x'] self._test(args) def test_option_then_setting(self): """ Options passed before settings are correctly handled. """ args = ['base_command', 'testlabel', '--option_a=x', '--settings=alternate_settings'] self._test(args) def test_short_option_then_setting(self): """ Short options passed before settings are correctly handled. """ args = ['base_command', 'testlabel', '-a', 'x', '--settings=alternate_settings'] self._test(args) def test_option_then_setting_then_option(self): """ Options are correctly handled when they are passed before and after a setting. """ args = ['base_command', 'testlabel', '--option_a=x', '--settings=alternate_settings', '--option_b=y'] self._test(args, option_b="'y'") def _test(self, args, option_b="'2'"): out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:BaseCommand labels=('testlabel',), options=[" "('force_color', False), ('no_color', False), ('option_a', 'x'), " "('option_b', %s), ('option_c', '3'), ('pythonpath', None), " "('settings', 'alternate_settings'), ('traceback', False), " "('verbosity', 1)]" % option_b ) @override_settings(ROOT_URLCONF='admin_scripts.urls') class StartProject(LiveServerTestCase, AdminScriptTestCase): available_apps = [ 'admin_scripts', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', ] def test_wrong_args(self): "Make sure passing the wrong kinds of arguments outputs an error and prints usage" out, err = self.run_django_admin(['startproject']) self.assertNoOutput(out) self.assertOutput(err, "usage:") self.assertOutput(err, "You must provide a project name.") def test_simple_project(self): "Make sure the startproject management command creates a project" args = ['startproject', 'testproject'] testproject_dir = os.path.join(self.test_dir, 'testproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) # running again.. out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "already exists") def test_invalid_project_name(self): "Make sure the startproject management command validates a project name" for bad_name in ('7testproject', '../testproject'): with self.subTest(project_name=bad_name): args = ['startproject', bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "Error: '%s' is not a valid project name. Please make " "sure the name is a valid identifier." % bad_name ) self.assertFalse(os.path.exists(testproject_dir)) def test_importable_project_name(self): """ startproject validates that project name doesn't clash with existing Python modules. """ bad_name = 'os' args = ['startproject', bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing " "Python module and cannot be used as a project name. Please try " "another name." ) self.assertFalse(os.path.exists(testproject_dir)) def test_simple_project_different_directory(self): "Make sure the startproject management command creates a project in a specific directory" args = ['startproject', 'testproject', 'othertestproject'] testproject_dir = os.path.join(self.test_dir, 'othertestproject') os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'manage.py'))) # running again.. out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput( err, "already exists. Overlaying a project into an existing directory " "won't replace conflicting files." ) def test_custom_project_template(self): "Make sure the startproject management command is able to use a different project template" template_path = os.path.join(custom_templates_dir, 'project_template') args = ['startproject', '--template', template_path, 'customtestproject'] testproject_dir = os.path.join(self.test_dir, 'customtestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir'))) def test_template_dir_with_trailing_slash(self): "Ticket 17475: Template dir passed has a trailing path separator" template_path = os.path.join(custom_templates_dir, 'project_template' + os.sep) args = ['startproject', '--template', template_path, 'customtestproject'] testproject_dir = os.path.join(self.test_dir, 'customtestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir'))) def test_custom_project_template_from_tarball_by_path(self): "Make sure the startproject management command is able to use a different project template from a tarball" template_path = os.path.join(custom_templates_dir, 'project_template.tgz') args = ['startproject', '--template', template_path, 'tarballtestproject'] testproject_dir = os.path.join(self.test_dir, 'tarballtestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) def test_custom_project_template_from_tarball_to_alternative_location(self): "Startproject can use a project template from a tarball and create it in a specified location" template_path = os.path.join(custom_templates_dir, 'project_template.tgz') args = ['startproject', '--template', template_path, 'tarballtestproject', 'altlocation'] testproject_dir = os.path.join(self.test_dir, 'altlocation') os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) def test_custom_project_template_from_tarball_by_url(self): """ The startproject management command is able to use a different project template from a tarball via a URL. """ template_url = '%s/custom_templates/project_template.tgz' % self.live_server_url args = ['startproject', '--template', template_url, 'urltestproject'] testproject_dir = os.path.join(self.test_dir, 'urltestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) def test_project_template_tarball_url(self): "Startproject management command handles project template tar/zip balls from non-canonical urls" template_url = '%s/custom_templates/project_template.tgz/' % self.live_server_url args = ['startproject', '--template', template_url, 'urltestproject'] testproject_dir = os.path.join(self.test_dir, 'urltestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'run.py'))) def test_file_without_extension(self): "Make sure the startproject management command is able to render custom files" template_path = os.path.join(custom_templates_dir, 'project_template') args = ['startproject', '--template', template_path, 'customtestproject', '-e', 'txt', '-n', 'Procfile'] testproject_dir = os.path.join(self.test_dir, 'customtestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, 'additional_dir'))) base_path = os.path.join(testproject_dir, 'additional_dir') for f in ('Procfile', 'additional_file.py', 'requirements.txt'): self.assertTrue(os.path.exists(os.path.join(base_path, f))) with open(os.path.join(base_path, f)) as fh: self.assertEqual(fh.read().strip(), '# some file for customtestproject test project') def test_custom_project_template_context_variables(self): "Make sure template context variables are rendered with proper values" template_path = os.path.join(custom_templates_dir, 'project_template') args = ['startproject', '--template', template_path, 'another_project', 'project_dir'] testproject_dir = os.path.join(self.test_dir, 'project_dir') os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) test_manage_py = os.path.join(testproject_dir, 'manage.py') with open(test_manage_py) as fp: content = fp.read() self.assertIn("project_name = 'another_project'", content) self.assertIn("project_directory = '%s'" % testproject_dir, content) def test_no_escaping_of_project_variables(self): "Make sure template context variables are not html escaped" # We're using a custom command so we need the alternate settings self.write_settings('alternate_settings.py') template_path = os.path.join(custom_templates_dir, 'project_template') args = [ 'custom_startproject', '--template', template_path, 'another_project', 'project_dir', '--extra', '<&>', '--settings=alternate_settings', ] testproject_dir = os.path.join(self.test_dir, 'project_dir') os.mkdir(testproject_dir) out, err = self.run_manage(args) self.assertNoOutput(err) test_manage_py = os.path.join(testproject_dir, 'additional_dir', 'extra.py') with open(test_manage_py) as fp: content = fp.read() self.assertIn("<&>", content) def test_custom_project_destination_missing(self): """ Make sure an exception is raised when the provided destination directory doesn't exist """ template_path = os.path.join(custom_templates_dir, 'project_template') args = ['startproject', '--template', template_path, 'yet_another_project', 'project_dir2'] testproject_dir = os.path.join(self.test_dir, 'project_dir2') out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Destination directory '%s' does not exist, please create it first." % testproject_dir) self.assertFalse(os.path.exists(testproject_dir)) def test_custom_project_template_with_non_ascii_templates(self): """ The startproject management command is able to render templates with non-ASCII content. """ template_path = os.path.join(custom_templates_dir, 'project_template') args = ['startproject', '--template', template_path, '--extension=txt', 'customtestproject'] testproject_dir = os.path.join(self.test_dir, 'customtestproject') out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) path = os.path.join(testproject_dir, 'ticket-18091-non-ascii-template.txt') with open(path, encoding='utf-8') as f: self.assertEqual(f.read().splitlines(False), [ 'Some non-ASCII text for testing ticket #18091:', 'üäö €']) class StartApp(AdminScriptTestCase): def test_invalid_name(self): """startapp validates that app name is a valid Python identifier.""" for bad_name in ('7testproject', '../testproject'): with self.subTest(app_name=bad_name): args = ['startapp', bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: '{}' is not a valid app name. Please make " "sure the name is a valid identifier.".format(bad_name) ) self.assertFalse(os.path.exists(testproject_dir)) def test_importable_name(self): """ startapp validates that app name doesn't clash with existing Python modules. """ bad_name = 'os' args = ['startapp', bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing " "Python module and cannot be used as an app name. Please try " "another name." ) self.assertFalse(os.path.exists(testproject_dir)) def test_invalid_target_name(self): for bad_target in ('invalid.dir_name', '7invalid_dir_name', '.invalid_dir_name'): with self.subTest(bad_target): _, err = self.run_django_admin(['startapp', 'app', bad_target]) self.assertOutput( err, "CommandError: '%s' is not a valid app directory. Please " "make sure the directory is a valid identifier." % bad_target ) def test_importable_target_name(self): _, err = self.run_django_admin(['startapp', 'app', 'os']) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing Python " "module and cannot be used as an app directory. Please try " "another directory." ) def test_overlaying_app(self): self.run_django_admin(['startapp', 'app1']) out, err = self.run_django_admin(['startapp', 'app2', 'app1']) self.assertOutput( err, "already exists. Overlaying an app into an existing directory " "won't replace conflicting files." ) class DiffSettings(AdminScriptTestCase): """Tests for diffsettings management command.""" def test_basic(self): """Runs without error and emits settings diff.""" self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'}) args = ['diffsettings', '--settings=settings_to_diff'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "FOO = 'bar' ###") # Attributes from django.conf.Settings don't appear. self.assertNotInOutput(out, 'is_overridden = ') def test_settings_configured(self): out, err = self.run_manage(['diffsettings'], manage_py='configured_settings_manage.py') self.assertNoOutput(err) self.assertOutput(out, 'CUSTOM = 1 ###\nDEBUG = True') # Attributes from django.conf.UserSettingsHolder don't appear. self.assertNotInOutput(out, 'default_settings = ') def test_dynamic_settings_configured(self): # Custom default settings appear. out, err = self.run_manage(['diffsettings'], manage_py='configured_dynamic_settings_manage.py') self.assertNoOutput(err) self.assertOutput(out, "FOO = 'bar' ###") def test_all(self): """The all option also shows settings with the default value.""" self.write_settings('settings_to_diff.py', sdict={'STATIC_URL': 'None'}) args = ['diffsettings', '--settings=settings_to_diff', '--all'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "### STATIC_URL = None") def test_custom_default(self): """ The --default option specifies an alternate settings module for comparison. """ self.write_settings('settings_default.py', sdict={'FOO': '"foo"', 'BAR': '"bar1"'}) self.write_settings('settings_to_diff.py', sdict={'FOO': '"foo"', 'BAR': '"bar2"'}) out, err = self.run_manage(['diffsettings', '--settings=settings_to_diff', '--default=settings_default']) self.assertNoOutput(err) self.assertNotInOutput(out, "FOO") self.assertOutput(out, "BAR = 'bar2'") def test_unified(self): """--output=unified emits settings diff in unified mode.""" self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'}) args = ['diffsettings', '--settings=settings_to_diff', '--output=unified'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "+ FOO = 'bar'") self.assertOutput(out, "- SECRET_KEY = ''") self.assertOutput(out, "+ SECRET_KEY = 'django_tests_secret_key'") self.assertNotInOutput(out, " APPEND_SLASH = True") def test_unified_all(self): """ --output=unified --all emits settings diff in unified mode and includes settings with the default value. """ self.write_settings('settings_to_diff.py', sdict={'FOO': '"bar"'}) args = ['diffsettings', '--settings=settings_to_diff', '--output=unified', '--all'] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, " APPEND_SLASH = True") self.assertOutput(out, "+ FOO = 'bar'") self.assertOutput(out, "- SECRET_KEY = ''") class Dumpdata(AdminScriptTestCase): """Tests for dumpdata management command.""" def setUp(self): super().setUp() self.write_settings('settings.py') def test_pks_parsing(self): """Regression for #20509 Test would raise an exception rather than printing an error message. """ args = ['dumpdata', '--pks=1'] out, err = self.run_manage(args) self.assertOutput(err, "You can only use --pks option with one model") self.assertNoOutput(out) class MainModule(AdminScriptTestCase): """python -m django works like django-admin.""" def test_runs_django_admin(self): cmd_out, _ = self.run_django_admin(['--version']) mod_out, _ = self.run_test('-m', ['django', '--version']) self.assertEqual(mod_out, cmd_out) def test_program_name_in_help(self): out, err = self.run_test('-m', ['django', 'help']) self.assertOutput(out, "Type 'python -m django help <subcommand>' for help on a specific subcommand.") class DjangoAdminSuggestions(AdminScriptTestCase): def setUp(self): super().setUp() self.write_settings('settings.py') def test_suggestions(self): args = ['rnserver', '--settings=test_project.settings'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'rnserver'. Did you mean runserver?") def test_no_suggestions(self): args = ['abcdef', '--settings=test_project.settings'] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertNotInOutput(err, 'Did you mean')
ecf695ac54255693a5f0e0f88603a1aa82e9f8cfb507c7cc1a1e550602a4515b
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if __name__ == '__main__': settings.configure(DEBUG=True, CUSTOM=1) execute_from_command_line(sys.argv)
98c9e04667f47210cfff4800175bf7e3084fa5ceb043496888180f93f25c735f
import os from django.urls import path from django.views.static import serve here = os.path.dirname(__file__) urlpatterns = [ path('custom_templates/<path:path>', serve, { 'document_root': os.path.join(here, 'custom_templates')}), ]
c0741a5917d319f845dd9af4b6582592d16fcb7c105420acf310c34410fbe326
#!/usr/bin/env python import sys from django.conf import global_settings, settings from django.core.management import execute_from_command_line class Settings: def __getattr__(self, name): if name == 'FOO': return 'bar' return getattr(global_settings, name) def __dir__(self): return super().__dir__() + dir(global_settings) + ['FOO'] if __name__ == '__main__': settings.configure(Settings()) execute_from_command_line(sys.argv)
c86f082bf6f08b249752a0964c7b0702e395aec2c478d708260663696928da57
from django.conf import settings from django.contrib.redirects.middleware import RedirectFallbackMiddleware from django.contrib.redirects.models import Redirect from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponseForbidden, HttpResponseRedirect from django.test import TestCase, modify_settings, override_settings @modify_settings(MIDDLEWARE={'append': 'django.contrib.redirects.middleware.RedirectFallbackMiddleware'}) @override_settings(APPEND_SLASH=False, ROOT_URLCONF='redirects_tests.urls', SITE_ID=1) class RedirectTests(TestCase): @classmethod def setUpTestData(cls): cls.site = Site.objects.get(pk=settings.SITE_ID) def test_model(self): r1 = Redirect.objects.create(site=self.site, old_path='/initial', new_path='/new_target') self.assertEqual(str(r1), "/initial ---> /new_target") def test_redirect(self): Redirect.objects.create(site=self.site, old_path='/initial', new_path='/new_target') response = self.client.get('/initial') self.assertRedirects(response, '/new_target', status_code=301, target_status_code=404) @override_settings(APPEND_SLASH=True) def test_redirect_with_append_slash(self): Redirect.objects.create(site=self.site, old_path='/initial/', new_path='/new_target/') response = self.client.get('/initial') self.assertRedirects(response, '/new_target/', status_code=301, target_status_code=404) @override_settings(APPEND_SLASH=True) def test_redirect_with_append_slash_and_query_string(self): Redirect.objects.create(site=self.site, old_path='/initial/?foo', new_path='/new_target/') response = self.client.get('/initial?foo') self.assertRedirects(response, '/new_target/', status_code=301, target_status_code=404) @override_settings(APPEND_SLASH=True) def test_redirect_not_found_with_append_slash(self): """ Exercise the second Redirect.DoesNotExist branch in RedirectFallbackMiddleware. """ response = self.client.get('/test') self.assertEqual(response.status_code, 404) def test_redirect_shortcircuits_non_404_response(self): """RedirectFallbackMiddleware short-circuits on non-404 requests.""" response = self.client.get('/') self.assertEqual(response.status_code, 200) def test_response_gone(self): """When the redirect target is '', return a 410""" Redirect.objects.create(site=self.site, old_path='/initial', new_path='') response = self.client.get('/initial') self.assertEqual(response.status_code, 410) @modify_settings(INSTALLED_APPS={'remove': 'django.contrib.sites'}) def test_sites_not_installed(self): msg = ( 'You cannot use RedirectFallbackMiddleware when ' 'django.contrib.sites is not installed.' ) with self.assertRaisesMessage(ImproperlyConfigured, msg): RedirectFallbackMiddleware() class OverriddenRedirectFallbackMiddleware(RedirectFallbackMiddleware): # Use HTTP responses different from the defaults response_gone_class = HttpResponseForbidden response_redirect_class = HttpResponseRedirect @modify_settings(MIDDLEWARE={'append': 'redirects_tests.tests.OverriddenRedirectFallbackMiddleware'}) @override_settings(SITE_ID=1) class OverriddenRedirectMiddlewareTests(TestCase): @classmethod def setUpTestData(cls): cls.site = Site.objects.get(pk=settings.SITE_ID) def test_response_gone_class(self): Redirect.objects.create(site=self.site, old_path='/initial/', new_path='') response = self.client.get('/initial/') self.assertEqual(response.status_code, 403) def test_response_redirect_class(self): Redirect.objects.create(site=self.site, old_path='/initial/', new_path='/new_target/') response = self.client.get('/initial/') self.assertEqual(response.status_code, 302)
e2b25f2854bba4c55d5d3d7421fe632e35a03b9500c5cb579a8886c6d94c90cc
from django.http import HttpResponse from django.urls import path urlpatterns = [ path('', lambda req: HttpResponse('OK')), ]
0df1c5a5758041588ca179cd1d5c13abe65700afd0107f765a6dd427c11c4765
from operator import attrgetter from django.db import IntegrityError, NotSupportedError, connection from django.db.models import FileField, Value from django.db.models.functions import Lower from django.test import ( TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from .models import ( Country, NoFields, NullableFields, Pizzeria, ProxyCountry, ProxyMultiCountry, ProxyMultiProxyCountry, ProxyProxyCountry, Restaurant, State, TwoFields, ) class BulkCreateTests(TestCase): def setUp(self): self.data = [ Country(name="United States of America", iso_two_letter="US"), Country(name="The Netherlands", iso_two_letter="NL"), Country(name="Germany", iso_two_letter="DE"), Country(name="Czech Republic", iso_two_letter="CZ") ] def test_simple(self): created = Country.objects.bulk_create(self.data) self.assertEqual(len(created), 4) self.assertQuerysetEqual(Country.objects.order_by("-name"), [ "United States of America", "The Netherlands", "Germany", "Czech Republic" ], attrgetter("name")) created = Country.objects.bulk_create([]) self.assertEqual(created, []) self.assertEqual(Country.objects.count(), 4) @skipUnlessDBFeature('has_bulk_insert') def test_efficiency(self): with self.assertNumQueries(1): Country.objects.bulk_create(self.data) @skipUnlessDBFeature('has_bulk_insert') def test_long_non_ascii_text(self): """ Inserting non-ASCII values with a length in the range 2001 to 4000 characters, i.e. 4002 to 8000 bytes, must be set as a CLOB on Oracle (#22144). """ Country.objects.bulk_create([Country(description='Ж' * 3000)]) self.assertEqual(Country.objects.count(), 1) def test_multi_table_inheritance_unsupported(self): expected_message = "Can't bulk create a multi-table inherited model" with self.assertRaisesMessage(ValueError, expected_message): Pizzeria.objects.bulk_create([ Pizzeria(name="The Art of Pizza"), ]) with self.assertRaisesMessage(ValueError, expected_message): ProxyMultiCountry.objects.bulk_create([ ProxyMultiCountry(name="Fillory", iso_two_letter="FL"), ]) with self.assertRaisesMessage(ValueError, expected_message): ProxyMultiProxyCountry.objects.bulk_create([ ProxyMultiProxyCountry(name="Fillory", iso_two_letter="FL"), ]) def test_proxy_inheritance_supported(self): ProxyCountry.objects.bulk_create([ ProxyCountry(name="Qwghlm", iso_two_letter="QW"), Country(name="Tortall", iso_two_letter="TA"), ]) self.assertQuerysetEqual(ProxyCountry.objects.all(), { "Qwghlm", "Tortall" }, attrgetter("name"), ordered=False) ProxyProxyCountry.objects.bulk_create([ ProxyProxyCountry(name="Netherlands", iso_two_letter="NT"), ]) self.assertQuerysetEqual(ProxyProxyCountry.objects.all(), { "Qwghlm", "Tortall", "Netherlands", }, attrgetter("name"), ordered=False) def test_non_auto_increment_pk(self): State.objects.bulk_create([ State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"] ]) self.assertQuerysetEqual(State.objects.order_by("two_letter_code"), [ "CA", "IL", "ME", "NY", ], attrgetter("two_letter_code")) @skipUnlessDBFeature('has_bulk_insert') def test_non_auto_increment_pk_efficiency(self): with self.assertNumQueries(1): State.objects.bulk_create([ State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"] ]) self.assertQuerysetEqual(State.objects.order_by("two_letter_code"), [ "CA", "IL", "ME", "NY", ], attrgetter("two_letter_code")) @skipIfDBFeature('allows_auto_pk_0') def test_zero_as_autoval(self): """ Zero as id for AutoField should raise exception in MySQL, because MySQL does not allow zero for automatic primary key. """ valid_country = Country(name='Germany', iso_two_letter='DE') invalid_country = Country(id=0, name='Poland', iso_two_letter='PL') msg = 'The database backend does not accept 0 as a value for AutoField.' with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create([valid_country, invalid_country]) def test_batch_same_vals(self): # SQLite had a problem where all the same-valued models were # collapsed to one insert. Restaurant.objects.bulk_create([ Restaurant(name='foo') for i in range(0, 2) ]) self.assertEqual(Restaurant.objects.count(), 2) def test_large_batch(self): TwoFields.objects.bulk_create([ TwoFields(f1=i, f2=i + 1) for i in range(0, 1001) ]) self.assertEqual(TwoFields.objects.count(), 1001) self.assertEqual( TwoFields.objects.filter(f1__gte=450, f1__lte=550).count(), 101) self.assertEqual(TwoFields.objects.filter(f2__gte=901).count(), 101) @skipUnlessDBFeature('has_bulk_insert') def test_large_single_field_batch(self): # SQLite had a problem with more than 500 UNIONed selects in single # query. Restaurant.objects.bulk_create([ Restaurant() for i in range(0, 501) ]) @skipUnlessDBFeature('has_bulk_insert') def test_large_batch_efficiency(self): with override_settings(DEBUG=True): connection.queries_log.clear() TwoFields.objects.bulk_create([ TwoFields(f1=i, f2=i + 1) for i in range(0, 1001) ]) self.assertLess(len(connection.queries), 10) def test_large_batch_mixed(self): """ Test inserting a large batch with objects having primary key set mixed together with objects without PK set. """ TwoFields.objects.bulk_create([ TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1) for i in range(100000, 101000) ]) self.assertEqual(TwoFields.objects.count(), 1000) # We can't assume much about the ID's created, except that the above # created IDs must exist. id_range = range(100000, 101000, 2) self.assertEqual(TwoFields.objects.filter(id__in=id_range).count(), 500) self.assertEqual(TwoFields.objects.exclude(id__in=id_range).count(), 500) @skipUnlessDBFeature('has_bulk_insert') def test_large_batch_mixed_efficiency(self): """ Test inserting a large batch with objects having primary key set mixed together with objects without PK set. """ with override_settings(DEBUG=True): connection.queries_log.clear() TwoFields.objects.bulk_create([ TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1) for i in range(100000, 101000)]) self.assertLess(len(connection.queries), 10) def test_explicit_batch_size(self): objs = [TwoFields(f1=i, f2=i) for i in range(0, 4)] num_objs = len(objs) TwoFields.objects.bulk_create(objs, batch_size=1) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=2) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=3) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=num_objs) self.assertEqual(TwoFields.objects.count(), num_objs) def test_empty_model(self): NoFields.objects.bulk_create([NoFields() for i in range(2)]) self.assertEqual(NoFields.objects.count(), 2) @skipUnlessDBFeature('has_bulk_insert') def test_explicit_batch_size_efficiency(self): objs = [TwoFields(f1=i, f2=i) for i in range(0, 100)] with self.assertNumQueries(2): TwoFields.objects.bulk_create(objs, 50) TwoFields.objects.all().delete() with self.assertNumQueries(1): TwoFields.objects.bulk_create(objs, len(objs)) @skipUnlessDBFeature('has_bulk_insert') def test_bulk_insert_expressions(self): Restaurant.objects.bulk_create([ Restaurant(name="Sam's Shake Shack"), Restaurant(name=Lower(Value("Betty's Beetroot Bar"))) ]) bbb = Restaurant.objects.filter(name="betty's beetroot bar") self.assertEqual(bbb.count(), 1) @skipUnlessDBFeature('has_bulk_insert') def test_bulk_insert_nullable_fields(self): # NULL can be mixed with other values in nullable fields nullable_fields = [field for field in NullableFields._meta.get_fields() if field.name != 'id'] NullableFields.objects.bulk_create([ NullableFields(**{field.name: None}) for field in nullable_fields ]) self.assertEqual(NullableFields.objects.count(), len(nullable_fields)) for field in nullable_fields: with self.subTest(field=field): field_value = '' if isinstance(field, FileField) else None self.assertEqual(NullableFields.objects.filter(**{field.name: field_value}).count(), 1) @skipUnlessDBFeature('can_return_rows_from_bulk_insert') def test_set_pk_and_insert_single_item(self): with self.assertNumQueries(1): countries = Country.objects.bulk_create([self.data[0]]) self.assertEqual(len(countries), 1) self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0]) @skipUnlessDBFeature('can_return_rows_from_bulk_insert') def test_set_pk_and_query_efficiency(self): with self.assertNumQueries(1): countries = Country.objects.bulk_create(self.data) self.assertEqual(len(countries), 4) self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0]) self.assertEqual(Country.objects.get(pk=countries[1].pk), countries[1]) self.assertEqual(Country.objects.get(pk=countries[2].pk), countries[2]) self.assertEqual(Country.objects.get(pk=countries[3].pk), countries[3]) @skipUnlessDBFeature('can_return_rows_from_bulk_insert') def test_set_state(self): country_nl = Country(name='Netherlands', iso_two_letter='NL') country_be = Country(name='Belgium', iso_two_letter='BE') Country.objects.bulk_create([country_nl]) country_be.save() # Objects save via bulk_create() and save() should have equal state. self.assertEqual(country_nl._state.adding, country_be._state.adding) self.assertEqual(country_nl._state.db, country_be._state.db) def test_set_state_with_pk_specified(self): state_ca = State(two_letter_code='CA') state_ny = State(two_letter_code='NY') State.objects.bulk_create([state_ca]) state_ny.save() # Objects save via bulk_create() and save() should have equal state. self.assertEqual(state_ca._state.adding, state_ny._state.adding) self.assertEqual(state_ca._state.db, state_ny._state.db) @skipIfDBFeature('supports_ignore_conflicts') def test_ignore_conflicts_value_error(self): message = 'This database backend does not support ignoring conflicts.' with self.assertRaisesMessage(NotSupportedError, message): TwoFields.objects.bulk_create(self.data, ignore_conflicts=True) @skipUnlessDBFeature('supports_ignore_conflicts') def test_ignore_conflicts_ignore(self): data = [ TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2), TwoFields(f1=3, f2=3), ] TwoFields.objects.bulk_create(data) self.assertEqual(TwoFields.objects.count(), 3) # With ignore_conflicts=True, conflicts are ignored. conflicting_objects = [ TwoFields(f1=2, f2=2), TwoFields(f1=3, f2=3), ] TwoFields.objects.bulk_create([conflicting_objects[0]], ignore_conflicts=True) TwoFields.objects.bulk_create(conflicting_objects, ignore_conflicts=True) self.assertEqual(TwoFields.objects.count(), 3) self.assertIsNone(conflicting_objects[0].pk) self.assertIsNone(conflicting_objects[1].pk) # New objects are created and conflicts are ignored. new_object = TwoFields(f1=4, f2=4) TwoFields.objects.bulk_create(conflicting_objects + [new_object], ignore_conflicts=True) self.assertEqual(TwoFields.objects.count(), 4) self.assertIsNone(new_object.pk) # Without ignore_conflicts=True, there's a problem. with self.assertRaises(IntegrityError): TwoFields.objects.bulk_create(conflicting_objects)
9e111f01d9e0ef8fe15e2ed50a4c82be83f5ee28ca99db05d3cdf747a7cbec47
import datetime from unittest import mock, skipIf, skipUnless from django.core.exceptions import FieldError from django.db import NotSupportedError, connection from django.db.models import ( F, OuterRef, RowRange, Subquery, Value, ValueRange, Window, WindowFrame, ) from django.db.models.aggregates import Avg, Max, Min, Sum from django.db.models.functions import ( CumeDist, DenseRank, ExtractYear, FirstValue, Lag, LastValue, Lead, NthValue, Ntile, PercentRank, Rank, RowNumber, Upper, ) from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from .models import Employee @skipUnlessDBFeature('supports_over_clause') class WindowFunctionTests(TestCase): @classmethod def setUpTestData(cls): Employee.objects.bulk_create([ Employee(name=e[0], salary=e[1], department=e[2], hire_date=e[3], age=e[4]) for e in [ ('Jones', 45000, 'Accounting', datetime.datetime(2005, 11, 1), 20), ('Williams', 37000, 'Accounting', datetime.datetime(2009, 6, 1), 20), ('Jenson', 45000, 'Accounting', datetime.datetime(2008, 4, 1), 20), ('Adams', 50000, 'Accounting', datetime.datetime(2013, 7, 1), 50), ('Smith', 55000, 'Sales', datetime.datetime(2007, 6, 1), 30), ('Brown', 53000, 'Sales', datetime.datetime(2009, 9, 1), 30), ('Johnson', 40000, 'Marketing', datetime.datetime(2012, 3, 1), 30), ('Smith', 38000, 'Marketing', datetime.datetime(2009, 10, 1), 20), ('Wilkinson', 60000, 'IT', datetime.datetime(2011, 3, 1), 40), ('Moore', 34000, 'IT', datetime.datetime(2013, 8, 1), 40), ('Miller', 100000, 'Management', datetime.datetime(2005, 6, 1), 40), ('Johnson', 80000, 'Management', datetime.datetime(2005, 7, 1), 50), ] ]) def test_dense_rank(self): qs = Employee.objects.annotate(rank=Window( expression=DenseRank(), order_by=ExtractYear(F('hire_date')).asc(), )) self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 1), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 1), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 1), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 2), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 3), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 4), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 4), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 4), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 5), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 6), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 7), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 7), ], lambda entry: (entry.name, entry.salary, entry.department, entry.hire_date, entry.rank), ordered=False) def test_department_salary(self): qs = Employee.objects.annotate(department_sum=Window( expression=Sum('salary'), partition_by=F('department'), order_by=[F('hire_date').asc()], )).order_by('department', 'department_sum') self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', 45000, 45000), ('Jenson', 'Accounting', 45000, 90000), ('Williams', 'Accounting', 37000, 127000), ('Adams', 'Accounting', 50000, 177000), ('Wilkinson', 'IT', 60000, 60000), ('Moore', 'IT', 34000, 94000), ('Miller', 'Management', 100000, 100000), ('Johnson', 'Management', 80000, 180000), ('Smith', 'Marketing', 38000, 38000), ('Johnson', 'Marketing', 40000, 78000), ('Smith', 'Sales', 55000, 55000), ('Brown', 'Sales', 53000, 108000), ], lambda entry: (entry.name, entry.department, entry.salary, entry.department_sum)) def test_rank(self): """ Rank the employees based on the year they're were hired. Since there are multiple employees hired in different years, this will contain gaps. """ qs = Employee.objects.annotate(rank=Window( expression=Rank(), order_by=ExtractYear(F('hire_date')).asc(), )) self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 1), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 1), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 1), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 4), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 5), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 6), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 6), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 6), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 9), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 10), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 11), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 11), ], lambda entry: (entry.name, entry.salary, entry.department, entry.hire_date, entry.rank), ordered=False) def test_row_number(self): """ The row number window function computes the number based on the order in which the tuples were inserted. Depending on the backend, Oracle requires an ordering-clause in the Window expression. """ qs = Employee.objects.annotate(row_number=Window( expression=RowNumber(), order_by=F('pk').asc(), )).order_by('pk') self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', 1), ('Williams', 'Accounting', 2), ('Jenson', 'Accounting', 3), ('Adams', 'Accounting', 4), ('Smith', 'Sales', 5), ('Brown', 'Sales', 6), ('Johnson', 'Marketing', 7), ('Smith', 'Marketing', 8), ('Wilkinson', 'IT', 9), ('Moore', 'IT', 10), ('Miller', 'Management', 11), ('Johnson', 'Management', 12), ], lambda entry: (entry.name, entry.department, entry.row_number)) @skipIf(connection.vendor == 'oracle', "Oracle requires ORDER BY in row_number, ANSI:SQL doesn't") def test_row_number_no_ordering(self): """ The row number window function computes the number based on the order in which the tuples were inserted. """ # Add a default ordering for consistent results across databases. qs = Employee.objects.annotate(row_number=Window( expression=RowNumber(), )).order_by('pk') self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', 1), ('Williams', 'Accounting', 2), ('Jenson', 'Accounting', 3), ('Adams', 'Accounting', 4), ('Smith', 'Sales', 5), ('Brown', 'Sales', 6), ('Johnson', 'Marketing', 7), ('Smith', 'Marketing', 8), ('Wilkinson', 'IT', 9), ('Moore', 'IT', 10), ('Miller', 'Management', 11), ('Johnson', 'Management', 12), ], lambda entry: (entry.name, entry.department, entry.row_number)) def test_avg_salary_department(self): qs = Employee.objects.annotate(avg_salary=Window( expression=Avg('salary'), order_by=F('department').asc(), partition_by='department', )).order_by('department', '-salary', 'name') self.assertQuerysetEqual(qs, [ ('Adams', 50000, 'Accounting', 44250.00), ('Jenson', 45000, 'Accounting', 44250.00), ('Jones', 45000, 'Accounting', 44250.00), ('Williams', 37000, 'Accounting', 44250.00), ('Wilkinson', 60000, 'IT', 47000.00), ('Moore', 34000, 'IT', 47000.00), ('Miller', 100000, 'Management', 90000.00), ('Johnson', 80000, 'Management', 90000.00), ('Johnson', 40000, 'Marketing', 39000.00), ('Smith', 38000, 'Marketing', 39000.00), ('Smith', 55000, 'Sales', 54000.00), ('Brown', 53000, 'Sales', 54000.00), ], transform=lambda row: (row.name, row.salary, row.department, row.avg_salary)) def test_lag(self): """ Compute the difference between an employee's salary and the next highest salary in the employee's department. Return None if the employee has the lowest salary. """ qs = Employee.objects.annotate(lag=Window( expression=Lag(expression='salary', offset=1), partition_by=F('department'), order_by=[F('salary').asc(), F('name').asc()], )).order_by('department', F('salary').asc(), F('name').asc()) self.assertQuerysetEqual(qs, [ ('Williams', 37000, 'Accounting', None), ('Jenson', 45000, 'Accounting', 37000), ('Jones', 45000, 'Accounting', 45000), ('Adams', 50000, 'Accounting', 45000), ('Moore', 34000, 'IT', None), ('Wilkinson', 60000, 'IT', 34000), ('Johnson', 80000, 'Management', None), ('Miller', 100000, 'Management', 80000), ('Smith', 38000, 'Marketing', None), ('Johnson', 40000, 'Marketing', 38000), ('Brown', 53000, 'Sales', None), ('Smith', 55000, 'Sales', 53000), ], transform=lambda row: (row.name, row.salary, row.department, row.lag)) def test_first_value(self): qs = Employee.objects.annotate(first_value=Window( expression=FirstValue('salary'), partition_by=F('department'), order_by=F('hire_date').asc(), )).order_by('department', 'hire_date') self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 45000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 45000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 45000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 45000), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 60000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 60000), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 100000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 100000), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 38000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 38000), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 55000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 55000), ], lambda row: (row.name, row.salary, row.department, row.hire_date, row.first_value)) def test_last_value(self): qs = Employee.objects.annotate(last_value=Window( expression=LastValue('hire_date'), partition_by=F('department'), order_by=F('hire_date').asc(), )) self.assertQuerysetEqual(qs, [ ('Adams', 'Accounting', datetime.date(2013, 7, 1), 50000, datetime.date(2013, 7, 1)), ('Jenson', 'Accounting', datetime.date(2008, 4, 1), 45000, datetime.date(2008, 4, 1)), ('Jones', 'Accounting', datetime.date(2005, 11, 1), 45000, datetime.date(2005, 11, 1)), ('Williams', 'Accounting', datetime.date(2009, 6, 1), 37000, datetime.date(2009, 6, 1)), ('Moore', 'IT', datetime.date(2013, 8, 1), 34000, datetime.date(2013, 8, 1)), ('Wilkinson', 'IT', datetime.date(2011, 3, 1), 60000, datetime.date(2011, 3, 1)), ('Miller', 'Management', datetime.date(2005, 6, 1), 100000, datetime.date(2005, 6, 1)), ('Johnson', 'Management', datetime.date(2005, 7, 1), 80000, datetime.date(2005, 7, 1)), ('Johnson', 'Marketing', datetime.date(2012, 3, 1), 40000, datetime.date(2012, 3, 1)), ('Smith', 'Marketing', datetime.date(2009, 10, 1), 38000, datetime.date(2009, 10, 1)), ('Brown', 'Sales', datetime.date(2009, 9, 1), 53000, datetime.date(2009, 9, 1)), ('Smith', 'Sales', datetime.date(2007, 6, 1), 55000, datetime.date(2007, 6, 1)), ], transform=lambda row: (row.name, row.department, row.hire_date, row.salary, row.last_value), ordered=False) def test_function_list_of_values(self): qs = Employee.objects.annotate(lead=Window( expression=Lead(expression='salary'), order_by=[F('hire_date').asc(), F('name').desc()], partition_by='department', )).values_list('name', 'salary', 'department', 'hire_date', 'lead') \ .order_by('department', F('hire_date').asc(), F('name').desc()) self.assertNotIn('GROUP BY', str(qs.query)) self.assertSequenceEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 45000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 37000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 50000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), None), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 34000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), None), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 80000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), None), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 40000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), None), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 53000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), None), ]) def test_min_department(self): """An alternative way to specify a query for FirstValue.""" qs = Employee.objects.annotate(min_salary=Window( expression=Min('salary'), partition_by=F('department'), order_by=[F('salary').asc(), F('name').asc()] )).order_by('department', 'salary', 'name') self.assertQuerysetEqual(qs, [ ('Williams', 'Accounting', 37000, 37000), ('Jenson', 'Accounting', 45000, 37000), ('Jones', 'Accounting', 45000, 37000), ('Adams', 'Accounting', 50000, 37000), ('Moore', 'IT', 34000, 34000), ('Wilkinson', 'IT', 60000, 34000), ('Johnson', 'Management', 80000, 80000), ('Miller', 'Management', 100000, 80000), ('Smith', 'Marketing', 38000, 38000), ('Johnson', 'Marketing', 40000, 38000), ('Brown', 'Sales', 53000, 53000), ('Smith', 'Sales', 55000, 53000), ], lambda row: (row.name, row.department, row.salary, row.min_salary)) def test_max_per_year(self): """ Find the maximum salary awarded in the same year as the employee was hired, regardless of the department. """ qs = Employee.objects.annotate(max_salary_year=Window( expression=Max('salary'), order_by=ExtractYear('hire_date').asc(), partition_by=ExtractYear('hire_date') )).order_by(ExtractYear('hire_date'), 'salary') self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', 45000, 2005, 100000), ('Johnson', 'Management', 80000, 2005, 100000), ('Miller', 'Management', 100000, 2005, 100000), ('Smith', 'Sales', 55000, 2007, 55000), ('Jenson', 'Accounting', 45000, 2008, 45000), ('Williams', 'Accounting', 37000, 2009, 53000), ('Smith', 'Marketing', 38000, 2009, 53000), ('Brown', 'Sales', 53000, 2009, 53000), ('Wilkinson', 'IT', 60000, 2011, 60000), ('Johnson', 'Marketing', 40000, 2012, 40000), ('Moore', 'IT', 34000, 2013, 50000), ('Adams', 'Accounting', 50000, 2013, 50000), ], lambda row: (row.name, row.department, row.salary, row.hire_date.year, row.max_salary_year)) def test_cume_dist(self): """ Compute the cumulative distribution for the employees based on the salary in increasing order. Equal to rank/total number of rows (12). """ qs = Employee.objects.annotate(cume_dist=Window( expression=CumeDist(), order_by=F('salary').asc(), )).order_by('salary', 'name') # Round result of cume_dist because Oracle uses greater precision. self.assertQuerysetEqual(qs, [ ('Moore', 'IT', 34000, 0.0833333333), ('Williams', 'Accounting', 37000, 0.1666666667), ('Smith', 'Marketing', 38000, 0.25), ('Johnson', 'Marketing', 40000, 0.3333333333), ('Jenson', 'Accounting', 45000, 0.5), ('Jones', 'Accounting', 45000, 0.5), ('Adams', 'Accounting', 50000, 0.5833333333), ('Brown', 'Sales', 53000, 0.6666666667), ('Smith', 'Sales', 55000, 0.75), ('Wilkinson', 'IT', 60000, 0.8333333333), ('Johnson', 'Management', 80000, 0.9166666667), ('Miller', 'Management', 100000, 1), ], lambda row: (row.name, row.department, row.salary, round(row.cume_dist, 10))) def test_nthvalue(self): qs = Employee.objects.annotate( nth_value=Window(expression=NthValue( expression='salary', nth=2), order_by=[F('hire_date').asc(), F('name').desc()], partition_by=F('department'), ) ).order_by('department', 'hire_date', 'name') self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', datetime.date(2005, 11, 1), 45000, None), ('Jenson', 'Accounting', datetime.date(2008, 4, 1), 45000, 45000), ('Williams', 'Accounting', datetime.date(2009, 6, 1), 37000, 45000), ('Adams', 'Accounting', datetime.date(2013, 7, 1), 50000, 45000), ('Wilkinson', 'IT', datetime.date(2011, 3, 1), 60000, None), ('Moore', 'IT', datetime.date(2013, 8, 1), 34000, 34000), ('Miller', 'Management', datetime.date(2005, 6, 1), 100000, None), ('Johnson', 'Management', datetime.date(2005, 7, 1), 80000, 80000), ('Smith', 'Marketing', datetime.date(2009, 10, 1), 38000, None), ('Johnson', 'Marketing', datetime.date(2012, 3, 1), 40000, 40000), ('Smith', 'Sales', datetime.date(2007, 6, 1), 55000, None), ('Brown', 'Sales', datetime.date(2009, 9, 1), 53000, 53000), ], lambda row: (row.name, row.department, row.hire_date, row.salary, row.nth_value)) def test_lead(self): """ Determine what the next person hired in the same department makes. Because the dataset is ambiguous, the name is also part of the ordering clause. No default is provided, so None/NULL should be returned. """ qs = Employee.objects.annotate(lead=Window( expression=Lead(expression='salary'), order_by=[F('hire_date').asc(), F('name').desc()], partition_by='department', )).order_by('department', F('hire_date').asc(), F('name').desc()) self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 45000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 37000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 50000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), None), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 34000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), None), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 80000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), None), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 40000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), None), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 53000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), None), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.lead)) def test_lead_offset(self): """ Determine what the person hired after someone makes. Due to ambiguity, the name is also included in the ordering. """ qs = Employee.objects.annotate(lead=Window( expression=Lead('salary', offset=2), partition_by='department', order_by=F('hire_date').asc(), )) self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 37000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 50000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), None), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), None), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), None), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), None), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), None), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), None), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), None), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), None), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), None), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), None), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.lead), ordered=False ) @skipUnlessDBFeature('supports_default_in_lead_lag') def test_lead_default(self): qs = Employee.objects.annotate(lead_default=Window( expression=Lead(expression='salary', offset=5, default=60000), partition_by=F('department'), order_by=F('department').asc(), )) self.assertEqual(list(qs.values_list('lead_default', flat=True).distinct()), [60000]) def test_ntile(self): """ Compute the group for each of the employees across the entire company, based on how high the salary is for them. There are twelve employees so it divides evenly into four groups. """ qs = Employee.objects.annotate(ntile=Window( expression=Ntile(num_buckets=4), order_by=F('salary').desc(), )).order_by('ntile', '-salary', 'name') self.assertQuerysetEqual(qs, [ ('Miller', 'Management', 100000, 1), ('Johnson', 'Management', 80000, 1), ('Wilkinson', 'IT', 60000, 1), ('Smith', 'Sales', 55000, 2), ('Brown', 'Sales', 53000, 2), ('Adams', 'Accounting', 50000, 2), ('Jenson', 'Accounting', 45000, 3), ('Jones', 'Accounting', 45000, 3), ('Johnson', 'Marketing', 40000, 3), ('Smith', 'Marketing', 38000, 4), ('Williams', 'Accounting', 37000, 4), ('Moore', 'IT', 34000, 4), ], lambda x: (x.name, x.department, x.salary, x.ntile)) def test_percent_rank(self): """ Calculate the percentage rank of the employees across the entire company based on salary and name (in case of ambiguity). """ qs = Employee.objects.annotate(percent_rank=Window( expression=PercentRank(), order_by=[F('salary').asc(), F('name').asc()], )).order_by('percent_rank') # Round to account for precision differences among databases. self.assertQuerysetEqual(qs, [ ('Moore', 'IT', 34000, 0.0), ('Williams', 'Accounting', 37000, 0.0909090909), ('Smith', 'Marketing', 38000, 0.1818181818), ('Johnson', 'Marketing', 40000, 0.2727272727), ('Jenson', 'Accounting', 45000, 0.3636363636), ('Jones', 'Accounting', 45000, 0.4545454545), ('Adams', 'Accounting', 50000, 0.5454545455), ('Brown', 'Sales', 53000, 0.6363636364), ('Smith', 'Sales', 55000, 0.7272727273), ('Wilkinson', 'IT', 60000, 0.8181818182), ('Johnson', 'Management', 80000, 0.9090909091), ('Miller', 'Management', 100000, 1.0), ], transform=lambda row: (row.name, row.department, row.salary, round(row.percent_rank, 10))) def test_nth_returns_null(self): """ Find the nth row of the data set. None is returned since there are fewer than 20 rows in the test data. """ qs = Employee.objects.annotate(nth_value=Window( expression=NthValue('salary', nth=20), order_by=F('salary').asc() )) self.assertEqual(list(qs.values_list('nth_value', flat=True).distinct()), [None]) def test_multiple_partitioning(self): """ Find the maximum salary for each department for people hired in the same year. """ qs = Employee.objects.annotate(max=Window( expression=Max('salary'), partition_by=[F('department'), ExtractYear(F('hire_date'))], )).order_by('department', 'hire_date', 'name') self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 45000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 45000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 37000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 50000), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 60000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 34000), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 100000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 100000), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 38000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 40000), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 55000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 53000), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.max)) def test_multiple_ordering(self): """ Accumulate the salaries over the departments based on hire_date. If two people were hired on the same date in the same department, the ordering clause will render a different result for those people. """ qs = Employee.objects.annotate(sum=Window( expression=Sum('salary'), partition_by='department', order_by=[F('hire_date').asc(), F('name').asc()], )).order_by('department', 'sum') self.assertQuerysetEqual(qs, [ ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 45000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 90000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 127000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 177000), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 60000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 94000), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 100000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 180000), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 38000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 78000), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 55000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 108000), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.sum)) @skipUnlessDBFeature('supports_frame_range_fixed_distance') def test_range_n_preceding_and_following(self): qs = Employee.objects.annotate(sum=Window( expression=Sum('salary'), order_by=F('salary').asc(), partition_by='department', frame=ValueRange(start=-2, end=2), )) self.assertIn('RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING', str(qs.query)) self.assertQuerysetEqual(qs, [ ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 37000), ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 90000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 90000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 50000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 53000), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 55000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 40000), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 38000), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 60000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 34000), ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 100000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 80000), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.sum), ordered=False) def test_range_unbound(self): """A query with RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.""" qs = Employee.objects.annotate(sum=Window( expression=Sum('salary'), partition_by='age', order_by=[F('age').asc()], frame=ValueRange(start=None, end=None), )).order_by('department', 'hire_date', 'name') self.assertIn('RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING', str(qs.query)) self.assertQuerysetEqual(qs, [ ('Jones', 'Accounting', 45000, datetime.date(2005, 11, 1), 165000), ('Jenson', 'Accounting', 45000, datetime.date(2008, 4, 1), 165000), ('Williams', 'Accounting', 37000, datetime.date(2009, 6, 1), 165000), ('Adams', 'Accounting', 50000, datetime.date(2013, 7, 1), 130000), ('Wilkinson', 'IT', 60000, datetime.date(2011, 3, 1), 194000), ('Moore', 'IT', 34000, datetime.date(2013, 8, 1), 194000), ('Miller', 'Management', 100000, datetime.date(2005, 6, 1), 194000), ('Johnson', 'Management', 80000, datetime.date(2005, 7, 1), 130000), ('Smith', 'Marketing', 38000, datetime.date(2009, 10, 1), 165000), ('Johnson', 'Marketing', 40000, datetime.date(2012, 3, 1), 148000), ('Smith', 'Sales', 55000, datetime.date(2007, 6, 1), 148000), ('Brown', 'Sales', 53000, datetime.date(2009, 9, 1), 148000) ], transform=lambda row: (row.name, row.department, row.salary, row.hire_date, row.sum)) @skipIf( connection.vendor == 'sqlite' and connection.Database.sqlite_version_info < (3, 27), 'Nondeterministic failure on SQLite < 3.27.' ) def test_subquery_row_range_rank(self): qs = Employee.objects.annotate( highest_avg_salary_date=Subquery( Employee.objects.filter( department=OuterRef('department'), ).annotate( avg_salary=Window( expression=Avg('salary'), order_by=[F('hire_date').asc()], frame=RowRange(start=-1, end=1), ), ).order_by('-avg_salary', 'hire_date').values('hire_date')[:1], ), ).order_by('department', 'name') self.assertQuerysetEqual(qs, [ ('Adams', 'Accounting', datetime.date(2005, 11, 1)), ('Jenson', 'Accounting', datetime.date(2005, 11, 1)), ('Jones', 'Accounting', datetime.date(2005, 11, 1)), ('Williams', 'Accounting', datetime.date(2005, 11, 1)), ('Moore', 'IT', datetime.date(2011, 3, 1)), ('Wilkinson', 'IT', datetime.date(2011, 3, 1)), ('Johnson', 'Management', datetime.date(2005, 6, 1)), ('Miller', 'Management', datetime.date(2005, 6, 1)), ('Johnson', 'Marketing', datetime.date(2009, 10, 1)), ('Smith', 'Marketing', datetime.date(2009, 10, 1)), ('Brown', 'Sales', datetime.date(2007, 6, 1)), ('Smith', 'Sales', datetime.date(2007, 6, 1)), ], transform=lambda row: (row.name, row.department, row.highest_avg_salary_date)) def test_row_range_rank(self): """ A query with ROWS BETWEEN UNBOUNDED PRECEDING AND 3 FOLLOWING. The resulting sum is the sum of the three next (if they exist) and all previous rows according to the ordering clause. """ qs = Employee.objects.annotate(sum=Window( expression=Sum('salary'), order_by=[F('hire_date').asc(), F('name').desc()], frame=RowRange(start=None, end=3), )).order_by('sum', 'hire_date') self.assertIn('ROWS BETWEEN UNBOUNDED PRECEDING AND 3 FOLLOWING', str(qs.query)) self.assertQuerysetEqual(qs, [ ('Miller', 100000, 'Management', datetime.date(2005, 6, 1), 280000), ('Johnson', 80000, 'Management', datetime.date(2005, 7, 1), 325000), ('Jones', 45000, 'Accounting', datetime.date(2005, 11, 1), 362000), ('Smith', 55000, 'Sales', datetime.date(2007, 6, 1), 415000), ('Jenson', 45000, 'Accounting', datetime.date(2008, 4, 1), 453000), ('Williams', 37000, 'Accounting', datetime.date(2009, 6, 1), 513000), ('Brown', 53000, 'Sales', datetime.date(2009, 9, 1), 553000), ('Smith', 38000, 'Marketing', datetime.date(2009, 10, 1), 603000), ('Wilkinson', 60000, 'IT', datetime.date(2011, 3, 1), 637000), ('Johnson', 40000, 'Marketing', datetime.date(2012, 3, 1), 637000), ('Adams', 50000, 'Accounting', datetime.date(2013, 7, 1), 637000), ('Moore', 34000, 'IT', datetime.date(2013, 8, 1), 637000), ], transform=lambda row: (row.name, row.salary, row.department, row.hire_date, row.sum)) @skipUnlessDBFeature('can_distinct_on_fields') def test_distinct_window_function(self): """ Window functions are not aggregates, and hence a query to filter out duplicates may be useful. """ qs = Employee.objects.annotate( sum=Window( expression=Sum('salary'), partition_by=ExtractYear('hire_date'), order_by=ExtractYear('hire_date') ), year=ExtractYear('hire_date'), ).values('year', 'sum').distinct('year').order_by('year') results = [ {'year': 2005, 'sum': 225000}, {'year': 2007, 'sum': 55000}, {'year': 2008, 'sum': 45000}, {'year': 2009, 'sum': 128000}, {'year': 2011, 'sum': 60000}, {'year': 2012, 'sum': 40000}, {'year': 2013, 'sum': 84000}, ] for idx, val in zip(range(len(results)), results): with self.subTest(result=val): self.assertEqual(qs[idx], val) def test_fail_update(self): """Window expressions can't be used in an UPDATE statement.""" msg = ( 'Window expressions are not allowed in this query (salary=<Window: ' 'Max(Col(expressions_window_employee, expressions_window.Employee.salary)) ' 'OVER (PARTITION BY Col(expressions_window_employee, ' 'expressions_window.Employee.department))>).' ) with self.assertRaisesMessage(FieldError, msg): Employee.objects.filter(department='Management').update( salary=Window(expression=Max('salary'), partition_by='department'), ) def test_fail_insert(self): """Window expressions can't be used in an INSERT statement.""" msg = ( 'Window expressions are not allowed in this query (salary=<Window: ' 'Sum(Value(10000), order_by=OrderBy(F(pk), descending=False)) OVER ()' ) with self.assertRaisesMessage(FieldError, msg): Employee.objects.create( name='Jameson', department='Management', hire_date=datetime.date(2007, 7, 1), salary=Window(expression=Sum(Value(10000), order_by=F('pk').asc())), ) def test_window_expression_within_subquery(self): subquery_qs = Employee.objects.annotate( highest=Window(FirstValue('id'), partition_by=F('department'), order_by=F('salary').desc()) ).values('highest') highest_salary = Employee.objects.filter(pk__in=subquery_qs) self.assertSequenceEqual(highest_salary.values('department', 'salary'), [ {'department': 'Accounting', 'salary': 50000}, {'department': 'Sales', 'salary': 55000}, {'department': 'Marketing', 'salary': 40000}, {'department': 'IT', 'salary': 60000}, {'department': 'Management', 'salary': 100000} ]) def test_invalid_start_value_range(self): msg = "start argument must be a negative integer, zero, or None, but got '3'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=ValueRange(start=3), ))) def test_invalid_end_value_range(self): msg = "end argument must be a positive integer, zero, or None, but got '-3'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=ValueRange(end=-3), ))) def test_invalid_type_end_value_range(self): msg = "end argument must be a positive integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=ValueRange(end='a'), ))) def test_invalid_type_start_value_range(self): msg = "start argument must be a negative integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), frame=ValueRange(start='a'), ))) def test_invalid_type_end_row_range(self): msg = "end argument must be a positive integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), frame=RowRange(end='a'), ))) @skipUnless(connection.vendor == 'postgresql', 'Frame construction not allowed on PostgreSQL') def test_postgresql_illegal_range_frame_start(self): msg = 'PostgreSQL only supports UNBOUNDED together with PRECEDING and FOLLOWING.' with self.assertRaisesMessage(NotSupportedError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=ValueRange(start=-1), ))) @skipUnless(connection.vendor == 'postgresql', 'Frame construction not allowed on PostgreSQL') def test_postgresql_illegal_range_frame_end(self): msg = 'PostgreSQL only supports UNBOUNDED together with PRECEDING and FOLLOWING.' with self.assertRaisesMessage(NotSupportedError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=ValueRange(end=1), ))) def test_invalid_type_start_row_range(self): msg = "start argument must be a negative integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list(Employee.objects.annotate(test=Window( expression=Sum('salary'), order_by=F('hire_date').asc(), frame=RowRange(start='a'), ))) class WindowUnsupportedTests(TestCase): def test_unsupported_backend(self): msg = 'This backend does not support window expressions.' with mock.patch.object(connection.features, 'supports_over_clause', False): with self.assertRaisesMessage(NotSupportedError, msg): Employee.objects.annotate(dense_rank=Window(expression=DenseRank())).get() class NonQueryWindowTests(SimpleTestCase): def test_window_repr(self): self.assertEqual( repr(Window(expression=Sum('salary'), partition_by='department')), '<Window: Sum(F(salary)) OVER (PARTITION BY F(department))>' ) self.assertEqual( repr(Window(expression=Avg('salary'), order_by=F('department').asc())), '<Window: Avg(F(salary)) OVER (ORDER BY OrderBy(F(department), descending=False))>' ) def test_window_frame_repr(self): self.assertEqual( repr(RowRange(start=-1)), '<RowRange: ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING>' ) self.assertEqual( repr(ValueRange(start=None, end=1)), '<ValueRange: RANGE BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING>' ) self.assertEqual( repr(ValueRange(start=0, end=0)), '<ValueRange: RANGE BETWEEN CURRENT ROW AND CURRENT ROW>' ) self.assertEqual( repr(RowRange(start=0, end=0)), '<RowRange: ROWS BETWEEN CURRENT ROW AND CURRENT ROW>' ) def test_empty_group_by_cols(self): window = Window(expression=Sum('pk')) self.assertEqual(window.get_group_by_cols(), []) self.assertFalse(window.contains_aggregate) def test_frame_empty_group_by_cols(self): frame = WindowFrame() self.assertEqual(frame.get_group_by_cols(), []) def test_frame_window_frame_notimplemented(self): frame = WindowFrame() msg = 'Subclasses must implement window_frame_start_end().' with self.assertRaisesMessage(NotImplementedError, msg): frame.window_frame_start_end(None, None, None) def test_invalid_filter(self): msg = 'Window is disallowed in the filter clause' with self.assertRaisesMessage(NotSupportedError, msg): Employee.objects.annotate(dense_rank=Window(expression=DenseRank())).filter(dense_rank__gte=1) def test_invalid_order_by(self): msg = 'order_by must be either an Expression or a sequence of expressions' with self.assertRaisesMessage(ValueError, msg): Window(expression=Sum('power'), order_by='-horse') def test_invalid_source_expression(self): msg = "Expression 'Upper' isn't compatible with OVER clauses." with self.assertRaisesMessage(ValueError, msg): Window(expression=Upper('name'))
de07deec62917a6721fda6034d2e3b994d740abd257a1eda843de268d465e3c3
from django.db import models class Employee(models.Model): name = models.CharField(max_length=40, blank=False, null=False) salary = models.PositiveIntegerField() department = models.CharField(max_length=40, blank=False, null=False) hire_date = models.DateField(blank=False, null=False) age = models.IntegerField(blank=False, null=False) def __str__(self): return '{}, {}, {}, {}'.format(self.name, self.department, self.salary, self.hire_date)
2a31d25ee24154cb2faebf7ce0af7cbd403613959e7b8fb453ecedac7a50560a
from datetime import datetime from operator import attrgetter from django.core.exceptions import FieldError from django.db.models import ( CharField, Count, DateTimeField, F, Max, OuterRef, Subquery, Value, ) from django.db.models.functions import Upper from django.test import TestCase from django.utils.deprecation import RemovedInDjango31Warning from .models import Article, Author, OrderedByFArticle, Reference class OrderingTests(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Article.objects.create(headline="Article 1", pub_date=datetime(2005, 7, 26)) cls.a2 = Article.objects.create(headline="Article 2", pub_date=datetime(2005, 7, 27)) cls.a3 = Article.objects.create(headline="Article 3", pub_date=datetime(2005, 7, 27)) cls.a4 = Article.objects.create(headline="Article 4", pub_date=datetime(2005, 7, 28)) cls.author_1 = Author.objects.create(name="Name 1") cls.author_2 = Author.objects.create(name="Name 2") for i in range(2): Author.objects.create() def test_default_ordering(self): """ By default, Article.objects.all() orders by pub_date descending, then headline ascending. """ self.assertQuerysetEqual( Article.objects.all(), [ "Article 4", "Article 2", "Article 3", "Article 1", ], attrgetter("headline") ) # Getting a single item should work too: self.assertEqual(Article.objects.all()[0], self.a4) def test_default_ordering_override(self): """ Override ordering with order_by, which is in the same format as the ordering attribute in models. """ self.assertQuerysetEqual( Article.objects.order_by("headline"), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.order_by("pub_date", "-headline"), [ "Article 1", "Article 3", "Article 2", "Article 4", ], attrgetter("headline") ) def test_order_by_override(self): """ Only the last order_by has any effect (since they each override any previous ordering). """ self.assertQuerysetEqual( Article.objects.order_by("id"), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.order_by("id").order_by("-headline"), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline") ) def test_order_by_nulls_first_and_last(self): msg = "nulls_first and nulls_last are mutually exclusive" with self.assertRaisesMessage(ValueError, msg): Article.objects.order_by(F("author").desc(nulls_last=True, nulls_first=True)) def assertQuerysetEqualReversible(self, queryset, sequence): self.assertSequenceEqual(queryset, sequence) self.assertSequenceEqual(queryset.reverse(), list(reversed(sequence))) def test_order_by_nulls_last(self): Article.objects.filter(headline="Article 3").update(author=self.author_1) Article.objects.filter(headline="Article 4").update(author=self.author_2) # asc and desc are chainable with nulls_last. self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").desc(nulls_last=True), 'headline'), [self.a4, self.a3, self.a1, self.a2], ) self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").asc(nulls_last=True), 'headline'), [self.a3, self.a4, self.a1, self.a2], ) self.assertQuerysetEqualReversible( Article.objects.order_by(Upper("author__name").desc(nulls_last=True), 'headline'), [self.a4, self.a3, self.a1, self.a2], ) self.assertQuerysetEqualReversible( Article.objects.order_by(Upper("author__name").asc(nulls_last=True), 'headline'), [self.a3, self.a4, self.a1, self.a2], ) def test_order_by_nulls_first(self): Article.objects.filter(headline="Article 3").update(author=self.author_1) Article.objects.filter(headline="Article 4").update(author=self.author_2) # asc and desc are chainable with nulls_first. self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").asc(nulls_first=True), 'headline'), [self.a1, self.a2, self.a3, self.a4], ) self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").desc(nulls_first=True), 'headline'), [self.a1, self.a2, self.a4, self.a3], ) self.assertQuerysetEqualReversible( Article.objects.order_by(Upper("author__name").asc(nulls_first=True), 'headline'), [self.a1, self.a2, self.a3, self.a4], ) self.assertQuerysetEqualReversible( Article.objects.order_by(Upper("author__name").desc(nulls_first=True), 'headline'), [self.a1, self.a2, self.a4, self.a3], ) def test_orders_nulls_first_on_filtered_subquery(self): Article.objects.filter(headline='Article 1').update(author=self.author_1) Article.objects.filter(headline='Article 2').update(author=self.author_1) Article.objects.filter(headline='Article 4').update(author=self.author_2) Author.objects.filter(name__isnull=True).delete() author_3 = Author.objects.create(name='Name 3') article_subquery = Article.objects.filter( author=OuterRef('pk'), headline__icontains='Article', ).order_by().values('author').annotate( last_date=Max('pub_date'), ).values('last_date') self.assertQuerysetEqualReversible( Author.objects.annotate( last_date=Subquery(article_subquery, output_field=DateTimeField()) ).order_by( F('last_date').asc(nulls_first=True) ).distinct(), [author_3, self.author_1, self.author_2], ) def test_stop_slicing(self): """ Use the 'stop' part of slicing notation to limit the results. """ self.assertQuerysetEqual( Article.objects.order_by("headline")[:2], [ "Article 1", "Article 2", ], attrgetter("headline") ) def test_stop_start_slicing(self): """ Use the 'stop' and 'start' parts of slicing notation to offset the result list. """ self.assertQuerysetEqual( Article.objects.order_by("headline")[1:3], [ "Article 2", "Article 3", ], attrgetter("headline") ) def test_random_ordering(self): """ Use '?' to order randomly. """ self.assertEqual( len(list(Article.objects.order_by("?"))), 4 ) def test_reversed_ordering(self): """ Ordering can be reversed using the reverse() method on a queryset. This allows you to extract things like "the last two items" (reverse and then take the first two). """ self.assertQuerysetEqual( Article.objects.all().reverse()[:2], [ "Article 1", "Article 3", ], attrgetter("headline") ) def test_reverse_ordering_pure(self): qs1 = Article.objects.order_by(F('headline').asc()) qs2 = qs1.reverse() self.assertQuerysetEqual( qs2, [ 'Article 4', 'Article 3', 'Article 2', 'Article 1', ], attrgetter('headline'), ) self.assertQuerysetEqual( qs1, [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) def test_reverse_meta_ordering_pure(self): Article.objects.create( headline='Article 5', pub_date=datetime(2005, 7, 30), author=self.author_1, second_author=self.author_2, ) Article.objects.create( headline='Article 5', pub_date=datetime(2005, 7, 30), author=self.author_2, second_author=self.author_1, ) self.assertQuerysetEqual( Article.objects.filter(headline='Article 5').reverse(), ['Name 2', 'Name 1'], attrgetter('author.name'), ) self.assertQuerysetEqual( Article.objects.filter(headline='Article 5'), ['Name 1', 'Name 2'], attrgetter('author.name'), ) def test_no_reordering_after_slicing(self): msg = 'Cannot reverse a query once a slice has been taken.' qs = Article.objects.all()[0:2] with self.assertRaisesMessage(TypeError, msg): qs.reverse() with self.assertRaisesMessage(TypeError, msg): qs.last() def test_extra_ordering(self): """ Ordering can be based on fields included from an 'extra' clause """ self.assertQuerysetEqual( Article.objects.extra(select={"foo": "pub_date"}, order_by=["foo", "headline"]), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) def test_extra_ordering_quoting(self): """ If the extra clause uses an SQL keyword for a name, it will be protected by quoting. """ self.assertQuerysetEqual( Article.objects.extra(select={"order": "pub_date"}, order_by=["order", "headline"]), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) def test_extra_ordering_with_table_name(self): self.assertQuerysetEqual( Article.objects.extra(order_by=['ordering_article.headline']), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.extra(order_by=['-ordering_article.headline']), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline") ) def test_order_by_pk(self): """ 'pk' works as an ordering option in Meta. """ self.assertQuerysetEqual( Author.objects.all(), list(reversed(range(1, Author.objects.count() + 1))), attrgetter("pk"), ) def test_order_by_fk_attname(self): """ ordering by a foreign key by its attribute name prevents the query from inheriting its related model ordering option (#19195). """ for i in range(1, 5): author = Author.objects.get(pk=i) article = getattr(self, "a%d" % (5 - i)) article.author = author article.save(update_fields={'author'}) self.assertQuerysetEqual( Article.objects.order_by('author_id'), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline") ) def test_order_by_f_expression(self): self.assertQuerysetEqual( Article.objects.order_by(F('headline')), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.order_by(F('headline').asc()), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) self.assertQuerysetEqual( Article.objects.order_by(F('headline').desc()), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline") ) def test_order_by_f_expression_duplicates(self): """ A column may only be included once (the first occurrence) so we check to ensure there are no duplicates by inspecting the SQL. """ qs = Article.objects.order_by(F('headline').asc(), F('headline').desc()) sql = str(qs.query).upper() fragment = sql[sql.find('ORDER BY'):] self.assertEqual(fragment.count('HEADLINE'), 1) self.assertQuerysetEqual( qs, [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline") ) qs = Article.objects.order_by(F('headline').desc(), F('headline').asc()) sql = str(qs.query).upper() fragment = sql[sql.find('ORDER BY'):] self.assertEqual(fragment.count('HEADLINE'), 1) self.assertQuerysetEqual( qs, [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline") ) def test_order_by_constant_value(self): # Order by annotated constant from selected columns. qs = Article.objects.annotate( constant=Value('1', output_field=CharField()), ).order_by('constant', '-headline') self.assertSequenceEqual(qs, [self.a4, self.a3, self.a2, self.a1]) # Order by annotated constant which is out of selected columns. self.assertSequenceEqual( qs.values_list('headline', flat=True), [ 'Article 4', 'Article 3', 'Article 2', 'Article 1', ], ) # Order by constant. qs = Article.objects.order_by(Value('1', output_field=CharField()), '-headline') self.assertSequenceEqual(qs, [self.a4, self.a3, self.a2, self.a1]) def test_order_by_constant_value_without_output_field(self): msg = 'Cannot resolve expression type, unknown output_field' qs = Article.objects.annotate(constant=Value('1')).order_by('constant') for ordered_qs in ( qs, qs.values('headline'), Article.objects.order_by(Value('1')), ): with self.subTest(ordered_qs=ordered_qs), self.assertRaisesMessage(FieldError, msg): ordered_qs.first() def test_related_ordering_duplicate_table_reference(self): """ An ordering referencing a model with an ordering referencing a model multiple time no circular reference should be detected (#24654). """ first_author = Author.objects.create() second_author = Author.objects.create() self.a1.author = first_author self.a1.second_author = second_author self.a1.save() self.a2.author = second_author self.a2.second_author = first_author self.a2.save() r1 = Reference.objects.create(article_id=self.a1.pk) r2 = Reference.objects.create(article_id=self.a2.pk) self.assertSequenceEqual(Reference.objects.all(), [r2, r1]) def test_default_ordering_by_f_expression(self): """F expressions can be used in Meta.ordering.""" articles = OrderedByFArticle.objects.all() articles.filter(headline='Article 2').update(author=self.author_2) articles.filter(headline='Article 3').update(author=self.author_1) self.assertQuerysetEqual( articles, ['Article 1', 'Article 4', 'Article 3', 'Article 2'], attrgetter('headline') ) def test_deprecated_values_annotate(self): msg = ( "Article QuerySet won't use Meta.ordering in Django 3.1. Add " ".order_by('-pub_date', 'headline', OrderBy(F(author__name), " "descending=False), OrderBy(F(second_author__name), " "descending=False)) to retain the current query." ) with self.assertRaisesMessage(RemovedInDjango31Warning, msg): list(Article.objects.values('author').annotate(Count('headline')))
85623074ea8b56666ce40afc8c98f2caafdcfcd76729a94f495fb49ea3b77bbd
""" Specifying ordering Specify default ordering for a model using the ``ordering`` attribute, which should be a list or tuple of field names. This tells Django how to order ``QuerySet`` results. If a field name in ``ordering`` starts with a hyphen, that field will be ordered in descending order. Otherwise, it'll be ordered in ascending order. The special-case field name ``"?"`` specifies random order. The ordering attribute is not required. If you leave it off, ordering will be undefined -- not random, just undefined. """ from django.db import models from django.db.models.expressions import OrderBy class Author(models.Model): name = models.CharField(max_length=63, null=True, blank=True) class Meta: ordering = ('-pk',) class Article(models.Model): author = models.ForeignKey(Author, models.SET_NULL, null=True) second_author = models.ForeignKey(Author, models.SET_NULL, null=True, related_name='+') headline = models.CharField(max_length=100) pub_date = models.DateTimeField() class Meta: ordering = ( '-pub_date', 'headline', models.F('author__name').asc(), OrderBy(models.F('second_author__name')), ) def __str__(self): return self.headline class OrderedByAuthorArticle(Article): class Meta: proxy = True ordering = ('author', 'second_author') class OrderedByFArticle(Article): class Meta: proxy = True ordering = (models.F('author').asc(nulls_first=True), 'id') class Reference(models.Model): article = models.ForeignKey(OrderedByAuthorArticle, models.CASCADE) class Meta: ordering = ('article',)
8569312386a91c12111c45420747f596060a61324ed95e2a84ae4b668ecc9e16
import warnings from django.test import SimpleTestCase from django.utils.deprecation import ( DeprecationInstanceCheck, RemovedInNextVersionWarning, RenameMethodsBase, ) class RenameManagerMethods(RenameMethodsBase): renamed_methods = ( ('old', 'new', DeprecationWarning), ) class RenameMethodsTests(SimpleTestCase): """ Tests the `RenameMethodsBase` type introduced to rename `get_query_set` to `get_queryset` across the code base following #15363. """ def test_class_definition_warnings(self): """ Ensure a warning is raised upon class definition to suggest renaming the faulty method. """ msg = '`Manager.old` method should be renamed `new`.' with self.assertWarnsMessage(DeprecationWarning, msg): class Manager(metaclass=RenameManagerMethods): def old(self): pass def test_get_new_defined(self): """ Ensure `old` complains and not `new` when only `new` is defined. """ class Manager(metaclass=RenameManagerMethods): def new(self): pass manager = Manager() with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('always') manager.new() self.assertEqual(len(recorded), 0) msg = '`Manager.old` is deprecated, use `new` instead.' with self.assertWarnsMessage(DeprecationWarning, msg): manager.old() def test_get_old_defined(self): """ Ensure `old` complains when only `old` is defined. """ msg = '`Manager.old` method should be renamed `new`.' with self.assertWarnsMessage(DeprecationWarning, msg): class Manager(metaclass=RenameManagerMethods): def old(self): pass manager = Manager() with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('always') manager.new() self.assertEqual(len(recorded), 0) msg = '`Manager.old` is deprecated, use `new` instead.' with self.assertWarnsMessage(DeprecationWarning, msg): manager.old() def test_deprecated_subclass_renamed(self): """ Ensure the correct warnings are raised when a class that didn't rename `old` subclass one that did. """ class Renamed(metaclass=RenameManagerMethods): def new(self): pass msg = '`Deprecated.old` method should be renamed `new`.' with self.assertWarnsMessage(DeprecationWarning, msg): class Deprecated(Renamed): def old(self): super().old() deprecated = Deprecated() msg = '`Renamed.old` is deprecated, use `new` instead.' with self.assertWarnsMessage(DeprecationWarning, msg): deprecated.new() msg = '`Deprecated.old` is deprecated, use `new` instead.' with self.assertWarnsMessage(DeprecationWarning, msg): deprecated.old() def test_renamed_subclass_deprecated(self): """ Ensure the correct warnings are raised when a class that renamed `old` subclass one that didn't. """ msg = '`Deprecated.old` method should be renamed `new`.' with self.assertWarnsMessage(DeprecationWarning, msg): class Deprecated(metaclass=RenameManagerMethods): def old(self): pass class Renamed(Deprecated): def new(self): super().new() renamed = Renamed() with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter('always') renamed.new() self.assertEqual(len(recorded), 0) msg = '`Renamed.old` is deprecated, use `new` instead.' with self.assertWarnsMessage(DeprecationWarning, msg): renamed.old() def test_deprecated_subclass_renamed_and_mixins(self): """ Ensure the correct warnings are raised when a subclass inherit from a class that renamed `old` and mixins that may or may not have renamed `new`. """ class Renamed(metaclass=RenameManagerMethods): def new(self): pass class RenamedMixin: def new(self): super().new() class DeprecatedMixin: def old(self): super().old() msg = '`DeprecatedMixin.old` method should be renamed `new`.' with self.assertWarnsMessage(DeprecationWarning, msg): class Deprecated(DeprecatedMixin, RenamedMixin, Renamed): pass deprecated = Deprecated() msg = '`RenamedMixin.old` is deprecated, use `new` instead.' with self.assertWarnsMessage(DeprecationWarning, msg): deprecated.new() msg = '`DeprecatedMixin.old` is deprecated, use `new` instead.' with self.assertWarnsMessage(DeprecationWarning, msg): deprecated.old() class DeprecationInstanceCheckTest(SimpleTestCase): def test_warning(self): class Manager(metaclass=DeprecationInstanceCheck): alternative = 'fake.path.Foo' deprecation_warning = RemovedInNextVersionWarning msg = '`Manager` is deprecated, use `fake.path.Foo` instead.' with self.assertWarnsMessage(RemovedInNextVersionWarning, msg): isinstance(object, Manager)
f480d6e2e3db6d6c1b43dd917dd712866a1433d9347e83905534ad6eafbbb4a4
import base64 import hashlib import os import shutil import sys import tempfile as sys_tempfile import unittest from io import BytesIO, StringIO from urllib.parse import quote from django.core.files import temp as tempfile from django.core.files.uploadedfile import SimpleUploadedFile from django.http.multipartparser import ( MultiPartParser, MultiPartParserError, parse_header, ) from django.test import SimpleTestCase, TestCase, client, override_settings from . import uploadhandler from .models import FileModel UNICODE_FILENAME = 'test-0123456789_中文_Orléans.jpg' MEDIA_ROOT = sys_tempfile.mkdtemp() UPLOAD_TO = os.path.join(MEDIA_ROOT, 'test_upload') @override_settings(MEDIA_ROOT=MEDIA_ROOT, ROOT_URLCONF='file_uploads.urls', MIDDLEWARE=[]) class FileUploadTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() os.makedirs(MEDIA_ROOT, exist_ok=True) @classmethod def tearDownClass(cls): shutil.rmtree(MEDIA_ROOT) super().tearDownClass() def test_simple_upload(self): with open(__file__, 'rb') as fp: post_data = { 'name': 'Ringo', 'file_field': fp, } response = self.client.post('/upload/', post_data) self.assertEqual(response.status_code, 200) def test_large_upload(self): file = tempfile.NamedTemporaryFile with file(suffix=".file1") as file1, file(suffix=".file2") as file2: file1.write(b'a' * (2 ** 21)) file1.seek(0) file2.write(b'a' * (10 * 2 ** 20)) file2.seek(0) post_data = { 'name': 'Ringo', 'file_field1': file1, 'file_field2': file2, } for key in list(post_data): try: post_data[key + '_hash'] = hashlib.sha1(post_data[key].read()).hexdigest() post_data[key].seek(0) except AttributeError: post_data[key + '_hash'] = hashlib.sha1(post_data[key].encode()).hexdigest() response = self.client.post('/verify/', post_data) self.assertEqual(response.status_code, 200) def _test_base64_upload(self, content, encode=base64.b64encode): payload = client.FakePayload("\r\n".join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="test.txt"', 'Content-Type: application/octet-stream', 'Content-Transfer-Encoding: base64', ''])) payload.write(b'\r\n' + encode(content.encode()) + b'\r\n') payload.write('--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/echo_content/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.json()['file'], content) def test_base64_upload(self): self._test_base64_upload("This data will be transmitted base64-encoded.") def test_big_base64_upload(self): self._test_base64_upload("Big data" * 68000) # > 512Kb def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_unicode_file_name(self): with sys_tempfile.TemporaryDirectory() as temp_dir: # This file contains Chinese symbols and an accented char in the name. with open(os.path.join(temp_dir, UNICODE_FILENAME), 'w+b') as file1: file1.write(b'b' * (2 ** 10)) file1.seek(0) response = self.client.post('/unicode_name/', {'file_unicode': file1}) self.assertEqual(response.status_code, 200) def test_unicode_file_name_rfc2231(self): """ Test receiving file upload when filename is encoded with RFC2231 (#22971). """ payload = client.FakePayload() payload.write('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file_unicode"; filename*=UTF-8\'\'%s' % quote(UNICODE_FILENAME), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n', '\r\n--' + client.BOUNDARY + '--\r\n' ])) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/unicode_name/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_unicode_name_rfc2231(self): """ Test receiving file upload when filename is encoded with RFC2231 (#22971). """ payload = client.FakePayload() payload.write( '\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name*=UTF-8\'\'file_unicode; filename*=UTF-8\'\'%s' % quote( UNICODE_FILENAME ), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n', '\r\n--' + client.BOUNDARY + '--\r\n' ]) ) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/unicode_name/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_blank_filenames(self): """ Receiving file upload when filename is blank (before and after sanitization) should be okay. """ # The second value is normalized to an empty name by # MultiPartParser.IE_sanitize() filenames = ['', 'C:\\Windows\\'] payload = client.FakePayload() for i, name in enumerate(filenames): payload.write('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n' ])) payload.write('\r\n--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/echo/', 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) # Empty filenames should be ignored received = response.json() for i, name in enumerate(filenames): self.assertIsNone(received.get('file%s' % i)) def test_dangerous_file_names(self): """Uploaded file names should be sanitized before ever reaching the view.""" # This test simulates possible directory traversal attacks by a # malicious uploader We have to do some monkeybusiness here to construct # a malicious payload with an invalid file name (containing os.sep or # os.pardir). This similar to what an attacker would need to do when # trying such an attack. scary_file_names = [ "/tmp/hax0rd.txt", # Absolute path, *nix-style. "C:\\Windows\\hax0rd.txt", # Absolute path, win-style. "C:/Windows/hax0rd.txt", # Absolute path, broken-style. "\\tmp\\hax0rd.txt", # Absolute path, broken in a different way. "/tmp\\hax0rd.txt", # Absolute path, broken by mixing. "subdir/hax0rd.txt", # Descendant path, *nix-style. "subdir\\hax0rd.txt", # Descendant path, win-style. "sub/dir\\hax0rd.txt", # Descendant path, mixed. "../../hax0rd.txt", # Relative path, *nix-style. "..\\..\\hax0rd.txt", # Relative path, win-style. "../..\\hax0rd.txt" # Relative path, mixed. ] payload = client.FakePayload() for i, name in enumerate(scary_file_names): payload.write('\r\n'.join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name), 'Content-Type: application/octet-stream', '', 'You got pwnd.\r\n' ])) payload.write('\r\n--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/echo/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) # The filenames should have been sanitized by the time it got to the view. received = response.json() for i, name in enumerate(scary_file_names): got = received["file%s" % i] self.assertEqual(got, "hax0rd.txt") def test_filename_overflow(self): """File names over 256 characters (dangerous on some platforms) get fixed up.""" long_str = 'f' * 300 cases = [ # field name, filename, expected ('long_filename', '%s.txt' % long_str, '%s.txt' % long_str[:251]), ('long_extension', 'foo.%s' % long_str, '.%s' % long_str[:254]), ('no_extension', long_str, long_str[:255]), ('no_filename', '.%s' % long_str, '.%s' % long_str[:254]), ('long_everything', '%s.%s' % (long_str, long_str), '.%s' % long_str[:254]), ] payload = client.FakePayload() for name, filename, _ in cases: payload.write("\r\n".join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="{}"; filename="{}"', 'Content-Type: application/octet-stream', '', 'Oops.', '' ]).format(name, filename)) payload.write('\r\n--' + client.BOUNDARY + '--\r\n') r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': "/echo/", 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } response = self.client.request(**r) result = response.json() for name, _, expected in cases: got = result[name] self.assertEqual(expected, got, 'Mismatch for {}'.format(name)) self.assertLess(len(got), 256, "Got a long file name (%s characters)." % len(got)) def test_file_content(self): file = tempfile.NamedTemporaryFile with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file: no_content_type.write(b'no content') no_content_type.seek(0) simple_file.write(b'text content') simple_file.seek(0) simple_file.content_type = 'text/plain' string_io = StringIO('string content') bytes_io = BytesIO(b'binary content') response = self.client.post('/echo_content/', { 'no_content_type': no_content_type, 'simple_file': simple_file, 'string': string_io, 'binary': bytes_io, }) received = response.json() self.assertEqual(received['no_content_type'], 'no content') self.assertEqual(received['simple_file'], 'text content') self.assertEqual(received['string'], 'string content') self.assertEqual(received['binary'], 'binary content') def test_content_type_extra(self): """Uploaded files may have content type parameters available.""" file = tempfile.NamedTemporaryFile with file(suffix=".ctype_extra") as no_content_type, file(suffix=".ctype_extra") as simple_file: no_content_type.write(b'something') no_content_type.seek(0) simple_file.write(b'something') simple_file.seek(0) simple_file.content_type = 'text/plain; test-key=test_value' response = self.client.post('/echo_content_type_extra/', { 'no_content_type': no_content_type, 'simple_file': simple_file, }) received = response.json() self.assertEqual(received['no_content_type'], {}) self.assertEqual(received['simple_file'], {'test-key': 'test_value'}) def test_truncated_multipart_handled_gracefully(self): """ If passed an incomplete multipart message, MultiPartParser does not attempt to read beyond the end of the stream, and simply will handle the part that can be parsed gracefully. """ payload_str = "\r\n".join([ '--' + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="foo.txt"', 'Content-Type: application/octet-stream', '', 'file contents' '--' + client.BOUNDARY + '--', '', ]) payload = client.FakePayload(payload_str[:-10]) r = { 'CONTENT_LENGTH': len(payload), 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/echo/', 'REQUEST_METHOD': 'POST', 'wsgi.input': payload, } self.assertEqual(self.client.request(**r).json(), {}) def test_empty_multipart_handled_gracefully(self): """ If passed an empty multipart message, MultiPartParser will return an empty QueryDict. """ r = { 'CONTENT_LENGTH': 0, 'CONTENT_TYPE': client.MULTIPART_CONTENT, 'PATH_INFO': '/echo/', 'REQUEST_METHOD': 'POST', 'wsgi.input': client.FakePayload(b''), } self.assertEqual(self.client.request(**r).json(), {}) def test_custom_upload_handler(self): file = tempfile.NamedTemporaryFile with file() as smallfile, file() as bigfile: # A small file (under the 5M quota) smallfile.write(b'a' * (2 ** 21)) smallfile.seek(0) # A big file (over the quota) bigfile.write(b'a' * (10 * 2 ** 20)) bigfile.seek(0) # Small file posting should work. self.assertIn('f', self.client.post('/quota/', {'f': smallfile}).json()) # Large files don't go through. self.assertNotIn('f', self.client.post("/quota/", {'f': bigfile}).json()) def test_broken_custom_upload_handler(self): with tempfile.NamedTemporaryFile() as file: file.write(b'a' * (2 ** 21)) file.seek(0) msg = 'You cannot alter upload handlers after the upload has been processed.' with self.assertRaisesMessage(AttributeError, msg): self.client.post('/quota/broken/', {'f': file}) def test_fileupload_getlist(self): file = tempfile.NamedTemporaryFile with file() as file1, file() as file2, file() as file2a: file1.write(b'a' * (2 ** 23)) file1.seek(0) file2.write(b'a' * (2 * 2 ** 18)) file2.seek(0) file2a.write(b'a' * (5 * 2 ** 20)) file2a.seek(0) response = self.client.post('/getlist_count/', { 'file1': file1, 'field1': 'test', 'field2': 'test3', 'field3': 'test5', 'field4': 'test6', 'field5': 'test7', 'file2': (file2, file2a) }) got = response.json() self.assertEqual(got.get('file1'), 1) self.assertEqual(got.get('file2'), 2) def test_fileuploads_closed_at_request_end(self): file = tempfile.NamedTemporaryFile with file() as f1, file() as f2a, file() as f2b: response = self.client.post('/fd_closing/t/', { 'file': f1, 'file2': (f2a, f2b), }) request = response.wsgi_request # The files were parsed. self.assertTrue(hasattr(request, '_files')) file = request._files['file'] self.assertTrue(file.closed) files = request._files.getlist('file2') self.assertTrue(files[0].closed) self.assertTrue(files[1].closed) def test_no_parsing_triggered_by_fd_closing(self): file = tempfile.NamedTemporaryFile with file() as f1, file() as f2a, file() as f2b: response = self.client.post('/fd_closing/f/', { 'file': f1, 'file2': (f2a, f2b), }) request = response.wsgi_request # The fd closing logic doesn't trigger parsing of the stream self.assertFalse(hasattr(request, '_files')) def test_file_error_blocking(self): """ The server should not block when there are upload errors (bug #8622). This can happen if something -- i.e. an exception handler -- tries to access POST while handling an error in parsing POST. This shouldn't cause an infinite loop! """ class POSTAccessingHandler(client.ClientHandler): """A handler that'll access POST during an exception.""" def handle_uncaught_exception(self, request, resolver, exc_info): ret = super().handle_uncaught_exception(request, resolver, exc_info) request.POST # evaluate return ret # Maybe this is a little more complicated that it needs to be; but if # the django.test.client.FakePayload.read() implementation changes then # this test would fail. So we need to know exactly what kind of error # it raises when there is an attempt to read more than the available bytes: try: client.FakePayload(b'a').read(2) except Exception as err: reference_error = err # install the custom handler that tries to access request.POST self.client.handler = POSTAccessingHandler() with open(__file__, 'rb') as fp: post_data = { 'name': 'Ringo', 'file_field': fp, } try: self.client.post('/upload_errors/', post_data) except reference_error.__class__ as err: self.assertFalse( str(err) == str(reference_error), "Caught a repeated exception that'll cause an infinite loop in file uploads." ) except Exception as err: # CustomUploadError is the error that should have been raised self.assertEqual(err.__class__, uploadhandler.CustomUploadError) def test_filename_case_preservation(self): """ The storage backend shouldn't mess with the case of the filenames uploaded. """ # Synthesize the contents of a file upload with a mixed case filename # so we don't have to carry such a file in the Django tests source code # tree. vars = {'boundary': 'oUrBoUnDaRyStRiNg'} post_data = [ '--%(boundary)s', 'Content-Disposition: form-data; name="file_field"; filename="MiXeD_cAsE.txt"', 'Content-Type: application/octet-stream', '', 'file contents\n' '', '--%(boundary)s--\r\n', ] response = self.client.post( '/filename_case/', '\r\n'.join(post_data) % vars, 'multipart/form-data; boundary=%(boundary)s' % vars ) self.assertEqual(response.status_code, 200) id = int(response.content) obj = FileModel.objects.get(pk=id) # The name of the file uploaded and the file stored in the server-side # shouldn't differ. self.assertEqual(os.path.basename(obj.testfile.path), 'MiXeD_cAsE.txt') @override_settings(MEDIA_ROOT=MEDIA_ROOT) class DirectoryCreationTests(SimpleTestCase): """ Tests for error handling during directory creation via _save_FIELD_file (ticket #6450) """ @classmethod def setUpClass(cls): super().setUpClass() os.makedirs(MEDIA_ROOT, exist_ok=True) @classmethod def tearDownClass(cls): shutil.rmtree(MEDIA_ROOT) super().tearDownClass() def setUp(self): self.obj = FileModel() @unittest.skipIf(sys.platform == 'win32', "Python on Windows doesn't have working os.chmod().") def test_readonly_root(self): """Permission errors are not swallowed""" os.chmod(MEDIA_ROOT, 0o500) self.addCleanup(os.chmod, MEDIA_ROOT, 0o700) with self.assertRaises(PermissionError): self.obj.testfile.save('foo.txt', SimpleUploadedFile('foo.txt', b'x'), save=False) def test_not_a_directory(self): # Create a file with the upload directory name open(UPLOAD_TO, 'wb').close() self.addCleanup(os.remove, UPLOAD_TO) msg = '%s exists and is not a directory.' % UPLOAD_TO with self.assertRaisesMessage(FileExistsError, msg): with SimpleUploadedFile('foo.txt', b'x') as file: self.obj.testfile.save('foo.txt', file, save=False) class MultiParserTests(SimpleTestCase): def test_empty_upload_handlers(self): # We're not actually parsing here; just checking if the parser properly # instantiates with empty upload handlers. MultiPartParser({ 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo', 'CONTENT_LENGTH': '1' }, StringIO('x'), [], 'utf-8') def test_invalid_content_type(self): with self.assertRaisesMessage(MultiPartParserError, 'Invalid Content-Type: text/plain'): MultiPartParser({ 'CONTENT_TYPE': 'text/plain', 'CONTENT_LENGTH': '1', }, StringIO('x'), [], 'utf-8') def test_negative_content_length(self): with self.assertRaisesMessage(MultiPartParserError, 'Invalid content length: -1'): MultiPartParser({ 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo', 'CONTENT_LENGTH': -1, }, StringIO('x'), [], 'utf-8') def test_bad_type_content_length(self): multipart_parser = MultiPartParser({ 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo', 'CONTENT_LENGTH': 'a', }, StringIO('x'), [], 'utf-8') self.assertEqual(multipart_parser._content_length, 0) def test_rfc2231_parsing(self): test_data = ( (b"Content-Type: application/x-stuff; title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A", "This is ***fun***"), (b"Content-Type: application/x-stuff; title*=UTF-8''foo-%c3%a4.html", "foo-ä.html"), (b"Content-Type: application/x-stuff; title*=iso-8859-1''foo-%E4.html", "foo-ä.html"), ) for raw_line, expected_title in test_data: parsed = parse_header(raw_line) self.assertEqual(parsed[1]['title'], expected_title) def test_rfc2231_wrong_title(self): """ Test wrongly formatted RFC 2231 headers (missing double single quotes). Parsing should not crash (#24209). """ test_data = ( (b"Content-Type: application/x-stuff; title*='This%20is%20%2A%2A%2Afun%2A%2A%2A", b"'This%20is%20%2A%2A%2Afun%2A%2A%2A"), (b"Content-Type: application/x-stuff; title*='foo.html", b"'foo.html"), (b"Content-Type: application/x-stuff; title*=bar.html", b"bar.html"), ) for raw_line, expected_title in test_data: parsed = parse_header(raw_line) self.assertEqual(parsed[1]['title'], expected_title)
8d285a42a9acc55cbccae06b9c2287b60b41d07e7e71b3d143e87f8fccbc44ff
from django.urls import path, re_path from . import views urlpatterns = [ path('upload/', views.file_upload_view), path('verify/', views.file_upload_view_verify), path('unicode_name/', views.file_upload_unicode_name), path('echo/', views.file_upload_echo), path('echo_content_type_extra/', views.file_upload_content_type_extra), path('echo_content/', views.file_upload_echo_content), path('quota/', views.file_upload_quota), path('quota/broken/', views.file_upload_quota_broken), path('getlist_count/', views.file_upload_getlist_count), path('upload_errors/', views.file_upload_errors), path('filename_case/', views.file_upload_filename_case_view), re_path(r'^fd_closing/(?P<access>t|f)/$', views.file_upload_fd_closing), ]
709738464b09354b42c52ee800e6d7417b69574ed74d22a0f52876eb5590275a
import hashlib import os from django.core.files.uploadedfile import UploadedFile from django.http import HttpResponse, HttpResponseServerError, JsonResponse from .models import FileModel from .tests import UNICODE_FILENAME, UPLOAD_TO from .uploadhandler import ErroringUploadHandler, QuotaUploadHandler def file_upload_view(request): """ A file upload can be updated into the POST dictionary. """ form_data = request.POST.copy() form_data.update(request.FILES) if isinstance(form_data.get('file_field'), UploadedFile) and isinstance(form_data['name'], str): # If a file is posted, the dummy client should only post the file name, # not the full path. if os.path.dirname(form_data['file_field'].name) != '': return HttpResponseServerError() return HttpResponse() else: return HttpResponseServerError() def file_upload_view_verify(request): """ Use the sha digest hash to verify the uploaded contents. """ form_data = request.POST.copy() form_data.update(request.FILES) for key, value in form_data.items(): if key.endswith('_hash'): continue if key + '_hash' not in form_data: continue submitted_hash = form_data[key + '_hash'] if isinstance(value, UploadedFile): new_hash = hashlib.sha1(value.read()).hexdigest() else: new_hash = hashlib.sha1(value.encode()).hexdigest() if new_hash != submitted_hash: return HttpResponseServerError() # Adding large file to the database should succeed largefile = request.FILES['file_field2'] obj = FileModel() obj.testfile.save(largefile.name, largefile) return HttpResponse() def file_upload_unicode_name(request): # Check to see if unicode name came through properly. if not request.FILES['file_unicode'].name.endswith(UNICODE_FILENAME): return HttpResponseServerError() # Check to make sure the exotic characters are preserved even # through file save. uni_named_file = request.FILES['file_unicode'] FileModel.objects.create(testfile=uni_named_file) full_name = '%s/%s' % (UPLOAD_TO, uni_named_file.name) return HttpResponse() if os.path.exists(full_name) else HttpResponseServerError() def file_upload_echo(request): """ Simple view to echo back info about uploaded files for tests. """ r = {k: f.name for k, f in request.FILES.items()} return JsonResponse(r) def file_upload_echo_content(request): """ Simple view to echo back the content of uploaded files for tests. """ def read_and_close(f): with f: return f.read().decode() r = {k: read_and_close(f) for k, f in request.FILES.items()} return JsonResponse(r) def file_upload_quota(request): """ Dynamically add in an upload handler. """ request.upload_handlers.insert(0, QuotaUploadHandler()) return file_upload_echo(request) def file_upload_quota_broken(request): """ You can't change handlers after reading FILES; this view shouldn't work. """ response = file_upload_echo(request) request.upload_handlers.insert(0, QuotaUploadHandler()) return response def file_upload_getlist_count(request): """ Check the .getlist() function to ensure we receive the correct number of files. """ file_counts = {} for key in request.FILES: file_counts[key] = len(request.FILES.getlist(key)) return JsonResponse(file_counts) def file_upload_errors(request): request.upload_handlers.insert(0, ErroringUploadHandler()) return file_upload_echo(request) def file_upload_filename_case_view(request): """ Check adding the file to the database will preserve the filename case. """ file = request.FILES['file_field'] obj = FileModel() obj.testfile.save(file.name, file) return HttpResponse('%d' % obj.pk) def file_upload_content_type_extra(request): """ Simple view to echo back extra content-type parameters. """ params = {} for file_name, uploadedfile in request.FILES.items(): params[file_name] = {k: v.decode() for k, v in uploadedfile.content_type_extra.items()} return JsonResponse(params) def file_upload_fd_closing(request, access): if access == 't': request.FILES # Trigger file parsing. return HttpResponse()
7fc2e55e18f8924906dfa90138c4922b5afc5eeeffe169c31549604881b6a035
from django.contrib.flatpages.sitemaps import FlatPageSitemap from django.contrib.sitemaps import views from django.urls import include, path urlpatterns = [ path( 'flatpages/sitemap.xml', views.sitemap, {'sitemaps': {'flatpages': FlatPageSitemap}}, name='django.contrib.sitemaps.views.sitemap'), path('flatpage_root', include('django.contrib.flatpages.urls')), path('accounts/', include('django.contrib.auth.urls')), ]
ca95efe9c3ab847af6248f01a8ee47c61c28f9bf4be788c67c882e740b981679
from django.conf import settings from django.contrib.flatpages.forms import FlatpageForm from django.contrib.flatpages.models import FlatPage from django.contrib.sites.models import Site from django.test import TestCase, modify_settings, override_settings from django.utils import translation @modify_settings(INSTALLED_APPS={'append': ['django.contrib.flatpages']}) @override_settings(SITE_ID=1) class FlatpageAdminFormTests(TestCase): @classmethod def setUpTestData(cls): # don't use the manager because we want to ensure the site exists # with pk=1, regardless of whether or not it already exists. cls.site1 = Site(pk=1, domain='example.com', name='example.com') cls.site1.save() def setUp(self): # Site fields cache needs to be cleared after flatpages is added to # INSTALLED_APPS Site._meta._expire_cache() self.form_data = { 'title': "A test page", 'content': "This is a test", 'sites': [settings.SITE_ID], } def test_flatpage_admin_form_url_validation(self): "The flatpage admin form correctly validates urls" self.assertTrue(FlatpageForm(data=dict(url='/new_flatpage/', **self.form_data)).is_valid()) self.assertTrue(FlatpageForm(data=dict(url='/some.special~chars/', **self.form_data)).is_valid()) self.assertTrue(FlatpageForm(data=dict(url='/some.very_special~chars-here/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a space/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a % char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a ! char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a & char/', **self.form_data)).is_valid()) self.assertFalse(FlatpageForm(data=dict(url='/a ? char/', **self.form_data)).is_valid()) def test_flatpage_requires_leading_slash(self): form = FlatpageForm(data=dict(url='no_leading_slash/', **self.form_data)) with translation.override('en'): self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a leading slash."]) @override_settings(APPEND_SLASH=True, MIDDLEWARE=['django.middleware.common.CommonMiddleware']) def test_flatpage_requires_trailing_slash_with_append_slash(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) with translation.override('en'): self.assertEqual( form.fields['url'].help_text, "Example: '/about/contact/'. Make sure to have leading and " "trailing slashes." ) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['url'], ["URL is missing a trailing slash."]) @override_settings(APPEND_SLASH=False, MIDDLEWARE=['django.middleware.common.CommonMiddleware']) def test_flatpage_doesnt_requires_trailing_slash_without_append_slash(self): form = FlatpageForm(data=dict(url='/no_trailing_slash', **self.form_data)) self.assertTrue(form.is_valid()) with translation.override('en'): self.assertEqual( form.fields['url'].help_text, "Example: '/about/contact'. Make sure to have a leading slash." ) def test_flatpage_admin_form_url_uniqueness_validation(self): "The flatpage admin form correctly enforces url uniqueness among flatpages of the same site" data = dict(url='/myflatpage1/', **self.form_data) FlatpageForm(data=data).save() f = FlatpageForm(data=data) with translation.override('en'): self.assertFalse(f.is_valid()) self.assertEqual( f.errors, {'__all__': ['Flatpage with url /myflatpage1/ already exists for site example.com']}) def test_flatpage_admin_form_edit(self): """ Existing flatpages can be edited in the admin form without triggering the url-uniqueness validation. """ existing = FlatPage.objects.create( url="/myflatpage1/", title="Some page", content="The content") existing.sites.add(settings.SITE_ID) data = dict(url='/myflatpage1/', **self.form_data) f = FlatpageForm(data=data, instance=existing) self.assertTrue(f.is_valid(), f.errors) updated = f.save() self.assertEqual(updated.title, "A test page") def test_flatpage_nosites(self): data = dict(url='/myflatpage1/', **self.form_data) data.update({'sites': ''}) f = FlatpageForm(data=data) self.assertFalse(f.is_valid()) self.assertEqual(f.errors, {'sites': [translation.gettext('This field is required.')]})
4469abc0b70df6db40d3f8dbc5fc1cdf7e938973f6d7bd592ea3d37d4d56251d
import datetime import os from decimal import Decimal from unittest import mock, skipUnless from django import forms from django.core.exceptions import ( NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ) from django.core.files.uploadedfile import SimpleUploadedFile from django.core.validators import ValidationError from django.db import connection, models from django.db.models.query import EmptyQuerySet from django.forms.models import ( ModelFormMetaclass, construct_instance, fields_for_model, model_to_dict, modelform_factory, ) from django.template import Context, Template from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from .models import ( Article, ArticleStatus, Author, Author1, Award, BetterWriter, BigInt, Book, Category, Character, Colour, ColourfulItem, CustomErrorMessage, CustomFF, CustomFieldForExclusionModel, DateTimePost, DerivedBook, DerivedPost, Document, ExplicitPK, FilePathModel, FlexibleDatePost, Homepage, ImprovedArticle, ImprovedArticleWithParentLink, Inventory, NullableUniqueCharFieldModel, Person, Photo, Post, Price, Product, Publication, PublicationDefaults, StrictAssignmentAll, StrictAssignmentFieldSpecific, Student, StumpJoke, TextFile, Triple, Writer, WriterProfile, test_images, ) if test_images: from .models import ImageFile, OptionalImageFile, NoExtensionImageFile class ImageFileForm(forms.ModelForm): class Meta: model = ImageFile fields = '__all__' class OptionalImageFileForm(forms.ModelForm): class Meta: model = OptionalImageFile fields = '__all__' class NoExtensionImageFileForm(forms.ModelForm): class Meta: model = NoExtensionImageFile fields = '__all__' class ProductForm(forms.ModelForm): class Meta: model = Product fields = '__all__' class PriceForm(forms.ModelForm): class Meta: model = Price fields = '__all__' class BookForm(forms.ModelForm): class Meta: model = Book fields = '__all__' class DerivedBookForm(forms.ModelForm): class Meta: model = DerivedBook fields = '__all__' class ExplicitPKForm(forms.ModelForm): class Meta: model = ExplicitPK fields = ('key', 'desc',) class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' class DerivedPostForm(forms.ModelForm): class Meta: model = DerivedPost fields = '__all__' class CustomWriterForm(forms.ModelForm): name = forms.CharField(required=False) class Meta: model = Writer fields = '__all__' class BaseCategoryForm(forms.ModelForm): class Meta: model = Category fields = '__all__' class ArticleForm(forms.ModelForm): class Meta: model = Article fields = '__all__' class RoykoForm(forms.ModelForm): class Meta: model = Writer fields = '__all__' class ArticleStatusForm(forms.ModelForm): class Meta: model = ArticleStatus fields = '__all__' class InventoryForm(forms.ModelForm): class Meta: model = Inventory fields = '__all__' class SelectInventoryForm(forms.Form): items = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode') class CustomFieldForExclusionForm(forms.ModelForm): class Meta: model = CustomFieldForExclusionModel fields = ['name', 'markup'] class TextFileForm(forms.ModelForm): class Meta: model = TextFile fields = '__all__' class BigIntForm(forms.ModelForm): class Meta: model = BigInt fields = '__all__' class ModelFormWithMedia(forms.ModelForm): class Media: js = ('/some/form/javascript',) css = { 'all': ('/some/form/css',) } class Meta: model = TextFile fields = '__all__' class CustomErrorMessageForm(forms.ModelForm): name1 = forms.CharField(error_messages={'invalid': 'Form custom error message.'}) class Meta: fields = '__all__' model = CustomErrorMessage class ModelFormBaseTest(TestCase): def test_base_form(self): self.assertEqual(list(BaseCategoryForm.base_fields), ['name', 'slug', 'url']) def test_no_model_class(self): class NoModelModelForm(forms.ModelForm): pass with self.assertRaisesMessage(ValueError, 'ModelForm has no model class specified.'): NoModelModelForm() def test_empty_fields_to_fields_for_model(self): """ An argument of fields=() to fields_for_model should return an empty dictionary """ field_dict = fields_for_model(Person, fields=()) self.assertEqual(len(field_dict), 0) def test_empty_fields_on_modelform(self): """ No fields on a ModelForm should actually result in no fields. """ class EmptyPersonForm(forms.ModelForm): class Meta: model = Person fields = () form = EmptyPersonForm() self.assertEqual(len(form.fields), 0) def test_empty_fields_to_construct_instance(self): """ No fields should be set on a model instance if construct_instance receives fields=(). """ form = modelform_factory(Person, fields="__all__")({'name': 'John Doe'}) self.assertTrue(form.is_valid()) instance = construct_instance(form, Person(), fields=()) self.assertEqual(instance.name, '') def test_blank_with_null_foreign_key_field(self): """ #13776 -- ModelForm's with models having a FK set to null=False and required=False should be valid. """ class FormForTestingIsValid(forms.ModelForm): class Meta: model = Student fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['character'].required = False char = Character.objects.create(username='user', last_action=datetime.datetime.today()) data = {'study': 'Engineering'} data2 = {'study': 'Engineering', 'character': char.pk} # form is valid because required=False for field 'character' f1 = FormForTestingIsValid(data) self.assertTrue(f1.is_valid()) f2 = FormForTestingIsValid(data2) self.assertTrue(f2.is_valid()) obj = f2.save() self.assertEqual(obj.character, char) def test_blank_false_with_null_true_foreign_key_field(self): """ A ModelForm with a model having ForeignKey(blank=False, null=True) and the form field set to required=False should allow the field to be unset. """ class AwardForm(forms.ModelForm): class Meta: model = Award fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['character'].required = False character = Character.objects.create(username='user', last_action=datetime.datetime.today()) award = Award.objects.create(name='Best sprinter', character=character) data = {'name': 'Best tester', 'character': ''} # remove character form = AwardForm(data=data, instance=award) self.assertTrue(form.is_valid()) award = form.save() self.assertIsNone(award.character) def test_save_blank_false_with_required_false(self): """ A ModelForm with a model with a field set to blank=False and the form field set to required=False should allow the field to be unset. """ obj = Writer.objects.create(name='test') form = CustomWriterForm(data={'name': ''}, instance=obj) self.assertTrue(form.is_valid()) obj = form.save() self.assertEqual(obj.name, '') def test_save_blank_null_unique_charfield_saves_null(self): form_class = modelform_factory(model=NullableUniqueCharFieldModel, fields=['codename']) empty_value = '' if connection.features.interprets_empty_strings_as_nulls else None form = form_class(data={'codename': ''}) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.instance.codename, empty_value) # Save a second form to verify there isn't a unique constraint violation. form = form_class(data={'codename': ''}) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.instance.codename, empty_value) def test_missing_fields_attribute(self): message = ( "Creating a ModelForm without either the 'fields' attribute " "or the 'exclude' attribute is prohibited; form " "MissingFieldsForm needs updating." ) with self.assertRaisesMessage(ImproperlyConfigured, message): class MissingFieldsForm(forms.ModelForm): class Meta: model = Category def test_extra_fields(self): class ExtraFields(BaseCategoryForm): some_extra_field = forms.BooleanField() self.assertEqual(list(ExtraFields.base_fields), ['name', 'slug', 'url', 'some_extra_field']) def test_extra_field_model_form(self): with self.assertRaisesMessage(FieldError, 'no-field'): class ExtraPersonForm(forms.ModelForm): """ ModelForm with an extra field """ age = forms.IntegerField() class Meta: model = Person fields = ('name', 'no-field') def test_extra_declared_field_model_form(self): class ExtraPersonForm(forms.ModelForm): """ ModelForm with an extra field """ age = forms.IntegerField() class Meta: model = Person fields = ('name', 'age') def test_extra_field_modelform_factory(self): with self.assertRaisesMessage(FieldError, 'Unknown field(s) (no-field) specified for Person'): modelform_factory(Person, fields=['no-field', 'name']) def test_replace_field(self): class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = '__all__' self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_replace_field_variant_2(self): # Should have the same result as before, # but 'fields' attribute specified differently class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = ['url'] self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_replace_field_variant_3(self): # Should have the same result as before, # but 'fields' attribute specified differently class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = [] # url will still appear, since it is explicit above self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) def test_override_field(self): class WriterForm(forms.ModelForm): book = forms.CharField(required=False) class Meta: model = Writer fields = '__all__' wf = WriterForm({'name': 'Richard Lockridge'}) self.assertTrue(wf.is_valid()) def test_limit_nonexistent_field(self): expected_msg = 'Unknown field(s) (nonexistent) specified for Category' with self.assertRaisesMessage(FieldError, expected_msg): class InvalidCategoryForm(forms.ModelForm): class Meta: model = Category fields = ['nonexistent'] def test_limit_fields_with_string(self): expected_msg = "CategoryForm.Meta.fields cannot be a string. Did you mean to type: ('url',)?" with self.assertRaisesMessage(TypeError, expected_msg): class CategoryForm(forms.ModelForm): class Meta: model = Category fields = ('url') # note the missing comma def test_exclude_fields(self): class ExcludeFields(forms.ModelForm): class Meta: model = Category exclude = ['url'] self.assertEqual(list(ExcludeFields.base_fields), ['name', 'slug']) def test_exclude_nonexistent_field(self): class ExcludeFields(forms.ModelForm): class Meta: model = Category exclude = ['nonexistent'] self.assertEqual(list(ExcludeFields.base_fields), ['name', 'slug', 'url']) def test_exclude_fields_with_string(self): expected_msg = "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: ('url',)?" with self.assertRaisesMessage(TypeError, expected_msg): class CategoryForm(forms.ModelForm): class Meta: model = Category exclude = ('url') # note the missing comma def test_exclude_and_validation(self): # This Price instance generated by this form is not valid because the quantity # field is required, but the form is valid because the field is excluded from # the form. This is for backwards compatibility. class PriceFormWithoutQuantity(forms.ModelForm): class Meta: model = Price exclude = ('quantity',) form = PriceFormWithoutQuantity({'price': '6.00'}) self.assertTrue(form.is_valid()) price = form.save(commit=False) msg = "{'quantity': ['This field cannot be null.']}" with self.assertRaisesMessage(ValidationError, msg): price.full_clean() # The form should not validate fields that it doesn't contain even if they are # specified using 'fields', not 'exclude'. class PriceFormWithoutQuantity(forms.ModelForm): class Meta: model = Price fields = ('price',) form = PriceFormWithoutQuantity({'price': '6.00'}) self.assertTrue(form.is_valid()) # The form should still have an instance of a model that is not complete and # not saved into a DB yet. self.assertEqual(form.instance.price, Decimal('6.00')) self.assertIsNone(form.instance.quantity) self.assertIsNone(form.instance.pk) def test_confused_form(self): class ConfusedForm(forms.ModelForm): """ Using 'fields' *and* 'exclude'. Not sure why you'd want to do this, but uh, "be liberal in what you accept" and all. """ class Meta: model = Category fields = ['name', 'url'] exclude = ['url'] self.assertEqual(list(ConfusedForm.base_fields), ['name']) def test_mixmodel_form(self): class MixModelForm(BaseCategoryForm): """ Don't allow more than one 'model' definition in the inheritance hierarchy. Technically, it would generate a valid form, but the fact that the resulting save method won't deal with multiple objects is likely to trip up people not familiar with the mechanics. """ class Meta: model = Article fields = '__all__' # MixModelForm is now an Article-related thing, because MixModelForm.Meta # overrides BaseCategoryForm.Meta. self.assertEqual( list(MixModelForm.base_fields), ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status'] ) def test_article_form(self): self.assertEqual( list(ArticleForm.base_fields), ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status'] ) def test_bad_form(self): # First class with a Meta class wins... class BadForm(ArticleForm, BaseCategoryForm): pass self.assertEqual( list(BadForm.base_fields), ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status'] ) def test_invalid_meta_model(self): class InvalidModelForm(forms.ModelForm): class Meta: pass # no model # Can't create new form msg = 'ModelForm has no model class specified.' with self.assertRaisesMessage(ValueError, msg): InvalidModelForm() # Even if you provide a model instance with self.assertRaisesMessage(ValueError, msg): InvalidModelForm(instance=Category) def test_subcategory_form(self): class SubCategoryForm(BaseCategoryForm): """ Subclassing without specifying a Meta on the class will use the parent's Meta (or the first parent in the MRO if there are multiple parent classes). """ pass self.assertEqual(list(SubCategoryForm.base_fields), ['name', 'slug', 'url']) def test_subclassmeta_form(self): class SomeCategoryForm(forms.ModelForm): checkbox = forms.BooleanField() class Meta: model = Category fields = '__all__' class SubclassMeta(SomeCategoryForm): """ We can also subclass the Meta inner class to change the fields list. """ class Meta(SomeCategoryForm.Meta): exclude = ['url'] self.assertHTMLEqual( str(SubclassMeta()), """<tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="20" required></td></tr> <tr><th><label for="id_slug">Slug:</label></th> <td><input id="id_slug" type="text" name="slug" maxlength="20" required></td></tr> <tr><th><label for="id_checkbox">Checkbox:</label></th> <td><input type="checkbox" name="checkbox" id="id_checkbox" required></td></tr>""" ) def test_orderfields_form(self): class OrderFields(forms.ModelForm): class Meta: model = Category fields = ['url', 'name'] self.assertEqual(list(OrderFields.base_fields), ['url', 'name']) self.assertHTMLEqual( str(OrderFields()), """<tr><th><label for="id_url">The URL:</label></th> <td><input id="id_url" type="text" name="url" maxlength="40" required></td></tr> <tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="20" required></td></tr>""" ) def test_orderfields2_form(self): class OrderFields2(forms.ModelForm): class Meta: model = Category fields = ['slug', 'url', 'name'] exclude = ['url'] self.assertEqual(list(OrderFields2.base_fields), ['slug', 'name']) def test_default_populated_on_optional_field(self): class PubForm(forms.ModelForm): mode = forms.CharField(max_length=255, required=False) class Meta: model = PublicationDefaults fields = ('mode',) # Empty data uses the model field default. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, 'di') self.assertEqual(m1._meta.get_field('mode').get_default(), 'di') # Blank data doesn't use the model field default. mf2 = PubForm({'mode': ''}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.mode, '') def test_default_not_populated_on_non_empty_value_in_cleaned_data(self): class PubForm(forms.ModelForm): mode = forms.CharField(max_length=255, required=False) mocked_mode = None def clean(self): self.cleaned_data['mode'] = self.mocked_mode return self.cleaned_data class Meta: model = PublicationDefaults fields = ('mode',) pub_form = PubForm({}) pub_form.mocked_mode = 'de' pub = pub_form.save(commit=False) self.assertEqual(pub.mode, 'de') # Default should be populated on an empty value in cleaned_data. default_mode = 'di' for empty_value in pub_form.fields['mode'].empty_values: with self.subTest(empty_value=empty_value): pub_form = PubForm({}) pub_form.mocked_mode = empty_value pub = pub_form.save(commit=False) self.assertEqual(pub.mode, default_mode) def test_default_not_populated_on_optional_checkbox_input(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ('active',) # Empty data doesn't use the model default because CheckboxInput # doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertIs(m1.active, False) self.assertIsInstance(mf1.fields['active'].widget, forms.CheckboxInput) self.assertIs(m1._meta.get_field('active').get_default(), True) def test_default_not_populated_on_checkboxselectmultiple(self): class PubForm(forms.ModelForm): mode = forms.CharField(required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = PublicationDefaults fields = ('mode',) # Empty data doesn't use the model default because an unchecked # CheckboxSelectMultiple doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, '') self.assertEqual(m1._meta.get_field('mode').get_default(), 'di') def test_default_not_populated_on_selectmultiple(self): class PubForm(forms.ModelForm): mode = forms.CharField(required=False, widget=forms.SelectMultiple) class Meta: model = PublicationDefaults fields = ('mode',) # Empty data doesn't use the model default because an unselected # SelectMultiple doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, '') self.assertEqual(m1._meta.get_field('mode').get_default(), 'di') def test_prefixed_form_with_default_field(self): class PubForm(forms.ModelForm): prefix = 'form-prefix' class Meta: model = PublicationDefaults fields = ('mode',) mode = 'de' self.assertNotEqual(mode, PublicationDefaults._meta.get_field('mode').get_default()) mf1 = PubForm({'form-prefix-mode': mode}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, mode) def test_renderer_kwarg(self): custom = object() self.assertIs(ProductForm(renderer=custom).renderer, custom) def test_default_splitdatetime_field(self): class PubForm(forms.ModelForm): datetime_published = forms.SplitDateTimeField(required=False) class Meta: model = PublicationDefaults fields = ('datetime_published',) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.datetime_published, datetime.datetime(2000, 1, 1)) mf2 = PubForm({'datetime_published_0': '2010-01-01', 'datetime_published_1': '0:00:00'}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.datetime_published, datetime.datetime(2010, 1, 1)) def test_default_filefield(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ('file',) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.file.name, 'default.txt') mf2 = PubForm({}, {'file': SimpleUploadedFile('name', b'foo')}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.file.name, 'name') def test_default_selectdatewidget(self): class PubForm(forms.ModelForm): date_published = forms.DateField(required=False, widget=forms.SelectDateWidget) class Meta: model = PublicationDefaults fields = ('date_published',) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.date_published, datetime.date.today()) mf2 = PubForm({'date_published_year': '2010', 'date_published_month': '1', 'date_published_day': '1'}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.date_published, datetime.date(2010, 1, 1)) class FieldOverridesByFormMetaForm(forms.ModelForm): class Meta: model = Category fields = ['name', 'url', 'slug'] widgets = { 'name': forms.Textarea, 'url': forms.TextInput(attrs={'class': 'url'}) } labels = { 'name': 'Title', } help_texts = { 'slug': 'Watch out! Letters, numbers, underscores and hyphens only.', } error_messages = { 'slug': { 'invalid': ( "Didn't you read the help text? " "We said letters, numbers, underscores and hyphens only!" ) } } field_classes = { 'url': forms.URLField, } class TestFieldOverridesByFormMeta(SimpleTestCase): def test_widget_overrides(self): form = FieldOverridesByFormMetaForm() self.assertHTMLEqual( str(form['name']), '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" required></textarea>', ) self.assertHTMLEqual( str(form['url']), '<input id="id_url" type="text" class="url" name="url" maxlength="40" required>', ) self.assertHTMLEqual( str(form['slug']), '<input id="id_slug" type="text" name="slug" maxlength="20" required>', ) def test_label_overrides(self): form = FieldOverridesByFormMetaForm() self.assertHTMLEqual( str(form['name'].label_tag()), '<label for="id_name">Title:</label>', ) self.assertHTMLEqual( str(form['url'].label_tag()), '<label for="id_url">The URL:</label>', ) self.assertHTMLEqual( str(form['slug'].label_tag()), '<label for="id_slug">Slug:</label>', ) def test_help_text_overrides(self): form = FieldOverridesByFormMetaForm() self.assertEqual( form['slug'].help_text, 'Watch out! Letters, numbers, underscores and hyphens only.', ) def test_error_messages_overrides(self): form = FieldOverridesByFormMetaForm(data={ 'name': 'Category', 'url': 'http://www.example.com/category/', 'slug': '!%#*@', }) form.full_clean() error = [ "Didn't you read the help text? " "We said letters, numbers, underscores and hyphens only!", ] self.assertEqual(form.errors, {'slug': error}) def test_field_type_overrides(self): form = FieldOverridesByFormMetaForm() self.assertIs(Category._meta.get_field('url').__class__, models.CharField) self.assertIsInstance(form.fields['url'], forms.URLField) class IncompleteCategoryFormWithFields(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: fields = ('name', 'slug') model = Category class IncompleteCategoryFormWithExclude(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: exclude = ['url'] model = Category class ValidationTest(SimpleTestCase): def test_validates_with_replaced_field_not_specified(self): form = IncompleteCategoryFormWithFields(data={'name': 'some name', 'slug': 'some-slug'}) assert form.is_valid() def test_validates_with_replaced_field_excluded(self): form = IncompleteCategoryFormWithExclude(data={'name': 'some name', 'slug': 'some-slug'}) assert form.is_valid() def test_notrequired_overrides_notblank(self): form = CustomWriterForm({}) assert form.is_valid() class UniqueTest(TestCase): """ unique/unique_together validation. """ @classmethod def setUpTestData(cls): cls.writer = Writer.objects.create(name='Mike Royko') def test_simple_unique(self): form = ProductForm({'slug': 'teddy-bear-blue'}) self.assertTrue(form.is_valid()) obj = form.save() form = ProductForm({'slug': 'teddy-bear-blue'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ['Product with this Slug already exists.']) form = ProductForm({'slug': 'teddy-bear-blue'}, instance=obj) self.assertTrue(form.is_valid()) def test_unique_together(self): """ModelForm test of unique_together constraint""" form = PriceForm({'price': '6.00', 'quantity': '1'}) self.assertTrue(form.is_valid()) form.save() form = PriceForm({'price': '6.00', 'quantity': '1'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], ['Price with this Price and Quantity already exists.']) def test_unique_together_exclusion(self): """ Forms don't validate unique_together constraints when only part of the constraint is included in the form's fields. This allows using form.save(commit=False) and then assigning the missing field(s) to the model instance. """ class BookForm(forms.ModelForm): class Meta: model = DerivedBook fields = ('isbn', 'suffix1') # The unique_together is on suffix1/suffix2 but only suffix1 is part # of the form. The fields must have defaults, otherwise they'll be # skipped by other logic. self.assertEqual(DerivedBook._meta.unique_together, (('suffix1', 'suffix2'),)) for name in ('suffix1', 'suffix2'): with self.subTest(name=name): field = DerivedBook._meta.get_field(name) self.assertEqual(field.default, 0) # The form fails validation with "Derived book with this Suffix1 and # Suffix2 already exists." if the unique_together validation isn't # skipped. DerivedBook.objects.create(isbn='12345') form = BookForm({'isbn': '56789', 'suffix1': '0'}) self.assertTrue(form.is_valid(), form.errors) def test_multiple_field_unique_together(self): """ When the same field is involved in multiple unique_together constraints, we need to make sure we don't remove the data for it before doing all the validation checking (not just failing after the first one). """ class TripleForm(forms.ModelForm): class Meta: model = Triple fields = '__all__' Triple.objects.create(left=1, middle=2, right=3) form = TripleForm({'left': '1', 'middle': '2', 'right': '3'}) self.assertFalse(form.is_valid()) form = TripleForm({'left': '1', 'middle': '3', 'right': '1'}) self.assertTrue(form.is_valid()) @skipUnlessDBFeature('supports_nullable_unique_constraints') def test_unique_null(self): title = 'I May Be Wrong But I Doubt It' form = BookForm({'title': title, 'author': self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = BookForm({'title': title, 'author': self.writer.pk}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], ['Book with this Title and Author already exists.']) form = BookForm({'title': title}) self.assertTrue(form.is_valid()) form.save() form = BookForm({'title': title}) self.assertTrue(form.is_valid()) def test_inherited_unique(self): title = 'Boss' Book.objects.create(title=title, author=self.writer, special_id=1) form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'special_id': '1', 'isbn': '12345'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['special_id'], ['Book with this Special id already exists.']) def test_inherited_unique_together(self): title = 'Boss' form = BookForm({'title': title, 'author': self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = DerivedBookForm({'title': title, 'author': self.writer.pk, 'isbn': '12345'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['__all__'], ['Book with this Title and Author already exists.']) def test_abstract_inherited_unique(self): title = 'Boss' isbn = '12345' DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm({ 'title': 'Other', 'author': self.writer.pk, 'isbn': isbn, 'suffix1': '1', 'suffix2': '2', }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['isbn'], ['Derived book with this Isbn already exists.']) def test_abstract_inherited_unique_together(self): title = 'Boss' isbn = '12345' DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm({ 'title': 'Other', 'author': self.writer.pk, 'isbn': '9876', 'suffix1': '0', 'suffix2': '0' }) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors['__all__'], ['Derived book with this Suffix1 and Suffix2 already exists.'], ) def test_explicitpk_unspecified(self): """Test for primary_key being in the form and failing validation.""" form = ExplicitPKForm({'key': '', 'desc': ''}) self.assertFalse(form.is_valid()) def test_explicitpk_unique(self): """Ensure keys and blank character strings are tested for uniqueness.""" form = ExplicitPKForm({'key': 'key1', 'desc': ''}) self.assertTrue(form.is_valid()) form.save() form = ExplicitPKForm({'key': 'key1', 'desc': ''}) self.assertFalse(form.is_valid()) if connection.features.interprets_empty_strings_as_nulls: self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['key'], ['Explicit pk with this Key already exists.']) else: self.assertEqual(len(form.errors), 3) self.assertEqual(form.errors['__all__'], ['Explicit pk with this Key and Desc already exists.']) self.assertEqual(form.errors['desc'], ['Explicit pk with this Desc already exists.']) self.assertEqual(form.errors['key'], ['Explicit pk with this Key already exists.']) def test_unique_for_date(self): p = Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], ['Title must be unique for Posted date.']) form = PostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'}) self.assertTrue(form.is_valid()) form = PostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ['Slug must be unique for Posted year.']) form = PostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'} form = PostForm(data, instance=p) self.assertTrue(form.is_valid()) form = PostForm({'title': "Django 1.0 is released"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['posted'], ['This field is required.']) def test_unique_for_date_in_exclude(self): """ If the date for unique_for_* constraints is excluded from the ModelForm (in this case 'posted' has editable=False, then the constraint should be ignored. """ class DateTimePostForm(forms.ModelForm): class Meta: model = DateTimePost fields = '__all__' DateTimePost.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.datetime(2008, 9, 3, 10, 10, 1), ) # 'title' has unique_for_date='posted' form = DateTimePostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) # 'slug' has unique_for_year='posted' form = DateTimePostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertTrue(form.is_valid()) # 'subtitle' has unique_for_month='posted' form = DateTimePostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertTrue(form.is_valid()) def test_inherited_unique_for_date(self): p = Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], ['Title must be unique for Posted date.']) form = DerivedPostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'}) self.assertTrue(form.is_valid()) form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'}) self.assertTrue(form.is_valid()) form = DerivedPostForm({'slug': "Django 1.0", 'posted': '2008-01-01'}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ['Slug must be unique for Posted year.']) form = DerivedPostForm({'subtitle': "Finally", 'posted': '2008-09-30'}) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.']) data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", 'posted': '2008-09-03'} form = DerivedPostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_unique_for_date_with_nullable_date(self): class FlexDatePostForm(forms.ModelForm): class Meta: model = FlexibleDatePost fields = '__all__' p = FlexibleDatePost.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = FlexDatePostForm({'title': "Django 1.0 is released"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({'slug': "Django 1.0"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({'subtitle': "Finally"}) self.assertTrue(form.is_valid()) data = {'subtitle': "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0"} form = FlexDatePostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_override_unique_message(self): class CustomProductForm(ProductForm): class Meta(ProductForm.Meta): error_messages = { 'slug': { 'unique': "%(model_name)s's %(field_label)s not unique.", } } Product.objects.create(slug='teddy-bear-blue') form = CustomProductForm({'slug': 'teddy-bear-blue'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['slug'], ["Product's Slug not unique."]) def test_override_unique_together_message(self): class CustomPriceForm(PriceForm): class Meta(PriceForm.Meta): error_messages = { NON_FIELD_ERRORS: { 'unique_together': "%(model_name)s's %(field_labels)s not unique.", } } Price.objects.create(price=6.00, quantity=1) form = CustomPriceForm({'price': '6.00', 'quantity': '1'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors[NON_FIELD_ERRORS], ["Price's Price and Quantity not unique."]) def test_override_unique_for_date_message(self): class CustomPostForm(PostForm): class Meta(PostForm.Meta): error_messages = { 'title': { 'unique_for_date': ( "%(model_name)s's %(field_label)s not unique " "for %(date_field_label)s date." ), } } Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = CustomPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors['title'], ["Post's Title not unique for Posted date."]) class ModelFormBasicTests(TestCase): def create_basic_data(self): self.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment') self.c2 = Category.objects.create(name="It's a test", slug='its-test', url='test') self.c3 = Category.objects.create(name='Third test', slug='third-test', url='third') self.w_royko = Writer.objects.create(name='Mike Royko') self.w_woodward = Writer.objects.create(name='Bob Woodward') def test_base_form(self): self.assertEqual(Category.objects.count(), 0) f = BaseCategoryForm() self.assertHTMLEqual( str(f), """<tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="20" required></td></tr> <tr><th><label for="id_slug">Slug:</label></th> <td><input id="id_slug" type="text" name="slug" maxlength="20" required></td></tr> <tr><th><label for="id_url">The URL:</label></th> <td><input id="id_url" type="text" name="url" maxlength="40" required></td></tr>""" ) self.assertHTMLEqual( str(f.as_ul()), """<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" required></li> <li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" required></li> <li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" required></li>""" ) self.assertHTMLEqual( str(f["name"]), """<input id="id_name" type="text" name="name" maxlength="20" required>""") def test_auto_id(self): f = BaseCategoryForm(auto_id=False) self.assertHTMLEqual( str(f.as_ul()), """<li>Name: <input type="text" name="name" maxlength="20" required></li> <li>Slug: <input type="text" name="slug" maxlength="20" required></li> <li>The URL: <input type="text" name="url" maxlength="40" required></li>""" ) def test_initial_values(self): self.create_basic_data() # Initial values can be provided for model forms f = ArticleForm( auto_id=False, initial={ 'headline': 'Your headline here', 'categories': [str(self.c1.id), str(self.c2.id)] }) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s" selected>Entertainment</option> <option value="%s" selected>It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) # When the ModelForm is passed an instance, that instance's current values are # inserted as 'initial' data in each Field. f = RoykoForm(auto_id=False, instance=self.w_royko) self.assertHTMLEqual( str(f), '''<tr><th>Name:</th><td><input type="text" name="name" value="Mike Royko" maxlength="50" required><br> <span class="helptext">Use both first and last names.</span></td></tr>''' ) art = Article.objects.create( headline='Test article', slug='test-article', pub_date=datetime.date(1988, 1, 4), writer=self.w_royko, article='Hello.' ) art_id_1 = art.id f = ArticleForm(auto_id=False, instance=art) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" value="test-article" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> <li>Writer: <select name="writer" required> <option value="">---------</option> <option value="%s">Bob Woodward</option> <option value="%s" selected>Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) f = ArticleForm({ 'headline': 'Test headline', 'slug': 'test-headline', 'pub_date': '1984-02-06', 'writer': str(self.w_royko.pk), 'article': 'Hello.' }, instance=art) self.assertEqual(f.errors, {}) self.assertTrue(f.is_valid()) test_art = f.save() self.assertEqual(test_art.id, art_id_1) test_art = Article.objects.get(id=art_id_1) self.assertEqual(test_art.headline, 'Test headline') def test_m2m_initial_callable(self): """ Regression for #10349: A callable can be provided as the initial value for an m2m field """ self.maxDiff = 1200 self.create_basic_data() # Set up a callable initial value def formfield_for_dbfield(db_field, **kwargs): if db_field.name == 'categories': kwargs['initial'] = lambda: Category.objects.all().order_by('name')[:2] return db_field.formfield(**kwargs) # Create a ModelForm, instantiate it, and check that the output is as expected ModelForm = modelform_factory( Article, fields=['headline', 'categories'], formfield_callback=formfield_for_dbfield, ) form = ModelForm() self.assertHTMLEqual( form.as_ul(), """<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="50" required></li> <li><label for="id_categories">Categories:</label> <select multiple name="categories" id="id_categories"> <option value="%d" selected>Entertainment</option> <option value="%d" selected>It&#x27;s a test</option> <option value="%d">Third test</option> </select></li>""" % (self.c1.pk, self.c2.pk, self.c3.pk)) def test_basic_creation(self): self.assertEqual(Category.objects.count(), 0) f = BaseCategoryForm({ 'name': 'Entertainment', 'slug': 'entertainment', 'url': 'entertainment', }) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['name'], 'Entertainment') self.assertEqual(f.cleaned_data['slug'], 'entertainment') self.assertEqual(f.cleaned_data['url'], 'entertainment') c1 = f.save() # Testing whether the same object is returned from the # ORM... not the fastest way... self.assertEqual(Category.objects.count(), 1) self.assertEqual(c1, Category.objects.all()[0]) self.assertEqual(c1.name, "Entertainment") def test_save_commit_false(self): # If you call save() with commit=False, then it will return an object that # hasn't yet been saved to the database. In this case, it's up to you to call # save() on the resulting model instance. f = BaseCategoryForm({'name': 'Third test', 'slug': 'third-test', 'url': 'third'}) self.assertTrue(f.is_valid()) c1 = f.save(commit=False) self.assertEqual(c1.name, "Third test") self.assertEqual(Category.objects.count(), 0) c1.save() self.assertEqual(Category.objects.count(), 1) def test_save_with_data_errors(self): # If you call save() with invalid data, you'll get a ValueError. f = BaseCategoryForm({'name': '', 'slug': 'not a slug!', 'url': 'foo'}) self.assertEqual(f.errors['name'], ['This field is required.']) self.assertEqual( f.errors['slug'], ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."] ) self.assertEqual(f.cleaned_data, {'url': 'foo'}) msg = "The Category could not be created because the data didn't validate." with self.assertRaisesMessage(ValueError, msg): f.save() f = BaseCategoryForm({'name': '', 'slug': '', 'url': 'foo'}) with self.assertRaisesMessage(ValueError, msg): f.save() def test_multi_fields(self): self.create_basic_data() self.maxDiff = None # ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any # fields with the 'choices' attribute are represented by a ChoiceField. f = ArticleForm(auto_id=False) self.assertHTMLEqual( str(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required></td></tr> <tr><th>Slug:</th><td><input type="text" name="slug" maxlength="50" required></td></tr> <tr><th>Pub date:</th><td><input type="text" name="pub_date" required></td></tr> <tr><th>Writer:</th><td><select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></td></tr> <tr><th>Article:</th><td><textarea rows="10" cols="40" name="article" required></textarea></td></tr> <tr><th>Categories:</th><td><select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></td></tr> <tr><th>Status:</th><td><select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></td></tr>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) # Add some categories and test the many-to-many form output. new_art = Article.objects.create( article="Hello.", headline="New headline", slug="new-headline", pub_date=datetime.date(1988, 1, 4), writer=self.w_royko) new_art.categories.add(Category.objects.get(name='Entertainment')) self.assertQuerysetEqual(new_art.categories.all(), ["Entertainment"]) f = ArticleForm(auto_id=False, instance=new_art) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> <li>Writer: <select name="writer" required> <option value="">---------</option> <option value="%s">Bob Woodward</option> <option value="%s" selected>Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s" selected>Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) def test_subset_fields(self): # You can restrict a form to a subset of the complete list of fields # by providing a 'fields' argument. If you try to save a # model created with such a form, you need to ensure that the fields # that are _not_ on the form have default values, or are allowed to have # a value of None. If a field isn't specified on a form, the object created # from the form can't provide a value for that field! class PartialArticleForm(forms.ModelForm): class Meta: model = Article fields = ('headline', 'pub_date') f = PartialArticleForm(auto_id=False) self.assertHTMLEqual( str(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" required></td></tr> <tr><th>Pub date:</th><td><input type="text" name="pub_date" required></td></tr>''') class PartialArticleFormWithSlug(forms.ModelForm): class Meta: model = Article fields = ('headline', 'slug', 'pub_date') w_royko = Writer.objects.create(name='Mike Royko') art = Article.objects.create( article="Hello.", headline="New headline", slug="new-headline", pub_date=datetime.date(1988, 1, 4), writer=w_royko) f = PartialArticleFormWithSlug({ 'headline': 'New headline', 'slug': 'new-headline', 'pub_date': '1988-01-04' }, auto_id=False, instance=art) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li>''' ) self.assertTrue(f.is_valid()) new_art = f.save() self.assertEqual(new_art.id, art.id) new_art = Article.objects.get(id=art.id) self.assertEqual(new_art.headline, 'New headline') def test_m2m_editing(self): self.create_basic_data() form_data = { 'headline': 'New headline', 'slug': 'new-headline', 'pub_date': '1988-01-04', 'writer': str(self.w_royko.pk), 'article': 'Hello.', 'categories': [str(self.c1.id), str(self.c2.id)] } # Create a new article, with categories, via the form. f = ArticleForm(form_data) new_art = f.save() new_art = Article.objects.get(id=new_art.id) art_id_1 = new_art.id self.assertQuerysetEqual(new_art.categories.order_by('name'), ["Entertainment", "It's a test"]) # Now, submit form data with no categories. This deletes the existing categories. form_data['categories'] = [] f = ArticleForm(form_data, instance=new_art) new_art = f.save() self.assertEqual(new_art.id, art_id_1) new_art = Article.objects.get(id=art_id_1) self.assertQuerysetEqual(new_art.categories.all(), []) # Create a new article, with no categories, via the form. f = ArticleForm(form_data) new_art = f.save() art_id_2 = new_art.id self.assertNotIn(art_id_2, (None, art_id_1)) new_art = Article.objects.get(id=art_id_2) self.assertQuerysetEqual(new_art.categories.all(), []) # Create a new article, with categories, via the form, but use commit=False. # The m2m data won't be saved until save_m2m() is invoked on the form. form_data['categories'] = [str(self.c1.id), str(self.c2.id)] f = ArticleForm(form_data) new_art = f.save(commit=False) # Manually save the instance new_art.save() art_id_3 = new_art.id self.assertNotIn(art_id_3, (None, art_id_1, art_id_2)) # The instance doesn't have m2m data yet new_art = Article.objects.get(id=art_id_3) self.assertQuerysetEqual(new_art.categories.all(), []) # Save the m2m data on the form f.save_m2m() self.assertQuerysetEqual(new_art.categories.order_by('name'), ["Entertainment", "It's a test"]) def test_custom_form_fields(self): # Here, we define a custom ModelForm. Because it happens to have the same fields as # the Category model, we can just call the form's save() to apply its changes to an # existing Category instance. class ShortCategory(forms.ModelForm): name = forms.CharField(max_length=5) slug = forms.CharField(max_length=5) url = forms.CharField(max_length=3) class Meta: model = Category fields = '__all__' cat = Category.objects.create(name='Third test') form = ShortCategory({'name': 'Third', 'slug': 'third', 'url': '3rd'}, instance=cat) self.assertEqual(form.save().name, 'Third') self.assertEqual(Category.objects.get(id=cat.id).name, 'Third') def test_runtime_choicefield_populated(self): self.maxDiff = None # Here, we demonstrate that choices for a ForeignKey ChoiceField are determined # at runtime, based on the data in the database when the form is displayed, not # the data in the database when the form is instantiated. self.create_basic_data() f = ArticleForm(auto_id=False) self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select> </li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk)) c4 = Category.objects.create(name='Fourth', url='4th') w_bernstein = Writer.objects.create(name='Carl Bernstein') self.assertHTMLEqual( f.as_ul(), '''<li>Headline: <input type="text" name="headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Carl Bernstein</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> <option value="%s">Fourth</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>''' % (self.w_woodward.pk, w_bernstein.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk, c4.pk)) def test_recleaning_model_form_instance(self): """ Re-cleaning an instance that was added via a ModelForm shouldn't raise a pk uniqueness error. """ class AuthorForm(forms.ModelForm): class Meta: model = Author fields = '__all__' form = AuthorForm({'full_name': 'Bob'}) self.assertTrue(form.is_valid()) obj = form.save() obj.name = 'Alice' obj.full_clean() class ModelMultipleChoiceFieldTests(TestCase): @classmethod def setUpTestData(cls): cls.c1 = Category.objects.create(name='Entertainment', slug='entertainment', url='entertainment') cls.c2 = Category.objects.create(name="It's a test", slug='its-test', url='test') cls.c3 = Category.objects.create(name='Third', slug='third-test', url='third') def test_model_multiple_choice_field(self): f = forms.ModelMultipleChoiceField(Category.objects.all()) self.assertEqual(list(f.choices), [ (self.c1.pk, 'Entertainment'), (self.c2.pk, "It's a test"), (self.c3.pk, 'Third')]) with self.assertRaises(ValidationError): f.clean(None) with self.assertRaises(ValidationError): f.clean([]) self.assertQuerysetEqual(f.clean([self.c1.id]), ["Entertainment"]) self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"]) self.assertQuerysetEqual(f.clean([str(self.c1.id)]), ["Entertainment"]) self.assertQuerysetEqual( f.clean([str(self.c1.id), str(self.c2.id)]), ["Entertainment", "It's a test"], ordered=False ) self.assertQuerysetEqual( f.clean([self.c1.id, str(self.c2.id)]), ["Entertainment", "It's a test"], ordered=False ) self.assertQuerysetEqual( f.clean((self.c1.id, str(self.c2.id))), ["Entertainment", "It's a test"], ordered=False ) with self.assertRaises(ValidationError): f.clean(['100']) with self.assertRaises(ValidationError): f.clean('hello') with self.assertRaises(ValidationError): f.clean(['fail']) # Invalid types that require TypeError to be caught (#22808). with self.assertRaises(ValidationError): f.clean([['fail']]) with self.assertRaises(ValidationError): f.clean([{'foo': 'bar'}]) # Add a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. # Note, we are using an id of 1006 here since tests that run before # this may create categories with primary keys up to 6. Use # a number that will not conflict. c6 = Category.objects.create(id=1006, name='Sixth', url='6th') self.assertQuerysetEqual(f.clean([c6.id]), ["Sixth"]) # Delete a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. Category.objects.get(url='6th').delete() with self.assertRaises(ValidationError): f.clean([c6.id]) def test_model_multiple_choice_required_false(self): f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False) self.assertIsInstance(f.clean([]), EmptyQuerySet) self.assertIsInstance(f.clean(()), EmptyQuerySet) with self.assertRaises(ValidationError): f.clean(['0']) with self.assertRaises(ValidationError): f.clean([str(self.c3.id), '0']) with self.assertRaises(ValidationError): f.clean([str(self.c1.id), '0']) # queryset can be changed after the field is created. f.queryset = Category.objects.exclude(name='Third') self.assertEqual(list(f.choices), [ (self.c1.pk, 'Entertainment'), (self.c2.pk, "It's a test")]) self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"]) with self.assertRaises(ValidationError): f.clean([self.c3.id]) with self.assertRaises(ValidationError): f.clean([str(self.c2.id), str(self.c3.id)]) f.queryset = Category.objects.all() f.label_from_instance = lambda obj: "multicategory " + str(obj) self.assertEqual(list(f.choices), [ (self.c1.pk, 'multicategory Entertainment'), (self.c2.pk, "multicategory It's a test"), (self.c3.pk, 'multicategory Third')]) def test_model_multiple_choice_number_of_queries(self): """ ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156). """ persons = [Writer.objects.create(name="Person %s" % i) for i in range(30)] f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]]) def test_model_multiple_choice_run_validators(self): """ ModelMultipleChoiceField run given validators (#14144). """ for i in range(30): Writer.objects.create(name="Person %s" % i) self._validator_run = False def my_validator(value): self._validator_run = True f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all(), validators=[my_validator]) f.clean([p.pk for p in Writer.objects.all()[8:9]]) self.assertTrue(self._validator_run) def test_model_multiple_choice_show_hidden_initial(self): """ Test support of show_hidden_initial by ModelMultipleChoiceField. """ class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField(show_hidden_initial=True, queryset=Writer.objects.all()) person1 = Writer.objects.create(name="Person 1") person2 = Writer.objects.create(name="Person 2") form = WriterForm( initial={'persons': [person1, person2]}, data={ 'initial-persons': [str(person1.pk), str(person2.pk)], 'persons': [str(person1.pk), str(person2.pk)], }, ) self.assertTrue(form.is_valid()) self.assertFalse(form.has_changed()) form = WriterForm( initial={'persons': [person1, person2]}, data={ 'initial-persons': [str(person1.pk), str(person2.pk)], 'persons': [str(person2.pk)], }, ) self.assertTrue(form.is_valid()) self.assertTrue(form.has_changed()) def test_model_multiple_choice_field_22745(self): """ #22745 -- Make sure that ModelMultipleChoiceField with CheckboxSelectMultiple widget doesn't produce unnecessary db queries when accessing its BoundField's attrs. """ class ModelMultipleChoiceForm(forms.Form): categories = forms.ModelMultipleChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple) form = ModelMultipleChoiceForm() field = form['categories'] # BoundField template = Template('{{ field.name }}{{ field }}{{ field.help_text }}') with self.assertNumQueries(1): template.render(Context({'field': field})) def test_show_hidden_initial_changed_queries_efficiently(self): class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField( show_hidden_initial=True, queryset=Writer.objects.all()) writers = (Writer.objects.create(name=str(x)) for x in range(0, 50)) writer_pks = tuple(x.pk for x in writers) form = WriterForm(data={'initial-persons': writer_pks}) with self.assertNumQueries(1): self.assertTrue(form.has_changed()) def test_clean_does_deduplicate_values(self): class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) person1 = Writer.objects.create(name="Person 1") form = WriterForm(data={}) queryset = form.fields['persons'].clean([str(person1.pk)] * 50) sql, params = queryset.query.sql_with_params() self.assertEqual(len(params), 1) def test_to_field_name_with_initial_data(self): class ArticleCategoriesForm(forms.ModelForm): categories = forms.ModelMultipleChoiceField(Category.objects.all(), to_field_name='slug') class Meta: model = Article fields = ['categories'] article = Article.objects.create( headline='Test article', slug='test-article', pub_date=datetime.date(1988, 1, 4), writer=Writer.objects.create(name='Test writer'), article='Hello.', ) article.categories.add(self.c2, self.c3) form = ArticleCategoriesForm(instance=article) self.assertCountEqual(form['categories'].value(), [self.c2.slug, self.c3.slug]) class ModelOneToOneFieldTests(TestCase): def test_modelform_onetoonefield(self): class ImprovedArticleForm(forms.ModelForm): class Meta: model = ImprovedArticle fields = '__all__' class ImprovedArticleWithParentLinkForm(forms.ModelForm): class Meta: model = ImprovedArticleWithParentLink fields = '__all__' self.assertEqual(list(ImprovedArticleForm.base_fields), ['article']) self.assertEqual(list(ImprovedArticleWithParentLinkForm.base_fields), []) def test_modelform_subclassed_model(self): class BetterWriterForm(forms.ModelForm): class Meta: # BetterWriter model is a subclass of Writer with an additional `score` field model = BetterWriter fields = '__all__' bw = BetterWriter.objects.create(name='Joe Better', score=10) self.assertEqual(sorted(model_to_dict(bw)), ['id', 'name', 'score', 'writer_ptr']) self.assertEqual(sorted(model_to_dict(bw, fields=[])), []) self.assertEqual(sorted(model_to_dict(bw, fields=['id', 'name'])), ['id', 'name']) self.assertEqual(sorted(model_to_dict(bw, exclude=[])), ['id', 'name', 'score', 'writer_ptr']) self.assertEqual(sorted(model_to_dict(bw, exclude=['id', 'name'])), ['score', 'writer_ptr']) form = BetterWriterForm({'name': 'Some Name', 'score': 12}) self.assertTrue(form.is_valid()) bw2 = form.save() self.assertEqual(bw2.score, 12) def test_onetoonefield(self): class WriterProfileForm(forms.ModelForm): class Meta: # WriterProfile has a OneToOneField to Writer model = WriterProfile fields = '__all__' self.w_royko = Writer.objects.create(name='Mike Royko') self.w_woodward = Writer.objects.create(name='Bob Woodward') form = WriterProfileForm() self.assertHTMLEqual( form.as_p(), '''<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></p> <p><label for="id_age">Age:</label> <input type="number" name="age" id="id_age" min="0" required></p>''' % ( self.w_woodward.pk, self.w_royko.pk, ) ) data = { 'writer': str(self.w_woodward.pk), 'age': '65', } form = WriterProfileForm(data) instance = form.save() self.assertEqual(str(instance), 'Bob Woodward is 65') form = WriterProfileForm(instance=instance) self.assertHTMLEqual( form.as_p(), '''<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required> <option value="">---------</option> <option value="%s" selected>Bob Woodward</option> <option value="%s">Mike Royko</option> </select></p> <p><label for="id_age">Age:</label> <input type="number" name="age" value="65" id="id_age" min="0" required></p>''' % ( self.w_woodward.pk, self.w_royko.pk, ) ) def test_assignment_of_none(self): class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ['publication', 'full_name'] publication = Publication.objects.create(title="Pravda", date_published=datetime.date(1991, 8, 22)) author = Author.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author) self.assertTrue(form.is_valid()) self.assertIsNone(form.cleaned_data['publication']) author = form.save() # author object returned from form still retains original publication object # that's why we need to retrieve it from database again new_author = Author.objects.get(pk=author.pk) self.assertIsNone(new_author.publication) def test_assignment_of_none_null_false(self): class AuthorForm(forms.ModelForm): class Meta: model = Author1 fields = ['publication', 'full_name'] publication = Publication.objects.create(title="Pravda", date_published=datetime.date(1991, 8, 22)) author = Author1.objects.create(publication=publication, full_name='John Doe') form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author) self.assertFalse(form.is_valid()) class FileAndImageFieldTests(TestCase): def test_clean_false(self): """ If the ``clean`` method on a non-required FileField receives False as the data (meaning clear the field value), it returns False, regardless of the value of ``initial``. """ f = forms.FileField(required=False) self.assertIs(f.clean(False), False) self.assertIs(f.clean(False, 'initial'), False) def test_clean_false_required(self): """ If the ``clean`` method on a required FileField receives False as the data, it has the same effect as None: initial is returned if non-empty, otherwise the validation catches the lack of a required value. """ f = forms.FileField(required=True) self.assertEqual(f.clean(False, 'initial'), 'initial') with self.assertRaises(ValidationError): f.clean(False) def test_full_clear(self): """ Integration happy-path test that a model FileField can actually be set and cleared via a ModelForm. """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' form = DocumentForm() self.assertIn('name="myfile"', str(form)) self.assertNotIn('myfile-clear', str(form)) form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')}) self.assertTrue(form.is_valid()) doc = form.save(commit=False) self.assertEqual(doc.myfile.name, 'something.txt') form = DocumentForm(instance=doc) self.assertIn('myfile-clear', str(form)) form = DocumentForm(instance=doc, data={'myfile-clear': 'true'}) doc = form.save(commit=False) self.assertFalse(doc.myfile) def test_clear_and_file_contradiction(self): """ If the user submits a new file upload AND checks the clear checkbox, they get a validation error, and the bound redisplay of the form still includes the current file and the clear checkbox. """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')}) self.assertTrue(form.is_valid()) doc = form.save(commit=False) form = DocumentForm( instance=doc, files={'myfile': SimpleUploadedFile('something.txt', b'content')}, data={'myfile-clear': 'true'}, ) self.assertTrue(not form.is_valid()) self.assertEqual(form.errors['myfile'], ['Please either submit a file or check the clear checkbox, not both.']) rendered = str(form) self.assertIn('something.txt', rendered) self.assertIn('myfile-clear', rendered) def test_render_empty_file_field(self): class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' doc = Document.objects.create() form = DocumentForm(instance=doc) self.assertHTMLEqual( str(form['myfile']), '<input id="id_myfile" name="myfile" type="file">' ) def test_file_field_data(self): # Test conditions when files is either not given or empty. f = TextFileForm(data={'description': 'Assistance'}) self.assertFalse(f.is_valid()) f = TextFileForm(data={'description': 'Assistance'}, files={}) self.assertFalse(f.is_valid()) # Upload a file and ensure it all works as expected. f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', b'hello world')}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.file.name, 'tests/test1.txt') instance.file.delete() # If the previous file has been deleted, the file name can be reused f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', b'hello world')}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.file.name, 'tests/test1.txt') # Check if the max_length attribute has been inherited from the model. f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test-maxlength.txt', b'hello world')}, ) self.assertFalse(f.is_valid()) # Edit an instance that already has the file defined in the model. This will not # save the file again, but leave it exactly as it is. f = TextFileForm({'description': 'Assistance'}, instance=instance) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['file'].name, 'tests/test1.txt') instance = f.save() self.assertEqual(instance.file.name, 'tests/test1.txt') # Delete the current file since this is not done by Django. instance.file.delete() # Override the file by uploading a new one. f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test2.txt', b'hello world')}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, 'tests/test2.txt') # Delete the current file since this is not done by Django. instance.file.delete() instance.delete() def test_filefield_required_false(self): # Test the non-required FileField f = TextFileForm(data={'description': 'Assistance'}) f.fields['file'].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, '') f = TextFileForm( data={'description': 'Assistance'}, files={'file': SimpleUploadedFile('test3.txt', b'hello world')}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, 'tests/test3.txt') # Instance can be edited w/out re-uploading the file and existing file should be preserved. f = TextFileForm({'description': 'New Description'}, instance=instance) f.fields['file'].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, 'New Description') self.assertEqual(instance.file.name, 'tests/test3.txt') # Delete the current file since this is not done by Django. instance.file.delete() instance.delete() def test_custom_file_field_save(self): """ Regression for #11149: save_form_data should be called only once """ class CFFForm(forms.ModelForm): class Meta: model = CustomFF fields = '__all__' # It's enough that the form saves without error -- the custom save routine will # generate an AssertionError if it is called more than once during save. form = CFFForm(data={'f': None}) form.save() def test_file_field_multiple_save(self): """ Simulate a file upload and check how many times Model.save() gets called. Test for bug #639. """ class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = '__all__' # Grab an image for testing. filename = os.path.join(os.path.dirname(__file__), 'test.png') with open(filename, "rb") as fp: img = fp.read() # Fake a POST QueryDict and FILES MultiValueDict. data = {'title': 'Testing'} files = {"image": SimpleUploadedFile('test.png', img, 'image/png')} form = PhotoForm(data=data, files=files) p = form.save() try: # Check the savecount stored on the object (see the model). self.assertEqual(p._savecount, 1) finally: # Delete the "uploaded" file to avoid clogging /tmp. p = Photo.objects.get() p.image.delete(save=False) def test_file_path_field_blank(self): """FilePathField(blank=True) includes the empty option.""" class FPForm(forms.ModelForm): class Meta: model = FilePathModel fields = '__all__' form = FPForm() self.assertEqual([name for _, name in form['path'].field.choices], ['---------', 'models.py']) @skipUnless(test_images, "Pillow not installed") def test_image_field(self): # ImageField and FileField are nearly identical, but they differ slightly when # it comes to validation. This specifically tests that #6302 is fixed for # both file fields and image fields. with open(os.path.join(os.path.dirname(__file__), 'test.png'), 'rb') as fp: image_data = fp.read() with open(os.path.join(os.path.dirname(__file__), 'test2.png'), 'rb') as fp: image_data2 = fp.read() f = ImageFileForm( data={'description': 'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.image.name, 'tests/test.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) f = ImageFileForm( data={'description': 'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.image.name, 'tests/test.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Edit an instance that already has the (required) image defined in the model. This will not # save the image again, but leave it exactly as it is. f = ImageFileForm(data={'description': 'Look, it changed'}, instance=instance) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data['image'].name, 'tests/test.png') instance = f.save() self.assertEqual(instance.image.name, 'tests/test.png') self.assertEqual(instance.height, 16) self.assertEqual(instance.width, 16) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) # Override the file by uploading a new one. f = ImageFileForm( data={'description': 'Changed it'}, files={'image': SimpleUploadedFile('test2.png', image_data2)}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test2.png') self.assertEqual(instance.height, 32) self.assertEqual(instance.width, 48) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) instance.delete() f = ImageFileForm( data={'description': 'Changed it'}, files={'image': SimpleUploadedFile('test2.png', image_data2)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test2.png') self.assertEqual(instance.height, 32) self.assertEqual(instance.width, 48) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) instance.delete() # Test the non-required ImageField # Note: In Oracle, we expect a null ImageField to return '' instead of # None. if connection.features.interprets_empty_strings_as_nulls: expected_null_imagefield_repr = '' else: expected_null_imagefield_repr = None f = OptionalImageFileForm(data={'description': 'Test'}) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, expected_null_imagefield_repr) self.assertIsNone(instance.width) self.assertIsNone(instance.height) f = OptionalImageFileForm( data={'description': 'And a final one'}, files={'image': SimpleUploadedFile('test3.png', image_data)}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test3.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Editing the instance without re-uploading the image should not affect # the image or its width/height properties. f = OptionalImageFileForm({'description': 'New Description'}, instance=instance) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, 'New Description') self.assertEqual(instance.image.name, 'tests/test3.png') self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Delete the current file since this is not done by Django. instance.image.delete() instance.delete() f = OptionalImageFileForm( data={'description': 'And a final one'}, files={'image': SimpleUploadedFile('test4.png', image_data2)} ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/test4.png') self.assertEqual(instance.width, 48) self.assertEqual(instance.height, 32) instance.delete() # Test callable upload_to behavior that's dependent on the value of another field in the model f = ImageFileForm( data={'description': 'And a final one', 'path': 'foo'}, files={'image': SimpleUploadedFile('test4.png', image_data)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'foo/test4.png') instance.delete() # Editing an instance that has an image without an extension shouldn't # fail validation. First create: f = NoExtensionImageFileForm( data={'description': 'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, 'tests/no_extension') # Then edit: f = NoExtensionImageFileForm(data={'description': 'Edited image'}, instance=instance) self.assertTrue(f.is_valid()) class ModelOtherFieldTests(SimpleTestCase): def test_big_integer_field(self): bif = BigIntForm({'biggie': '-9223372036854775808'}) self.assertTrue(bif.is_valid()) bif = BigIntForm({'biggie': '-9223372036854775809'}) self.assertFalse(bif.is_valid()) self.assertEqual( bif.errors, {'biggie': ['Ensure this value is greater than or equal to -9223372036854775808.']} ) bif = BigIntForm({'biggie': '9223372036854775807'}) self.assertTrue(bif.is_valid()) bif = BigIntForm({'biggie': '9223372036854775808'}) self.assertFalse(bif.is_valid()) self.assertEqual(bif.errors, {'biggie': ['Ensure this value is less than or equal to 9223372036854775807.']}) def test_url_on_modelform(self): "Check basic URL field validation on model forms" class HomepageForm(forms.ModelForm): class Meta: model = Homepage fields = '__all__' self.assertFalse(HomepageForm({'url': 'foo'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://example'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://example.'}).is_valid()) self.assertFalse(HomepageForm({'url': 'http://com.'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://localhost'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://example.com'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com/test'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000/test'}).is_valid()) self.assertTrue(HomepageForm({'url': 'http://example.com/foo/bar'}).is_valid()) def test_modelform_non_editable_field(self): """ When explicitly including a non-editable field in a ModelForm, the error message should be explicit. """ # 'created', non-editable, is excluded by default self.assertNotIn('created', ArticleForm().fields) msg = "'created' cannot be specified for Article model form as it is a non-editable field" with self.assertRaisesMessage(FieldError, msg): class InvalidArticleForm(forms.ModelForm): class Meta: model = Article fields = ('headline', 'created') def test_http_prefixing(self): """ If the http:// prefix is omitted on form input, the field adds it again. (Refs #13613) """ class HomepageForm(forms.ModelForm): class Meta: model = Homepage fields = '__all__' form = HomepageForm({'url': 'example.com'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['url'], 'http://example.com') form = HomepageForm({'url': 'example.com/test'}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data['url'], 'http://example.com/test') class OtherModelFormTests(TestCase): def test_media_on_modelform(self): # Similar to a regular Form class you can define custom media to be used on # the ModelForm. f = ModelFormWithMedia() self.assertHTMLEqual( str(f.media), '''<link href="/some/form/css" type="text/css" media="all" rel="stylesheet"> <script type="text/javascript" src="/some/form/javascript"></script>''' ) def test_choices_type(self): # Choices on CharField and IntegerField f = ArticleForm() with self.assertRaises(ValidationError): f.fields['status'].clean('42') f = ArticleStatusForm() with self.assertRaises(ValidationError): f.fields['status'].clean('z') def test_prefetch_related_queryset(self): """ ModelChoiceField should respect a prefetch_related() on its queryset. """ blue = Colour.objects.create(name='blue') red = Colour.objects.create(name='red') multicolor_item = ColourfulItem.objects.create() multicolor_item.colours.add(blue, red) red_item = ColourfulItem.objects.create() red_item.colours.add(red) class ColorModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return ', '.join(c.name for c in obj.colours.all()) field = ColorModelChoiceField(ColourfulItem.objects.prefetch_related('colours')) with self.assertNumQueries(3): # would be 4 if prefetch is ignored self.assertEqual(tuple(field.choices), ( ('', '---------'), (multicolor_item.pk, 'blue, red'), (red_item.pk, 'red'), )) def test_foreignkeys_which_use_to_field(self): apple = Inventory.objects.create(barcode=86, name='Apple') Inventory.objects.create(barcode=22, name='Pear') core = Inventory.objects.create(barcode=87, name='Core', parent=apple) field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name='barcode') self.assertEqual(tuple(field.choices), ( ('', '---------'), (86, 'Apple'), (87, 'Core'), (22, 'Pear'))) form = InventoryForm(instance=core) self.assertHTMLEqual(str(form['parent']), '''<select name="parent" id="id_parent"> <option value="">---------</option> <option value="86" selected>Apple</option> <option value="87">Core</option> <option value="22">Pear</option> </select>''') data = model_to_dict(core) data['parent'] = '22' form = InventoryForm(data=data, instance=core) core = form.save() self.assertEqual(core.parent.name, 'Pear') class CategoryForm(forms.ModelForm): description = forms.CharField() class Meta: model = Category fields = ['description', 'url'] self.assertEqual(list(CategoryForm.base_fields), ['description', 'url']) self.assertHTMLEqual( str(CategoryForm()), '''<tr><th><label for="id_description">Description:</label></th> <td><input type="text" name="description" id="id_description" required></td></tr> <tr><th><label for="id_url">The URL:</label></th> <td><input id="id_url" type="text" name="url" maxlength="40" required></td></tr>''' ) # to_field_name should also work on ModelMultipleChoiceField ################## field = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode') self.assertEqual(tuple(field.choices), ((86, 'Apple'), (87, 'Core'), (22, 'Pear'))) self.assertQuerysetEqual(field.clean([86]), ['Apple']) form = SelectInventoryForm({'items': [87, 22]}) self.assertTrue(form.is_valid()) self.assertEqual(len(form.cleaned_data), 1) self.assertQuerysetEqual(form.cleaned_data['items'], ['Core', 'Pear']) def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self): self.assertEqual(list(CustomFieldForExclusionForm.base_fields), ['name']) self.assertHTMLEqual( str(CustomFieldForExclusionForm()), '''<tr><th><label for="id_name">Name:</label></th> <td><input id="id_name" type="text" name="name" maxlength="10" required></td></tr>''' ) def test_iterable_model_m2m(self): class ColourfulItemForm(forms.ModelForm): class Meta: model = ColourfulItem fields = '__all__' colour = Colour.objects.create(name='Blue') form = ColourfulItemForm() self.maxDiff = 1024 self.assertHTMLEqual( form.as_p(), """<p><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="50" required></p> <p><label for="id_colours">Colours:</label> <select multiple name="colours" id="id_colours" required> <option value="%(blue_pk)s">Blue</option> </select></p>""" % {'blue_pk': colour.pk}) def test_callable_field_default(self): class PublicationDefaultsForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ('title', 'date_published', 'mode', 'category') self.maxDiff = 2000 form = PublicationDefaultsForm() today_str = str(datetime.date.today()) self.assertHTMLEqual( form.as_p(), """ <p><label for="id_title">Title:</label> <input id="id_title" maxlength="30" name="title" type="text" required></p> <p><label for="id_date_published">Date published:</label> <input id="id_date_published" name="date_published" type="text" value="{0}" required> <input id="initial-id_date_published" name="initial-date_published" type="hidden" value="{0}"></p> <p><label for="id_mode">Mode:</label> <select id="id_mode" name="mode"> <option value="di" selected>direct</option> <option value="de">delayed</option></select> <input id="initial-id_mode" name="initial-mode" type="hidden" value="di"></p> <p><label for="id_category">Category:</label> <select id="id_category" name="category"> <option value="1">Games</option> <option value="2">Comics</option> <option value="3" selected>Novel</option></select> <input id="initial-id_category" name="initial-category" type="hidden" value="3"> """.format(today_str) ) empty_data = { 'title': '', 'date_published': today_str, 'initial-date_published': today_str, 'mode': 'di', 'initial-mode': 'di', 'category': '3', 'initial-category': '3', } bound_form = PublicationDefaultsForm(empty_data) self.assertFalse(bound_form.has_changed()) class ModelFormCustomErrorTests(SimpleTestCase): def test_custom_error_messages(self): data = {'name1': '@#$!!**@#$', 'name2': '@#$!!**@#$'} errors = CustomErrorMessageForm(data).errors self.assertHTMLEqual( str(errors['name1']), '<ul class="errorlist"><li>Form custom error message.</li></ul>' ) self.assertHTMLEqual( str(errors['name2']), '<ul class="errorlist"><li>Model custom error message.</li></ul>' ) def test_model_clean_error_messages(self): data = {'name1': 'FORBIDDEN_VALUE', 'name2': 'ABC'} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertHTMLEqual( str(form.errors['name1']), '<ul class="errorlist"><li>Model.clean() error messages.</li></ul>' ) data = {'name1': 'FORBIDDEN_VALUE2', 'name2': 'ABC'} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertHTMLEqual( str(form.errors['name1']), '<ul class="errorlist"><li>Model.clean() error messages (simpler syntax).</li></ul>' ) data = {'name1': 'GLOBAL_ERROR', 'name2': 'ABC'} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors['__all__'], ['Global error message.']) class CustomCleanTests(TestCase): def test_override_clean(self): """ Regression for #12596: Calling super from ModelForm.clean() should be optional. """ class TripleFormWithCleanOverride(forms.ModelForm): class Meta: model = Triple fields = '__all__' def clean(self): if not self.cleaned_data['left'] == self.cleaned_data['right']: raise forms.ValidationError('Left and right should be equal') return self.cleaned_data form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1}) self.assertTrue(form.is_valid()) # form.instance.left will be None if the instance was not constructed # by form.full_clean(). self.assertEqual(form.instance.left, 1) def test_model_form_clean_applies_to_model(self): """ Regression test for #12960. Make sure the cleaned_data returned from ModelForm.clean() is applied to the model instance. """ class CategoryForm(forms.ModelForm): class Meta: model = Category fields = '__all__' def clean(self): self.cleaned_data['name'] = self.cleaned_data['name'].upper() return self.cleaned_data data = {'name': 'Test', 'slug': 'test', 'url': '/test'} form = CategoryForm(data) category = form.save() self.assertEqual(category.name, 'TEST') class ModelFormInheritanceTests(SimpleTestCase): def test_form_subclass_inheritance(self): class Form(forms.Form): age = forms.IntegerField() class ModelForm(forms.ModelForm, Form): class Meta: model = Writer fields = '__all__' self.assertEqual(list(ModelForm().fields), ['name', 'age']) def test_field_removal(self): class ModelForm(forms.ModelForm): class Meta: model = Writer fields = '__all__' class Mixin: age = None class Form(forms.Form): age = forms.IntegerField() class Form2(forms.Form): foo = forms.IntegerField() self.assertEqual(list(ModelForm().fields), ['name']) self.assertEqual(list(type('NewForm', (Mixin, Form), {})().fields), []) self.assertEqual(list(type('NewForm', (Form2, Mixin, Form), {})().fields), ['foo']) self.assertEqual(list(type('NewForm', (Mixin, ModelForm, Form), {})().fields), ['name']) self.assertEqual(list(type('NewForm', (ModelForm, Mixin, Form), {})().fields), ['name']) self.assertEqual(list(type('NewForm', (ModelForm, Form, Mixin), {})().fields), ['name', 'age']) self.assertEqual(list(type('NewForm', (ModelForm, Form), {'age': None})().fields), ['name']) def test_field_removal_name_clashes(self): """ Form fields can be removed in subclasses by setting them to None (#22510). """ class MyForm(forms.ModelForm): media = forms.CharField() class Meta: model = Writer fields = '__all__' class SubForm(MyForm): media = None self.assertIn('media', MyForm().fields) self.assertNotIn('media', SubForm().fields) self.assertTrue(hasattr(MyForm, 'media')) self.assertTrue(hasattr(SubForm, 'media')) class StumpJokeForm(forms.ModelForm): class Meta: model = StumpJoke fields = '__all__' class CustomFieldWithQuerysetButNoLimitChoicesTo(forms.Field): queryset = 42 class StumpJokeWithCustomFieldForm(forms.ModelForm): custom = CustomFieldWithQuerysetButNoLimitChoicesTo() class Meta: model = StumpJoke fields = () class LimitChoicesToTests(TestCase): """ Tests the functionality of ``limit_choices_to``. """ @classmethod def setUpTestData(cls): cls.threepwood = Character.objects.create( username='threepwood', last_action=datetime.datetime.today() + datetime.timedelta(days=1), ) cls.marley = Character.objects.create( username='marley', last_action=datetime.datetime.today() - datetime.timedelta(days=1), ) def test_limit_choices_to_callable_for_fk_rel(self): """ A ForeignKey can use limit_choices_to as a callable (#2554). """ stumpjokeform = StumpJokeForm() self.assertSequenceEqual(stumpjokeform.fields['most_recently_fooled'].queryset, [self.threepwood]) def test_limit_choices_to_callable_for_m2m_rel(self): """ A ManyToManyField can use limit_choices_to as a callable (#2554). """ stumpjokeform = StumpJokeForm() self.assertSequenceEqual(stumpjokeform.fields['most_recently_fooled'].queryset, [self.threepwood]) def test_custom_field_with_queryset_but_no_limit_choices_to(self): """ A custom field with a `queryset` attribute but no `limit_choices_to` works (#23795). """ f = StumpJokeWithCustomFieldForm() self.assertEqual(f.fields['custom'].queryset, 42) def test_fields_for_model_applies_limit_choices_to(self): fields = fields_for_model(StumpJoke, ['has_fooled_today']) self.assertSequenceEqual(fields['has_fooled_today'].queryset, [self.threepwood]) def test_callable_called_each_time_form_is_instantiated(self): field = StumpJokeForm.base_fields['most_recently_fooled'] with mock.patch.object(field, 'limit_choices_to') as today_callable_dict: StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 1) StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 2) StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 3) class FormFieldCallbackTests(SimpleTestCase): def test_baseform_with_widgets_in_meta(self): """Regression for #13095: Using base forms with widgets defined in Meta should not raise errors.""" widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {'name': widget} fields = "__all__" Form = modelform_factory(Person, form=BaseForm) self.assertIsInstance(Form.base_fields['name'].widget, forms.Textarea) def test_factory_with_widget_argument(self): """ Regression for #15315: modelform_factory should accept widgets argument """ widget = forms.Textarea() # Without a widget should not set the widget to textarea Form = modelform_factory(Person, fields="__all__") self.assertNotEqual(Form.base_fields['name'].widget.__class__, forms.Textarea) # With a widget should not set the widget to textarea Form = modelform_factory(Person, fields="__all__", widgets={'name': widget}) self.assertEqual(Form.base_fields['name'].widget.__class__, forms.Textarea) def test_modelform_factory_without_fields(self): """ Regression for #19733 """ message = ( "Calling modelform_factory without defining 'fields' or 'exclude' " "explicitly is prohibited." ) with self.assertRaisesMessage(ImproperlyConfigured, message): modelform_factory(Person) def test_modelform_factory_with_all_fields(self): """ Regression for #19733 """ form = modelform_factory(Person, fields="__all__") self.assertEqual(list(form.base_fields), ["name"]) def test_custom_callback(self): """A custom formfield_callback is used if provided""" callback_args = [] def callback(db_field, **kwargs): callback_args.append((db_field, kwargs)) return db_field.formfield(**kwargs) widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {'name': widget} fields = "__all__" modelform_factory(Person, form=BaseForm, formfield_callback=callback) id_field, name_field = Person._meta.fields self.assertEqual(callback_args, [(id_field, {}), (name_field, {'widget': widget})]) def test_bad_callback(self): # A bad callback provided by user still gives an error with self.assertRaises(TypeError): modelform_factory(Person, fields="__all__", formfield_callback='not a function or callable') def test_inherit_after_custom_callback(self): def callback(db_field, **kwargs): if isinstance(db_field, models.CharField): return forms.CharField(widget=forms.Textarea) return db_field.formfield(**kwargs) class BaseForm(forms.ModelForm): class Meta: model = Person fields = '__all__' NewForm = modelform_factory(Person, form=BaseForm, formfield_callback=callback) class InheritedForm(NewForm): pass for name in NewForm.base_fields: self.assertEqual( type(InheritedForm.base_fields[name].widget), type(NewForm.base_fields[name].widget) ) class LocalizedModelFormTest(TestCase): def test_model_form_applies_localize_to_some_fields(self): class PartiallyLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = ('left', 'right',) fields = '__all__' f = PartiallyLocalizedTripleForm({'left': 10, 'middle': 10, 'right': 10}) self.assertTrue(f.is_valid()) self.assertTrue(f.fields['left'].localize) self.assertFalse(f.fields['middle'].localize) self.assertTrue(f.fields['right'].localize) def test_model_form_applies_localize_to_all_fields(self): class FullyLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = '__all__' fields = '__all__' f = FullyLocalizedTripleForm({'left': 10, 'middle': 10, 'right': 10}) self.assertTrue(f.is_valid()) self.assertTrue(f.fields['left'].localize) self.assertTrue(f.fields['middle'].localize) self.assertTrue(f.fields['right'].localize) def test_model_form_refuses_arbitrary_string(self): msg = ( "BrokenLocalizedTripleForm.Meta.localized_fields " "cannot be a string. Did you mean to type: ('foo',)?" ) with self.assertRaisesMessage(TypeError, msg): class BrokenLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = "foo" class CustomMetaclass(ModelFormMetaclass): def __new__(cls, name, bases, attrs): new = super().__new__(cls, name, bases, attrs) new.base_fields = {} return new class CustomMetaclassForm(forms.ModelForm, metaclass=CustomMetaclass): pass class CustomMetaclassTestCase(SimpleTestCase): def test_modelform_factory_metaclass(self): new_cls = modelform_factory(Person, fields="__all__", form=CustomMetaclassForm) self.assertEqual(new_cls.base_fields, {}) class StrictAssignmentTests(SimpleTestCase): """ Should a model do anything special with __setattr__() or descriptors which raise a ValidationError, a model form should catch the error (#24706). """ def test_setattr_raises_validation_error_field_specific(self): """ A model ValidationError using the dict form should put the error message into the correct key of form.errors. """ form_class = modelform_factory(model=StrictAssignmentFieldSpecific, fields=['title']) form = form_class(data={'title': 'testing setattr'}, files=None) # This line turns on the ValidationError; it avoids the model erroring # when its own __init__() is called when creating form.instance. form.instance._should_error = True self.assertFalse(form.is_valid()) self.assertEqual(form.errors, { 'title': ['Cannot set attribute', 'This field cannot be blank.'] }) def test_setattr_raises_validation_error_non_field(self): """ A model ValidationError not using the dict form should put the error message into __all__ (i.e. non-field errors) on the form. """ form_class = modelform_factory(model=StrictAssignmentAll, fields=['title']) form = form_class(data={'title': 'testing setattr'}, files=None) # This line turns on the ValidationError; it avoids the model erroring # when its own __init__() is called when creating form.instance. form.instance._should_error = True self.assertFalse(form.is_valid()) self.assertEqual(form.errors, { '__all__': ['Cannot set attribute'], 'title': ['This field cannot be blank.'] }) class ModelToDictTests(TestCase): def test_many_to_many(self): """Data for a ManyToManyField is a list rather than a lazy QuerySet.""" blue = Colour.objects.create(name='blue') red = Colour.objects.create(name='red') item = ColourfulItem.objects.create() item.colours.set([blue]) data = model_to_dict(item)['colours'] self.assertEqual(data, [blue]) item.colours.set([red]) # If data were a QuerySet, it would be reevaluated here and give "red" # instead of the original value. self.assertEqual(data, [blue])
072c0b9961cabba9792837e076666e5c085950249ff72f8518152c3ecb930aee
import datetime import os import tempfile import uuid from django.core import validators from django.core.exceptions import ValidationError from django.core.files.storage import FileSystemStorage from django.db import models temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) class Person(models.Model): name = models.CharField(max_length=100) class Category(models.Model): name = models.CharField(max_length=20) slug = models.SlugField(max_length=20) url = models.CharField('The URL', max_length=40) def __str__(self): return self.name def __repr__(self): return self.__str__() class Writer(models.Model): name = models.CharField(max_length=50, help_text='Use both first and last names.') class Meta: ordering = ('name',) def __str__(self): return self.name class Article(models.Model): ARTICLE_STATUS = ( (1, 'Draft'), (2, 'Pending'), (3, 'Live'), ) headline = models.CharField(max_length=50) slug = models.SlugField() pub_date = models.DateField() created = models.DateField(editable=False) writer = models.ForeignKey(Writer, models.CASCADE) article = models.TextField() categories = models.ManyToManyField(Category, blank=True) status = models.PositiveIntegerField(choices=ARTICLE_STATUS, blank=True, null=True) def save(self, *args, **kwargs): if not self.id: self.created = datetime.date.today() return super().save(*args, **kwargs) def __str__(self): return self.headline class ImprovedArticle(models.Model): article = models.OneToOneField(Article, models.CASCADE) class ImprovedArticleWithParentLink(models.Model): article = models.OneToOneField(Article, models.CASCADE, parent_link=True) class BetterWriter(Writer): score = models.IntegerField() class Publication(models.Model): title = models.CharField(max_length=30) date_published = models.DateField() def __str__(self): return self.title def default_mode(): return 'di' def default_category(): return 3 class PublicationDefaults(models.Model): MODE_CHOICES = (('di', 'direct'), ('de', 'delayed')) CATEGORY_CHOICES = ((1, 'Games'), (2, 'Comics'), (3, 'Novel')) title = models.CharField(max_length=30) date_published = models.DateField(default=datetime.date.today) datetime_published = models.DateTimeField(default=datetime.datetime(2000, 1, 1)) mode = models.CharField(max_length=2, choices=MODE_CHOICES, default=default_mode) category = models.IntegerField(choices=CATEGORY_CHOICES, default=default_category) active = models.BooleanField(default=True) file = models.FileField(default='default.txt') class Author(models.Model): publication = models.OneToOneField(Publication, models.SET_NULL, null=True, blank=True) full_name = models.CharField(max_length=255) class Author1(models.Model): publication = models.OneToOneField(Publication, models.CASCADE, null=False) full_name = models.CharField(max_length=255) class WriterProfile(models.Model): writer = models.OneToOneField(Writer, models.CASCADE, primary_key=True) age = models.PositiveIntegerField() def __str__(self): return "%s is %s" % (self.writer, self.age) class Document(models.Model): myfile = models.FileField(upload_to='unused', blank=True) class TextFile(models.Model): description = models.CharField(max_length=20) file = models.FileField(storage=temp_storage, upload_to='tests', max_length=15) def __str__(self): return self.description class CustomFileField(models.FileField): def save_form_data(self, instance, data): been_here = getattr(self, 'been_saved', False) assert not been_here, "save_form_data called more than once" setattr(self, 'been_saved', True) class CustomFF(models.Model): f = CustomFileField(upload_to='unused', blank=True) class FilePathModel(models.Model): path = models.FilePathField(path=os.path.dirname(__file__), match='models.py', blank=True) try: from PIL import Image # NOQA: detect if Pillow is installed test_images = True class ImageFile(models.Model): def custom_upload_path(self, filename): path = self.path or 'tests' return '%s/%s' % (path, filename) description = models.CharField(max_length=20) # Deliberately put the image field *after* the width/height fields to # trigger the bug in #10404 with width/height not getting assigned. width = models.IntegerField(editable=False) height = models.IntegerField(editable=False) image = models.ImageField(storage=temp_storage, upload_to=custom_upload_path, width_field='width', height_field='height') path = models.CharField(max_length=16, blank=True, default='') def __str__(self): return self.description class OptionalImageFile(models.Model): def custom_upload_path(self, filename): path = self.path or 'tests' return '%s/%s' % (path, filename) description = models.CharField(max_length=20) image = models.ImageField(storage=temp_storage, upload_to=custom_upload_path, width_field='width', height_field='height', blank=True, null=True) width = models.IntegerField(editable=False, null=True) height = models.IntegerField(editable=False, null=True) path = models.CharField(max_length=16, blank=True, default='') def __str__(self): return self.description class NoExtensionImageFile(models.Model): def upload_to(self, filename): return 'tests/no_extension' description = models.CharField(max_length=20) image = models.ImageField(storage=temp_storage, upload_to=upload_to) def __str__(self): return self.description except ImportError: test_images = False class Homepage(models.Model): url = models.URLField() class Product(models.Model): slug = models.SlugField(unique=True) def __str__(self): return self.slug class Price(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField() class Meta: unique_together = (('price', 'quantity'),) def __str__(self): return "%s for %s" % (self.quantity, self.price) class Triple(models.Model): left = models.IntegerField() middle = models.IntegerField() right = models.IntegerField() class Meta: unique_together = (('left', 'middle'), ('middle', 'right')) class ArticleStatus(models.Model): ARTICLE_STATUS_CHAR = ( ('d', 'Draft'), ('p', 'Pending'), ('l', 'Live'), ) status = models.CharField(max_length=2, choices=ARTICLE_STATUS_CHAR, blank=True, null=True) class Inventory(models.Model): barcode = models.PositiveIntegerField(unique=True) parent = models.ForeignKey('self', models.SET_NULL, to_field='barcode', blank=True, null=True) name = models.CharField(blank=False, max_length=20) class Meta: ordering = ('name',) def __str__(self): return self.name def __repr__(self): return self.__str__() class Book(models.Model): title = models.CharField(max_length=40) author = models.ForeignKey(Writer, models.SET_NULL, blank=True, null=True) special_id = models.IntegerField(blank=True, null=True, unique=True) class Meta: unique_together = ('title', 'author') class BookXtra(models.Model): isbn = models.CharField(max_length=16, unique=True) suffix1 = models.IntegerField(blank=True, default=0) suffix2 = models.IntegerField(blank=True, default=0) class Meta: unique_together = (('suffix1', 'suffix2')) abstract = True class DerivedBook(Book, BookXtra): pass class ExplicitPK(models.Model): key = models.CharField(max_length=20, primary_key=True) desc = models.CharField(max_length=20, blank=True, unique=True) class Meta: unique_together = ('key', 'desc') def __str__(self): return self.key class Post(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateField() def __str__(self): return self.title class DateTimePost(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateTimeField(editable=False) def __str__(self): return self.title class DerivedPost(Post): pass class BigInt(models.Model): biggie = models.BigIntegerField() def __str__(self): return str(self.biggie) class MarkupField(models.CharField): def __init__(self, *args, **kwargs): kwargs["max_length"] = 20 super().__init__(*args, **kwargs) def formfield(self, **kwargs): # don't allow this field to be used in form (real use-case might be # that you know the markup will always be X, but it is among an app # that allows the user to say it could be something else) # regressed at r10062 return None class CustomFieldForExclusionModel(models.Model): name = models.CharField(max_length=10) markup = MarkupField() class FlexibleDatePost(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateField(blank=True, null=True) class Colour(models.Model): name = models.CharField(max_length=50) def __iter__(self): yield from range(5) def __str__(self): return self.name class ColourfulItem(models.Model): name = models.CharField(max_length=50) colours = models.ManyToManyField(Colour) class CustomErrorMessage(models.Model): name1 = models.CharField( max_length=50, validators=[validators.validate_slug], error_messages={'invalid': 'Model custom error message.'}, ) name2 = models.CharField( max_length=50, validators=[validators.validate_slug], error_messages={'invalid': 'Model custom error message.'}, ) def clean(self): if self.name1 == 'FORBIDDEN_VALUE': raise ValidationError({'name1': [ValidationError('Model.clean() error messages.')]}) elif self.name1 == 'FORBIDDEN_VALUE2': raise ValidationError({'name1': 'Model.clean() error messages (simpler syntax).'}) elif self.name1 == 'GLOBAL_ERROR': raise ValidationError("Global error message.") def today_callable_dict(): return {"last_action__gte": datetime.datetime.today()} def today_callable_q(): return models.Q(last_action__gte=datetime.datetime.today()) class Character(models.Model): username = models.CharField(max_length=100) last_action = models.DateTimeField() class StumpJoke(models.Model): most_recently_fooled = models.ForeignKey( Character, models.CASCADE, limit_choices_to=today_callable_dict, related_name="+", ) has_fooled_today = models.ManyToManyField(Character, limit_choices_to=today_callable_q, related_name="+") # Model for #13776 class Student(models.Model): character = models.ForeignKey(Character, models.CASCADE) study = models.CharField(max_length=30) # Model for #639 class Photo(models.Model): title = models.CharField(max_length=30) image = models.FileField(storage=temp_storage, upload_to='tests') # Support code for the tests; this keeps track of how many times save() # gets called on each instance. def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._savecount = 0 def save(self, force_insert=False, force_update=False): super().save(force_insert, force_update) self._savecount += 1 class UUIDPK(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=30) # Models for #24706 class StrictAssignmentFieldSpecific(models.Model): title = models.CharField(max_length=30) _should_error = False def __setattr__(self, key, value): if self._should_error is True: raise ValidationError(message={key: "Cannot set attribute"}, code='invalid') super().__setattr__(key, value) class StrictAssignmentAll(models.Model): title = models.CharField(max_length=30) _should_error = False def __setattr__(self, key, value): if self._should_error is True: raise ValidationError(message="Cannot set attribute", code='invalid') super().__setattr__(key, value) # A model with ForeignKey(blank=False, null=True) class Award(models.Model): name = models.CharField(max_length=30) character = models.ForeignKey(Character, models.SET_NULL, blank=False, null=True) class NullableUniqueCharFieldModel(models.Model): codename = models.CharField(max_length=50, blank=True, null=True, unique=True)
b07e1fdaefc2fee16ed0feac2b8210836cb279be5267ad8d3e90c154e5853462
from django.db.models import CharField, Max from django.db.models.functions import Lower from django.test import TestCase, skipUnlessDBFeature from django.test.utils import register_lookup from .models import Celebrity, Fan, Staff, StaffTag, Tag @skipUnlessDBFeature('can_distinct_on_fields') @skipUnlessDBFeature('supports_nullable_unique_constraints') class DistinctOnTests(TestCase): @classmethod def setUpTestData(cls): cls.t1 = Tag.objects.create(name='t1') cls.t2 = Tag.objects.create(name='t2', parent=cls.t1) cls.t3 = Tag.objects.create(name='t3', parent=cls.t1) cls.t4 = Tag.objects.create(name='t4', parent=cls.t3) cls.t5 = Tag.objects.create(name='t5', parent=cls.t3) cls.p1_o1 = Staff.objects.create(id=1, name="p1", organisation="o1") cls.p2_o1 = Staff.objects.create(id=2, name="p2", organisation="o1") cls.p3_o1 = Staff.objects.create(id=3, name="p3", organisation="o1") cls.p1_o2 = Staff.objects.create(id=4, name="p1", organisation="o2") cls.p1_o1.coworkers.add(cls.p2_o1, cls.p3_o1) StaffTag.objects.create(staff=cls.p1_o1, tag=cls.t1) StaffTag.objects.create(staff=cls.p1_o1, tag=cls.t1) celeb1 = Celebrity.objects.create(name="c1") celeb2 = Celebrity.objects.create(name="c2") cls.fan1 = Fan.objects.create(fan_of=celeb1) cls.fan2 = Fan.objects.create(fan_of=celeb1) cls.fan3 = Fan.objects.create(fan_of=celeb2) def test_basic_distinct_on(self): """QuerySet.distinct('field', ...) works""" # (qset, expected) tuples qsets = ( ( Staff.objects.distinct().order_by('name'), ['<Staff: p1>', '<Staff: p1>', '<Staff: p2>', '<Staff: p3>'], ), ( Staff.objects.distinct('name').order_by('name'), ['<Staff: p1>', '<Staff: p2>', '<Staff: p3>'], ), ( Staff.objects.distinct('organisation').order_by('organisation', 'name'), ['<Staff: p1>', '<Staff: p1>'], ), ( Staff.objects.distinct('name', 'organisation').order_by('name', 'organisation'), ['<Staff: p1>', '<Staff: p1>', '<Staff: p2>', '<Staff: p3>'], ), ( Celebrity.objects.filter(fan__in=[self.fan1, self.fan2, self.fan3]).distinct('name').order_by('name'), ['<Celebrity: c1>', '<Celebrity: c2>'], ), # Does combining querysets work? ( (Celebrity.objects.filter(fan__in=[self.fan1, self.fan2]). distinct('name').order_by('name') | Celebrity.objects.filter(fan__in=[self.fan3]). distinct('name').order_by('name')), ['<Celebrity: c1>', '<Celebrity: c2>'], ), ( StaffTag.objects.distinct('staff', 'tag'), ['<StaffTag: t1 -> p1>'], ), ( Tag.objects.order_by('parent__pk', 'pk').distinct('parent'), ['<Tag: t2>', '<Tag: t4>', '<Tag: t1>'], ), ( StaffTag.objects.select_related('staff').distinct('staff__name').order_by('staff__name'), ['<StaffTag: t1 -> p1>'], ), # Fetch the alphabetically first coworker for each worker ( (Staff.objects.distinct('id').order_by('id', 'coworkers__name'). values_list('id', 'coworkers__name')), ["(1, 'p2')", "(2, 'p1')", "(3, 'p1')", "(4, None)"] ), ) for qset, expected in qsets: self.assertQuerysetEqual(qset, expected) self.assertEqual(qset.count(), len(expected)) # Combining queries with different distinct_fields is not allowed. base_qs = Celebrity.objects.all() with self.assertRaisesMessage(AssertionError, "Cannot combine queries with different distinct fields."): base_qs.distinct('id') & base_qs.distinct('name') # Test join unreffing c1 = Celebrity.objects.distinct('greatest_fan__id', 'greatest_fan__fan_of') self.assertIn('OUTER JOIN', str(c1.query)) c2 = c1.distinct('pk') self.assertNotIn('OUTER JOIN', str(c2.query)) def test_transform(self): new_name = self.t1.name.upper() self.assertNotEqual(self.t1.name, new_name) Tag.objects.create(name=new_name) with register_lookup(CharField, Lower): self.assertCountEqual( Tag.objects.order_by().distinct('name__lower'), [self.t1, self.t2, self.t3, self.t4, self.t5], ) def test_distinct_not_implemented_checks(self): # distinct + annotate not allowed msg = 'annotate() + distinct(fields) is not implemented.' with self.assertRaisesMessage(NotImplementedError, msg): Celebrity.objects.annotate(Max('id')).distinct('id')[0] with self.assertRaisesMessage(NotImplementedError, msg): Celebrity.objects.distinct('id').annotate(Max('id'))[0] # However this check is done only when the query executes, so you # can use distinct() to remove the fields before execution. Celebrity.objects.distinct('id').annotate(Max('id')).distinct()[0] # distinct + aggregate not allowed msg = 'aggregate() + distinct(fields) not implemented.' with self.assertRaisesMessage(NotImplementedError, msg): Celebrity.objects.distinct('id').aggregate(Max('id')) def test_distinct_on_in_ordered_subquery(self): qs = Staff.objects.distinct('name').order_by('name', 'id') qs = Staff.objects.filter(pk__in=qs).order_by('name') self.assertSequenceEqual(qs, [self.p1_o1, self.p2_o1, self.p3_o1]) qs = Staff.objects.distinct('name').order_by('name', '-id') qs = Staff.objects.filter(pk__in=qs).order_by('name') self.assertSequenceEqual(qs, [self.p1_o2, self.p2_o1, self.p3_o1]) def test_distinct_on_get_ordering_preserved(self): """ Ordering shouldn't be cleared when distinct on fields are specified. refs #25081 """ staff = Staff.objects.distinct('name').order_by('name', '-organisation').get(name='p1') self.assertEqual(staff.organisation, 'o2')
04a657a19f23defdbc236cc9f50045fef8b02d5c7364bc1aec39bffe0b154e96
""" Distance and Area objects to allow for sensible and convenient calculation and conversions. Here are some tests. """ import unittest from django.contrib.gis.measure import A, Area, D, Distance class DistanceTest(unittest.TestCase): "Testing the Distance object" def test_init(self): "Testing initialization from valid units" d = Distance(m=100) self.assertEqual(d.m, 100) d1, d2, d3 = D(m=100), D(meter=100), D(metre=100) for d in (d1, d2, d3): self.assertEqual(d.m, 100) d = D(nm=100) self.assertEqual(d.m, 185200) y1, y2, y3 = D(yd=100), D(yard=100), D(Yard=100) for d in (y1, y2, y3): self.assertEqual(d.yd, 100) mm1, mm2 = D(millimeter=1000), D(MiLLiMeTeR=1000) for d in (mm1, mm2): self.assertEqual(d.m, 1.0) self.assertEqual(d.mm, 1000.0) def test_init_invalid(self): "Testing initialization from invalid units" with self.assertRaises(AttributeError): D(banana=100) def test_access(self): "Testing access in different units" d = D(m=100) self.assertEqual(d.km, 0.1) self.assertAlmostEqual(d.ft, 328.084, 3) def test_access_invalid(self): "Testing access in invalid units" d = D(m=100) self.assertFalse(hasattr(d, 'banana')) def test_addition(self): "Test addition & subtraction" d1 = D(m=100) d2 = D(m=200) d3 = d1 + d2 self.assertEqual(d3.m, 300) d3 += d1 self.assertEqual(d3.m, 400) d4 = d1 - d2 self.assertEqual(d4.m, -100) d4 -= d1 self.assertEqual(d4.m, -200) with self.assertRaises(TypeError): d1 + 1 with self.assertRaises(TypeError): d1 - 1 with self.assertRaises(TypeError): d1 += 1 with self.assertRaises(TypeError): d1 -= 1 def test_multiplication(self): "Test multiplication & division" d1 = D(m=100) d3 = d1 * 2 self.assertEqual(d3.m, 200) d3 = 2 * d1 self.assertEqual(d3.m, 200) d3 *= 5 self.assertEqual(d3.m, 1000) d4 = d1 / 2 self.assertEqual(d4.m, 50) d4 /= 5 self.assertEqual(d4.m, 10) d5 = d1 / D(m=2) self.assertEqual(d5, 50) a5 = d1 * D(m=10) self.assertIsInstance(a5, Area) self.assertEqual(a5.sq_m, 100 * 10) with self.assertRaises(TypeError): d1 *= D(m=1) with self.assertRaises(TypeError): d1 /= D(m=1) def test_unit_conversions(self): "Testing default units during maths" d1 = D(m=100) d2 = D(km=1) d3 = d1 + d2 self.assertEqual(d3._default_unit, 'm') d4 = d2 + d1 self.assertEqual(d4._default_unit, 'km') d5 = d1 * 2 self.assertEqual(d5._default_unit, 'm') d6 = d1 / 2 self.assertEqual(d6._default_unit, 'm') def test_comparisons(self): "Testing comparisons" d1 = D(m=100) d2 = D(km=1) d3 = D(km=0) self.assertGreater(d2, d1) self.assertEqual(d1, d1) self.assertLess(d1, d2) self.assertFalse(d3) def test_units_str(self): "Testing conversion to strings" d1 = D(m=100) d2 = D(km=3.5) self.assertEqual(str(d1), '100.0 m') self.assertEqual(str(d2), '3.5 km') self.assertEqual(repr(d1), 'Distance(m=100.0)') self.assertEqual(repr(d2), 'Distance(km=3.5)') def test_furlong(self): d = D(m=201.168) self.assertEqual(d.furlong, 1) def test_unit_att_name(self): "Testing the `unit_attname` class method" unit_tuple = [('Yard', 'yd'), ('Nautical Mile', 'nm'), ('German legal metre', 'german_m'), ('Indian yard', 'indian_yd'), ('Chain (Sears)', 'chain_sears'), ('Chain', 'chain'), ('Furrow Long', 'furlong')] for nm, att in unit_tuple: with self.subTest(nm=nm): self.assertEqual(att, D.unit_attname(nm)) class AreaTest(unittest.TestCase): "Testing the Area object" def test_init(self): "Testing initialization from valid units" a = Area(sq_m=100) self.assertEqual(a.sq_m, 100) a = A(sq_m=100) self.assertEqual(a.sq_m, 100) a = A(sq_mi=100) self.assertEqual(a.sq_m, 258998811.0336) def test_init_invalid_a(self): "Testing initialization from invalid units" with self.assertRaises(AttributeError): A(banana=100) def test_access(self): "Testing access in different units" a = A(sq_m=100) self.assertEqual(a.sq_km, 0.0001) self.assertAlmostEqual(a.sq_ft, 1076.391, 3) def test_access_invalid_a(self): "Testing access in invalid units" a = A(sq_m=100) self.assertFalse(hasattr(a, 'banana')) def test_addition(self): "Test addition & subtraction" a1 = A(sq_m=100) a2 = A(sq_m=200) a3 = a1 + a2 self.assertEqual(a3.sq_m, 300) a3 += a1 self.assertEqual(a3.sq_m, 400) a4 = a1 - a2 self.assertEqual(a4.sq_m, -100) a4 -= a1 self.assertEqual(a4.sq_m, -200) with self.assertRaises(TypeError): a1 + 1 with self.assertRaises(TypeError): a1 - 1 with self.assertRaises(TypeError): a1 += 1 with self.assertRaises(TypeError): a1 -= 1 def test_multiplication(self): "Test multiplication & division" a1 = A(sq_m=100) a3 = a1 * 2 self.assertEqual(a3.sq_m, 200) a3 = 2 * a1 self.assertEqual(a3.sq_m, 200) a3 *= 5 self.assertEqual(a3.sq_m, 1000) a4 = a1 / 2 self.assertEqual(a4.sq_m, 50) a4 /= 5 self.assertEqual(a4.sq_m, 10) with self.assertRaises(TypeError): a1 * A(sq_m=1) with self.assertRaises(TypeError): a1 *= A(sq_m=1) with self.assertRaises(TypeError): a1 / A(sq_m=1) with self.assertRaises(TypeError): a1 /= A(sq_m=1) def test_unit_conversions(self): "Testing default units during maths" a1 = A(sq_m=100) a2 = A(sq_km=1) a3 = a1 + a2 self.assertEqual(a3._default_unit, 'sq_m') a4 = a2 + a1 self.assertEqual(a4._default_unit, 'sq_km') a5 = a1 * 2 self.assertEqual(a5._default_unit, 'sq_m') a6 = a1 / 2 self.assertEqual(a6._default_unit, 'sq_m') def test_comparisons(self): "Testing comparisons" a1 = A(sq_m=100) a2 = A(sq_km=1) a3 = A(sq_km=0) self.assertGreater(a2, a1) self.assertEqual(a1, a1) self.assertLess(a1, a2) self.assertFalse(a3) def test_units_str(self): "Testing conversion to strings" a1 = A(sq_m=100) a2 = A(sq_km=3.5) self.assertEqual(str(a1), '100.0 sq_m') self.assertEqual(str(a2), '3.5 sq_km') self.assertEqual(repr(a1), 'Area(sq_m=100.0)') self.assertEqual(repr(a2), 'Area(sq_km=3.5)') def suite(): s = unittest.TestSuite() s.addTest(unittest.makeSuite(DistanceTest)) s.addTest(unittest.makeSuite(AreaTest)) return s def run(verbosity=2): unittest.TextTestRunner(verbosity=verbosity).run(suite()) if __name__ == "__main__": run()
0e8a81474927aa17f17ff7bb86de99550ab82322ffa0dd40e30dbc1adba32fd2
import unittest from django.core.exceptions import ImproperlyConfigured from django.db import ProgrammingError try: from django.contrib.gis.db.backends.postgis.operations import PostGISOperations HAS_POSTGRES = True except ImportError: HAS_POSTGRES = False if HAS_POSTGRES: class FakeConnection: def __init__(self): self.settings_dict = { 'NAME': 'test', } class FakePostGISOperations(PostGISOperations): def __init__(self, version=None): self.version = version self.connection = FakeConnection() def _get_postgis_func(self, func): if func == 'postgis_lib_version': if self.version is None: raise ProgrammingError else: return self.version elif func == 'version': pass else: raise NotImplementedError('This function was not expected to be called') @unittest.skipUnless(HAS_POSTGRES, "The psycopg2 driver is needed for these tests") class TestPostGISVersionCheck(unittest.TestCase): """ The PostGIS version check parses correctly the version numbers """ def test_get_version(self): expect = '1.0.0' ops = FakePostGISOperations(expect) actual = ops.postgis_lib_version() self.assertEqual(expect, actual) def test_version_classic_tuple(self): expect = ('1.2.3', 1, 2, 3) ops = FakePostGISOperations(expect[0]) actual = ops.postgis_version_tuple() self.assertEqual(expect, actual) def test_version_dev_tuple(self): expect = ('1.2.3dev', 1, 2, 3) ops = FakePostGISOperations(expect[0]) actual = ops.postgis_version_tuple() self.assertEqual(expect, actual) def test_version_loose_tuple(self): expect = ('1.2.3b1.dev0', 1, 2, 3) ops = FakePostGISOperations(expect[0]) actual = ops.postgis_version_tuple() self.assertEqual(expect, actual) def test_valid_version_numbers(self): versions = [ ('1.3.0', 1, 3, 0), ('2.1.1', 2, 1, 1), ('2.2.0dev', 2, 2, 0), ] for version in versions: with self.subTest(version=version): ops = FakePostGISOperations(version[0]) actual = ops.spatial_version self.assertEqual(version[1:], actual) def test_no_version_number(self): ops = FakePostGISOperations() with self.assertRaises(ImproperlyConfigured): ops.spatial_version
a93fa152d76cd5bc52d9794d070a2574d70558cf51d76edfe3e46d28b72d5075
import os from unittest import mock, skipUnless from django.conf import settings from django.contrib.gis.geoip2 import HAS_GEOIP2 from django.contrib.gis.geos import GEOSGeometry from django.test import SimpleTestCase if HAS_GEOIP2: from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception # Note: Requires both the GeoIP country and city datasets. # The GEOIP_DATA path should be the only setting set (the directory # should contain links or the actual database files 'GeoLite2-City.mmdb' and # 'GeoLite2-City.mmdb'. @skipUnless( HAS_GEOIP2 and getattr(settings, "GEOIP_PATH", None), "GeoIP is required along with the GEOIP_PATH setting." ) class GeoIPTest(SimpleTestCase): addr = '128.249.1.1' fqdn = 'tmc.edu' def test01_init(self): "GeoIP initialization." g1 = GeoIP2() # Everything inferred from GeoIP path path = settings.GEOIP_PATH g2 = GeoIP2(path, 0) # Passing in data path explicitly. g3 = GeoIP2.open(path, 0) # MaxMind Python API syntax. for g in (g1, g2, g3): self.assertTrue(g._country) self.assertTrue(g._city) # Only passing in the location of one database. city = os.path.join(path, 'GeoLite2-City.mmdb') cntry = os.path.join(path, 'GeoLite2-Country.mmdb') g4 = GeoIP2(city, country='') self.assertIsNone(g4._country) g5 = GeoIP2(cntry, city='') self.assertIsNone(g5._city) # Improper parameters. bad_params = (23, 'foo', 15.23) for bad in bad_params: with self.assertRaises(GeoIP2Exception): GeoIP2(cache=bad) if isinstance(bad, str): e = GeoIP2Exception else: e = TypeError with self.assertRaises(e): GeoIP2(bad, 0) def test_no_database_file(self): invalid_path = os.path.join(os.path.dirname(__file__), 'data') msg = 'Could not load a database from %s.' % invalid_path with self.assertRaisesMessage(GeoIP2Exception, msg): GeoIP2(invalid_path) def test02_bad_query(self): "GeoIP query parameter checking." cntry_g = GeoIP2(city='<foo>') # No city database available, these calls should fail. with self.assertRaises(GeoIP2Exception): cntry_g.city('tmc.edu') with self.assertRaises(GeoIP2Exception): cntry_g.coords('tmc.edu') # Non-string query should raise TypeError with self.assertRaises(TypeError): cntry_g.country_code(17) with self.assertRaises(TypeError): cntry_g.country_name(GeoIP2) @mock.patch('socket.gethostbyname') def test03_country(self, gethostbyname): "GeoIP country querying methods." gethostbyname.return_value = '128.249.1.1' g = GeoIP2(city='<foo>') for query in (self.fqdn, self.addr): self.assertEqual( 'US', g.country_code(query), 'Failed for func country_code and query %s' % query ) self.assertEqual( 'United States', g.country_name(query), 'Failed for func country_name and query %s' % query ) self.assertEqual( {'country_code': 'US', 'country_name': 'United States'}, g.country(query) ) @mock.patch('socket.gethostbyname') def test04_city(self, gethostbyname): "GeoIP city querying methods." gethostbyname.return_value = '128.249.1.1' g = GeoIP2(country='<foo>') for query in (self.fqdn, self.addr): # Country queries should still work. self.assertEqual( 'US', g.country_code(query), 'Failed for func country_code and query %s' % query ) self.assertEqual( 'United States', g.country_name(query), 'Failed for func country_name and query %s' % query ) self.assertEqual( {'country_code': 'US', 'country_name': 'United States'}, g.country(query) ) # City information dictionary. d = g.city(query) self.assertEqual('NA', d['continent_code']) self.assertEqual('North America', d['continent_name']) self.assertEqual('US', d['country_code']) self.assertEqual('Houston', d['city']) self.assertEqual('TX', d['region']) self.assertEqual('America/Chicago', d['time_zone']) self.assertFalse(d['is_in_european_union']) geom = g.geos(query) self.assertIsInstance(geom, GEOSGeometry) for e1, e2 in (geom.tuple, g.coords(query), g.lon_lat(query), g.lat_lon(query)): self.assertIsInstance(e1, float) self.assertIsInstance(e2, float) def test06_ipv6_query(self): "GeoIP can lookup IPv6 addresses." g = GeoIP2() d = g.city('2002:81ed:c9a5::81ed:c9a5') # IPv6 address for www.nhm.ku.edu self.assertEqual('US', d['country_code']) self.assertEqual('Lawrence', d['city']) self.assertEqual('KS', d['region']) def test_repr(self): path = settings.GEOIP_PATH g = GeoIP2(path=path) meta = g._reader.metadata() version = '%s.%s' % (meta.binary_format_major_version, meta.binary_format_minor_version) country_path = g._country_file city_path = g._city_file expected = '<GeoIP2 [v%(version)s] _country_file="%(country)s", _city_file="%(city)s">' % { 'version': version, 'country': country_path, 'city': city_path, } self.assertEqual(repr(g), expected) @mock.patch('socket.gethostbyname', return_value='expected') def test_check_query(self, gethostbyname): g = GeoIP2() self.assertEqual(g._check_query('127.0.0.1'), '127.0.0.1') self.assertEqual(g._check_query('2002:81ed:c9a5::81ed:c9a5'), '2002:81ed:c9a5::81ed:c9a5') self.assertEqual(g._check_query('invalid-ip-address'), 'expected')