repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_fields/test_decimalfield.py
tests/model_fields/test_decimalfield.py
import math from decimal import Decimal from unittest import mock from django.core import validators from django.core.exceptions import ValidationError from django.db import connection, models from django.test import TestCase from .models import BigD, Foo class DecimalFieldTests(TestCase): def test_to_python(self): f = models.DecimalField(max_digits=4, decimal_places=2) self.assertEqual(f.to_python(3), Decimal("3")) self.assertEqual(f.to_python("3.14"), Decimal("3.14")) # to_python() converts floats and honors max_digits. self.assertEqual(f.to_python(3.1415926535897), Decimal("3.142")) self.assertEqual(f.to_python(2.4), Decimal("2.400")) # Uses default rounding of ROUND_HALF_EVEN. self.assertEqual(f.to_python(2.0625), Decimal("2.062")) self.assertEqual(f.to_python(2.1875), Decimal("2.188")) def test_invalid_value(self): field = models.DecimalField(max_digits=4, decimal_places=2) msg = "“%s” value must be a decimal number." tests = [ (), [], {}, set(), object(), complex(), "non-numeric string", b"non-numeric byte-string", ] for value in tests: with self.subTest(value): with self.assertRaisesMessage(ValidationError, msg % (value,)): field.clean(value, None) def test_default(self): f = models.DecimalField(default=Decimal("0.00")) self.assertEqual(f.get_default(), Decimal("0.00")) def test_get_prep_value(self): f = models.DecimalField(max_digits=5, decimal_places=1) self.assertIsNone(f.get_prep_value(None)) self.assertEqual(f.get_prep_value("2.4"), Decimal("2.4")) def test_get_db_prep_value(self): """ DecimalField.get_db_prep_value() must call DatabaseOperations.adapt_decimalfield_value(). """ f = models.DecimalField(max_digits=5, decimal_places=1) # None of the built-in database backends implement # adapt_decimalfield_value(), so this must be confirmed with mocking. with mock.patch.object( connection.ops.__class__, "adapt_decimalfield_value" ) as adapt_decimalfield_value: f.get_db_prep_value("2.4", connection) adapt_decimalfield_value.assert_called_with(Decimal("2.4"), 5, 1) def test_filter_with_strings(self): """ Should be able to filter decimal fields using strings (#8023). """ foo = Foo.objects.create(a="abc", d=Decimal("12.34")) self.assertEqual(list(Foo.objects.filter(d="12.34")), [foo]) def test_save_without_float_conversion(self): """ Ensure decimals don't go through a corrupting float conversion during save (#5079). """ bd = BigD(d="12.9") bd.save() bd = BigD.objects.get(pk=bd.pk) self.assertEqual(bd.d, Decimal("12.9")) def test_save_nan_invalid(self): msg = "“nan” value must be a decimal number." for value in [float("nan"), math.nan, "nan"]: with self.subTest(value), self.assertRaisesMessage(ValidationError, msg): BigD.objects.create(d=value) def test_save_inf_invalid(self): msg = "“inf” value must be a decimal number." for value in [float("inf"), math.inf, "inf"]: with self.subTest(value), self.assertRaisesMessage(ValidationError, msg): BigD.objects.create(d=value) msg = "“-inf” value must be a decimal number." for value in [float("-inf"), -math.inf, "-inf"]: with self.subTest(value), self.assertRaisesMessage(ValidationError, msg): BigD.objects.create(d=value) def test_fetch_from_db_without_float_rounding(self): big_decimal = BigD.objects.create(d=Decimal(".100000000000000000000000000005")) big_decimal.refresh_from_db() self.assertEqual(big_decimal.d, Decimal(".100000000000000000000000000005")) def test_lookup_really_big_value(self): """ Really big values can be used in a filter statement. """ # This should not crash. self.assertSequenceEqual(Foo.objects.filter(d__gte=100000000000), []) def test_lookup_decimal_larger_than_max_digits(self): self.assertSequenceEqual(Foo.objects.filter(d__lte=Decimal("123456")), []) def test_max_digits_validation(self): field = models.DecimalField(max_digits=2) expected_message = validators.DecimalValidator.messages["max_digits"] % { "max": 2 } with self.assertRaisesMessage(ValidationError, expected_message): field.clean(100, None) def test_max_decimal_places_validation(self): field = models.DecimalField(decimal_places=1) expected_message = validators.DecimalValidator.messages[ "max_decimal_places" ] % {"max": 1} with self.assertRaisesMessage(ValidationError, expected_message): field.clean(Decimal("0.99"), None) def test_max_whole_digits_validation(self): field = models.DecimalField(max_digits=3, decimal_places=1) expected_message = validators.DecimalValidator.messages["max_whole_digits"] % { "max": 2 } with self.assertRaisesMessage(ValidationError, expected_message): field.clean(Decimal("999"), None) def test_roundtrip_with_trailing_zeros(self): """Trailing zeros in the fractional part aren't truncated.""" obj = Foo.objects.create(a="bar", d=Decimal("8.320")) obj.refresh_from_db() self.assertEqual(obj.d.compare_total(Decimal("8.320")), Decimal("0"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_fields/__init__.py
tests/model_fields/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_fields/test_mixins.py
tests/model_fields/test_mixins.py
from django.db.models.fields.mixins import FieldCacheMixin from django.test import SimpleTestCase from django.utils.functional import cached_property from .models import Foo class Example(FieldCacheMixin): @cached_property def cache_name(self): return "example" class FieldCacheMixinTests(SimpleTestCase): def setUp(self): self.instance = Foo() self.field = Example() def test_cache_name_not_implemented(self): with self.assertRaises(NotImplementedError): FieldCacheMixin().cache_name def test_cache_name(self): result = Example().cache_name self.assertEqual(result, "example") def test_get_cached_value_missing(self): with self.assertRaises(KeyError): self.field.get_cached_value(self.instance) def test_get_cached_value_default(self): default = object() result = self.field.get_cached_value(self.instance, default=default) self.assertIs(result, default) def test_get_cached_value_after_set(self): value = object() self.field.set_cached_value(self.instance, value) result = self.field.get_cached_value(self.instance) self.assertIs(result, value) def test_is_cached_false(self): result = self.field.is_cached(self.instance) self.assertFalse(result) def test_is_cached_true(self): self.field.set_cached_value(self.instance, 1) result = self.field.is_cached(self.instance) self.assertTrue(result) def test_delete_cached_value(self): self.field.set_cached_value(self.instance, 1) self.field.delete_cached_value(self.instance) result = self.field.is_cached(self.instance) self.assertFalse(result)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_fields/test_textfield.py
tests/model_fields/test_textfield.py
from django import forms from django.db import models from django.test import SimpleTestCase, TestCase from .models import Post class TextFieldTests(TestCase): def test_max_length_passed_to_formfield(self): """ TextField passes its max_length attribute to form fields created using their formfield() method. """ tf1 = models.TextField() tf2 = models.TextField(max_length=2345) self.assertIsNone(tf1.formfield().max_length) self.assertEqual(2345, tf2.formfield().max_length) def test_choices_generates_select_widget(self): """A TextField with choices uses a Select widget.""" f = models.TextField(choices=[("A", "A"), ("B", "B")]) self.assertIsInstance(f.formfield().widget, forms.Select) def test_to_python(self): """TextField.to_python() should return a string.""" f = models.TextField() self.assertEqual(f.to_python(1), "1") def test_lookup_integer_in_textfield(self): self.assertEqual(Post.objects.filter(body=24).count(), 0) def test_emoji(self): p = Post.objects.create(title="Whatever", body="Smile 😀.") p.refresh_from_db() self.assertEqual(p.body, "Smile 😀.") class TestMethods(SimpleTestCase): def test_deconstruct(self): field = models.TextField() *_, kwargs = field.deconstruct() self.assertEqual(kwargs, {}) field = models.TextField(db_collation="utf8_esperanto_ci") *_, kwargs = field.deconstruct() self.assertEqual(kwargs, {"db_collation": "utf8_esperanto_ci"})
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_fields/tests.py
tests/model_fields/tests.py
import pickle from django import forms from django.core.exceptions import ValidationError from django.db import models from django.test import SimpleTestCase, TestCase from django.utils.choices import CallableChoiceIterator from django.utils.functional import lazy from .models import ( Bar, Choiceful, Foo, RenamedField, VerboseNameField, Whiz, WhizDelayed, WhizIter, WhizIterEmpty, ) class Nested: class Field(models.Field): pass class BasicFieldTests(SimpleTestCase): def test_show_hidden_initial(self): """ Fields with choices respect show_hidden_initial as a kwarg to formfield(). """ choices = [(0, 0), (1, 1)] model_field = models.Field(choices=choices) form_field = model_field.formfield(show_hidden_initial=True) self.assertTrue(form_field.show_hidden_initial) form_field = model_field.formfield(show_hidden_initial=False) self.assertFalse(form_field.show_hidden_initial) def test_field_repr(self): """ __repr__() of a field displays its name. """ f = Foo._meta.get_field("a") self.assertEqual(repr(f), "<django.db.models.fields.CharField: a>") f = models.fields.CharField() self.assertEqual(repr(f), "<django.db.models.fields.CharField>") def test_field_repr_nested(self): """__repr__() uses __qualname__ for nested class support.""" self.assertEqual(repr(Nested.Field()), "<model_fields.tests.Nested.Field>") def test_field_name(self): """ A defined field name (name="fieldname") is used instead of the model model's attribute name (modelname). """ instance = RenamedField() self.assertTrue(hasattr(instance, "get_fieldname_display")) self.assertFalse(hasattr(instance, "get_modelname_display")) def test_field_verbose_name(self): m = VerboseNameField for i in range(1, 22): self.assertEqual( m._meta.get_field("field%d" % i).verbose_name, "verbose field%d" % i ) self.assertEqual(m._meta.get_field("id").verbose_name, "verbose pk") def test_choices_form_class(self): """Can supply a custom choices form class to Field.formfield()""" choices = [("a", "a")] field = models.CharField(choices=choices) klass = forms.TypedMultipleChoiceField self.assertIsInstance(field.formfield(choices_form_class=klass), klass) def test_formfield_disabled(self): """Field.formfield() sets disabled for fields with choices.""" field = models.CharField(choices=[("a", "b")]) form_field = field.formfield(disabled=True) self.assertIs(form_field.disabled, True) def test_field_str(self): f = models.Field() self.assertEqual(str(f), "<django.db.models.fields.Field>") f = Foo._meta.get_field("a") self.assertEqual(str(f), "model_fields.Foo.a") def test_field_ordering(self): """Fields are ordered based on their creation.""" f1 = models.Field() f2 = models.Field(auto_created=True) f3 = models.Field() self.assertLess(f2, f1) self.assertGreater(f3, f1) self.assertIsNotNone(f1) self.assertNotIn(f2, (None, 1, "")) def test_field_instance_is_picklable(self): """Field instances can be pickled.""" field = models.Field(max_length=100, default="a string") # Must be picklable with this cached property populated (#28188). field._get_default pickle.dumps(field) def test_deconstruct_nested_field(self): """deconstruct() uses __qualname__ for nested class support.""" name, path, args, kwargs = Nested.Field().deconstruct() self.assertEqual(path, "model_fields.tests.Nested.Field") def test_abstract_inherited_fields(self): """Field instances from abstract models are not equal.""" class AbstractModel(models.Model): field = models.IntegerField() class Meta: abstract = True class InheritAbstractModel1(AbstractModel): pass class InheritAbstractModel2(AbstractModel): pass abstract_model_field = AbstractModel._meta.get_field("field") inherit1_model_field = InheritAbstractModel1._meta.get_field("field") inherit2_model_field = InheritAbstractModel2._meta.get_field("field") self.assertNotEqual(abstract_model_field, inherit1_model_field) self.assertNotEqual(abstract_model_field, inherit2_model_field) self.assertNotEqual(inherit1_model_field, inherit2_model_field) self.assertLess(abstract_model_field, inherit1_model_field) self.assertLess(abstract_model_field, inherit2_model_field) self.assertLess(inherit1_model_field, inherit2_model_field) def test_hash_immutability(self): field = models.IntegerField() field_hash = hash(field) class MyModel(models.Model): rank = field self.assertEqual(field_hash, hash(field)) class ChoicesTests(SimpleTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.no_choices = Choiceful._meta.get_field("no_choices") cls.empty_choices = Choiceful._meta.get_field("empty_choices") cls.empty_choices_bool = Choiceful._meta.get_field("empty_choices_bool") cls.empty_choices_text = Choiceful._meta.get_field("empty_choices_text") cls.with_choices = Choiceful._meta.get_field("with_choices") cls.with_choices_dict = Choiceful._meta.get_field("with_choices_dict") cls.with_choices_nested_dict = Choiceful._meta.get_field( "with_choices_nested_dict" ) cls.choices_from_enum = Choiceful._meta.get_field("choices_from_enum") cls.choices_from_iterator = Choiceful._meta.get_field("choices_from_iterator") cls.choices_from_callable = Choiceful._meta.get_field("choices_from_callable") def test_choices(self): self.assertIsNone(self.no_choices.choices) self.assertEqual(self.empty_choices.choices, []) self.assertEqual(self.empty_choices_bool.choices, []) self.assertEqual(self.empty_choices_text.choices, []) self.assertEqual(self.with_choices.choices, [(1, "A")]) self.assertEqual(self.with_choices_dict.choices, [(1, "A")]) self.assertEqual(self.with_choices_nested_dict.choices, [("Thing", [(1, "A")])]) self.assertEqual( self.choices_from_iterator.choices, [(0, "0"), (1, "1"), (2, "2")] ) self.assertIsInstance( self.choices_from_callable.choices, CallableChoiceIterator ) self.assertEqual( self.choices_from_callable.choices.func(), [(0, "0"), (1, "1"), (2, "2")] ) def test_choices_slice(self): for choices, expected_slice in [ (self.empty_choices.choices, []), (self.empty_choices_bool.choices, []), (self.empty_choices_text.choices, []), (self.with_choices.choices, [(1, "A")]), (self.with_choices_dict.choices, [(1, "A")]), (self.with_choices_nested_dict.choices, [("Thing", [(1, "A")])]), (self.choices_from_iterator.choices, [(0, "0"), (1, "1")]), (self.choices_from_callable.choices.func(), [(0, "0"), (1, "1")]), (self.choices_from_callable.choices, [(0, "0"), (1, "1")]), ]: with self.subTest(choices=choices): self.assertEqual(choices[:2], expected_slice) def test_choices_negative_index(self): for choices, expected_choice in [ (self.with_choices.choices, (1, "A")), (self.with_choices_dict.choices, (1, "A")), (self.with_choices_nested_dict.choices, ("Thing", [(1, "A")])), (self.choices_from_iterator.choices, (2, "2")), (self.choices_from_callable.choices.func(), (2, "2")), (self.choices_from_callable.choices, (2, "2")), ]: with self.subTest(choices=choices): self.assertEqual(choices[-1], expected_choice) def test_flatchoices(self): self.assertEqual(self.no_choices.flatchoices, []) self.assertEqual(self.empty_choices.flatchoices, []) self.assertEqual(self.empty_choices_bool.flatchoices, []) self.assertEqual(self.empty_choices_text.flatchoices, []) self.assertEqual(self.with_choices.flatchoices, [(1, "A")]) self.assertEqual(self.with_choices_dict.flatchoices, [(1, "A")]) self.assertEqual(self.with_choices_nested_dict.flatchoices, [(1, "A")]) self.assertEqual( self.choices_from_iterator.flatchoices, [(0, "0"), (1, "1"), (2, "2")] ) self.assertEqual( self.choices_from_callable.flatchoices, [(0, "0"), (1, "1"), (2, "2")] ) def test_check(self): self.assertEqual(Choiceful.check(), []) def test_invalid_choice(self): model_instance = None # Actual model instance not needed. self.no_choices.validate(0, model_instance) msg = "['Value 99 is not a valid choice.']" with self.assertRaisesMessage(ValidationError, msg): self.empty_choices.validate(99, model_instance) with self.assertRaisesMessage(ValidationError, msg): self.with_choices.validate(99, model_instance) def test_formfield(self): no_choices_formfield = self.no_choices.formfield() self.assertIsInstance(no_choices_formfield, forms.IntegerField) fields = ( self.empty_choices, self.empty_choices_bool, self.empty_choices_text, self.with_choices, self.with_choices_dict, self.with_choices_nested_dict, self.choices_from_enum, self.choices_from_iterator, self.choices_from_callable, ) for field in fields: with self.subTest(field=field): self.assertIsInstance(field.formfield(), forms.ChoiceField) def test_choices_from_enum(self): # Choices class was transparently resolved when given as argument. self.assertEqual(self.choices_from_enum.choices, Choiceful.Suit.choices) self.assertEqual(self.choices_from_enum.flatchoices, Choiceful.Suit.choices) class GetFieldDisplayTests(SimpleTestCase): def test_choices_and_field_display(self): """ get_choices() interacts with get_FIELD_display() to return the expected values. """ self.assertEqual(Whiz(c=1).get_c_display(), "First") # A nested value self.assertEqual(Whiz(c=0).get_c_display(), "Other") # A top level value self.assertEqual(Whiz(c=9).get_c_display(), 9) # Invalid value self.assertIsNone(Whiz(c=None).get_c_display()) # Blank value self.assertEqual(Whiz(c="").get_c_display(), "") # Empty value self.assertEqual(WhizDelayed(c=0).get_c_display(), "Other") # Delayed choices def test_get_FIELD_display_translated(self): """A translated display value is coerced to str.""" val = Whiz(c=5).get_c_display() self.assertIsInstance(val, str) self.assertEqual(val, "translated") def test_overriding_FIELD_display(self): class FooBar(models.Model): foo_bar = models.IntegerField(choices=[(1, "foo"), (2, "bar")]) def get_foo_bar_display(self): return "something" f = FooBar(foo_bar=1) self.assertEqual(f.get_foo_bar_display(), "something") def test_overriding_inherited_FIELD_display(self): class Base(models.Model): foo = models.CharField(max_length=254, choices=[("A", "Base A")]) class Meta: abstract = True class Child(Base): foo = models.CharField( max_length=254, choices=[("A", "Child A"), ("B", "Child B")] ) self.assertEqual(Child(foo="A").get_foo_display(), "Child A") self.assertEqual(Child(foo="B").get_foo_display(), "Child B") def test_iterator_choices(self): """ get_choices() works with Iterators. """ self.assertEqual(WhizIter(c=1).c, 1) # A nested value self.assertEqual(WhizIter(c=9).c, 9) # Invalid value self.assertIsNone(WhizIter(c=None).c) # Blank value self.assertEqual(WhizIter(c="").c, "") # Empty value def test_empty_iterator_choices(self): """ get_choices() works with empty iterators. """ self.assertEqual(WhizIterEmpty(c="a").c, "a") # A nested value self.assertEqual(WhizIterEmpty(c="b").c, "b") # Invalid value self.assertIsNone(WhizIterEmpty(c=None).c) # Blank value self.assertEqual(WhizIterEmpty(c="").c, "") # Empty value class GetChoicesTests(SimpleTestCase): def test_empty_choices(self): choices = [] f = models.CharField(choices=choices) self.assertEqual(f.get_choices(include_blank=False), choices) def test_blank_in_choices(self): choices = [("", "<><>"), ("a", "A")] f = models.CharField(choices=choices) self.assertEqual(f.get_choices(include_blank=True), choices) def test_blank_in_grouped_choices(self): choices = [ ("f", "Foo"), ("b", "Bar"), ( "Group", [ ("", "No Preference"), ("fg", "Foo"), ("bg", "Bar"), ], ), ] f = models.CharField(choices=choices) self.assertEqual(f.get_choices(include_blank=True), choices) def test_lazy_strings_not_evaluated(self): lazy_func = lazy(lambda x: 0 / 0, int) # raises ZeroDivisionError if evaluated. f = models.CharField(choices=[(lazy_func("group"), [("a", "A"), ("b", "B")])]) self.assertEqual(f.get_choices(include_blank=True)[0], ("", "---------")) class GetChoicesOrderingTests(TestCase): @classmethod def setUpTestData(cls): cls.foo1 = Foo.objects.create(a="a", d="12.35") cls.foo2 = Foo.objects.create(a="b", d="12.34") cls.bar1 = Bar.objects.create(a=cls.foo1, b="b") cls.bar2 = Bar.objects.create(a=cls.foo2, b="a") cls.field = Bar._meta.get_field("a") def assertChoicesEqual(self, choices, objs): self.assertEqual(choices, [(obj.pk, str(obj)) for obj in objs]) def test_get_choices(self): self.assertChoicesEqual( self.field.get_choices(include_blank=False, ordering=("a",)), [self.foo1, self.foo2], ) self.assertChoicesEqual( self.field.get_choices(include_blank=False, ordering=("-a",)), [self.foo2, self.foo1], ) def test_get_choices_default_ordering(self): self.addCleanup(setattr, Foo._meta, "ordering", Foo._meta.ordering) Foo._meta.ordering = ("d",) self.assertChoicesEqual( self.field.get_choices(include_blank=False), [self.foo2, self.foo1] ) def test_get_choices_reverse_related_field(self): self.assertChoicesEqual( self.field.remote_field.get_choices(include_blank=False, ordering=("a",)), [self.bar1, self.bar2], ) self.assertChoicesEqual( self.field.remote_field.get_choices(include_blank=False, ordering=("-a",)), [self.bar2, self.bar1], ) def test_get_choices_reverse_related_field_default_ordering(self): self.addCleanup(setattr, Bar._meta, "ordering", Bar._meta.ordering) Bar._meta.ordering = ("b",) self.assertChoicesEqual( self.field.remote_field.get_choices(include_blank=False), [self.bar2, self.bar1], ) class GetChoicesLimitChoicesToTests(TestCase): @classmethod def setUpTestData(cls): cls.foo1 = Foo.objects.create(a="a", d="12.34") cls.foo2 = Foo.objects.create(a="b", d="12.34") cls.bar1 = Bar.objects.create(a=cls.foo1, b="b") cls.bar2 = Bar.objects.create(a=cls.foo2, b="a") cls.field = Bar._meta.get_field("a") def assertChoicesEqual(self, choices, objs): self.assertCountEqual(choices, [(obj.pk, str(obj)) for obj in objs]) def test_get_choices(self): self.assertChoicesEqual( self.field.get_choices(include_blank=False, limit_choices_to={"a": "a"}), [self.foo1], ) self.assertChoicesEqual( self.field.get_choices(include_blank=False, limit_choices_to={}), [self.foo1, self.foo2], ) def test_get_choices_reverse_related_field(self): field = self.field.remote_field self.assertChoicesEqual( field.get_choices(include_blank=False, limit_choices_to={"b": "b"}), [self.bar1], ) self.assertChoicesEqual( field.get_choices(include_blank=False, limit_choices_to={}), [self.bar1, self.bar2], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_fields/test_floatfield.py
tests/model_fields/test_floatfield.py
from django.db import transaction from django.test import TestCase from .models import FloatModel class TestFloatField(TestCase): def test_float_validates_object(self): instance = FloatModel(size=2.5) # Try setting float field to unsaved object instance.size = instance with transaction.atomic(): with self.assertRaises(TypeError): instance.save() # Set value to valid and save instance.size = 2.5 instance.save() self.assertTrue(instance.id) # Set field to object on saved instance instance.size = instance msg = ( "Tried to update field model_fields.FloatModel.size with a model " "instance, %r. Use a value compatible with FloatField." ) % instance with transaction.atomic(): with self.assertRaisesMessage(TypeError, msg): instance.save() # Try setting field to object on retrieved object obj = FloatModel.objects.get(pk=instance.id) obj.size = obj with self.assertRaisesMessage(TypeError, msg): obj.save() def test_invalid_value(self): tests = [ (TypeError, ()), (TypeError, []), (TypeError, {}), (TypeError, set()), (TypeError, object()), (TypeError, complex()), (ValueError, "non-numeric string"), (ValueError, b"non-numeric byte-string"), ] for exception, value in tests: with self.subTest(value): msg = "Field 'size' expected a number but got %r." % (value,) with self.assertRaisesMessage(exception, msg): FloatModel.objects.create(size=value)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_fields/test_field_flags.py
tests/model_fields/test_field_flags.py
from django import test from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.db import models from .models import AllFieldsModel NON_CONCRETE_FIELDS = ( models.ForeignObject, models.ManyToManyField, GenericForeignKey, GenericRelation, ) NON_EDITABLE_FIELDS = ( models.BinaryField, GenericForeignKey, GenericRelation, ) RELATION_FIELDS = ( models.ForeignKey, models.ForeignObject, models.ManyToManyField, models.OneToOneField, GenericForeignKey, GenericRelation, ) MANY_TO_MANY_CLASSES = { models.ManyToManyField, } MANY_TO_ONE_CLASSES = { models.ForeignObject, models.ForeignKey, GenericForeignKey, } ONE_TO_MANY_CLASSES = { models.ForeignObjectRel, models.ManyToOneRel, GenericRelation, } ONE_TO_ONE_CLASSES = { models.OneToOneField, } FLAG_PROPERTIES = ( "concrete", "editable", "is_relation", "model", "hidden", "one_to_many", "many_to_one", "many_to_many", "one_to_one", "related_model", ) FLAG_PROPERTIES_FOR_RELATIONS = ( "one_to_many", "many_to_one", "many_to_many", "one_to_one", ) class FieldFlagsTests(test.SimpleTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.fields = [ *AllFieldsModel._meta.fields, *AllFieldsModel._meta.private_fields, ] cls.all_fields = [ *cls.fields, *AllFieldsModel._meta.many_to_many, *AllFieldsModel._meta.private_fields, ] cls.fields_and_reverse_objects = [ *cls.all_fields, *AllFieldsModel._meta.related_objects, ] def test_each_field_should_have_a_concrete_attribute(self): self.assertTrue(all(f.concrete.__class__ == bool for f in self.fields)) def test_each_field_should_have_an_editable_attribute(self): self.assertTrue(all(f.editable.__class__ == bool for f in self.all_fields)) def test_each_field_should_have_a_has_rel_attribute(self): self.assertTrue(all(f.is_relation.__class__ == bool for f in self.all_fields)) def test_each_object_should_have_auto_created(self): self.assertTrue( all( f.auto_created.__class__ == bool for f in self.fields_and_reverse_objects ) ) def test_non_concrete_fields(self): for field in self.fields: if type(field) in NON_CONCRETE_FIELDS: self.assertFalse(field.concrete) else: self.assertTrue(field.concrete) def test_non_editable_fields(self): for field in self.all_fields: if type(field) in NON_EDITABLE_FIELDS: self.assertFalse(field.editable) else: self.assertTrue(field.editable) def test_related_fields(self): for field in self.all_fields: if type(field) in RELATION_FIELDS: self.assertTrue(field.is_relation) else: self.assertFalse(field.is_relation) def test_field_names_should_always_be_available(self): for field in self.fields_and_reverse_objects: self.assertTrue(field.name) def test_all_field_types_should_have_flags(self): for field in self.fields_and_reverse_objects: for flag in FLAG_PROPERTIES: self.assertTrue( hasattr(field, flag), "Field %s does not have flag %s" % (field, flag), ) if field.is_relation: true_cardinality_flags = sum( getattr(field, flag) is True for flag in FLAG_PROPERTIES_FOR_RELATIONS ) # If the field has a relation, there should be only one of the # 4 cardinality flags available. self.assertEqual(1, true_cardinality_flags) def test_cardinality_m2m(self): m2m_type_fields = [ f for f in self.all_fields if f.is_relation and f.many_to_many ] # Test classes are what we expect self.assertEqual(MANY_TO_MANY_CLASSES, {f.__class__ for f in m2m_type_fields}) # Ensure all m2m reverses are m2m for field in m2m_type_fields: reverse_field = field.remote_field self.assertTrue(reverse_field.is_relation) self.assertTrue(reverse_field.many_to_many) self.assertTrue(reverse_field.related_model) def test_cardinality_o2m(self): o2m_type_fields = [ f for f in self.fields_and_reverse_objects if f.is_relation and f.one_to_many ] # Test classes are what we expect self.assertEqual(ONE_TO_MANY_CLASSES, {f.__class__ for f in o2m_type_fields}) # Ensure all o2m reverses are m2o for field in o2m_type_fields: if field.concrete: reverse_field = field.remote_field self.assertTrue(reverse_field.is_relation and reverse_field.many_to_one) def test_cardinality_m2o(self): m2o_type_fields = [ f for f in self.fields_and_reverse_objects if f.is_relation and f.many_to_one ] # Test classes are what we expect self.assertEqual(MANY_TO_ONE_CLASSES, {f.__class__ for f in m2o_type_fields}) # Ensure all m2o reverses are o2m for obj in m2o_type_fields: if hasattr(obj, "field"): reverse_field = obj.field self.assertTrue(reverse_field.is_relation and reverse_field.one_to_many) def test_cardinality_o2o(self): o2o_type_fields = [f for f in self.all_fields if f.is_relation and f.one_to_one] # Test classes are what we expect self.assertEqual(ONE_TO_ONE_CLASSES, {f.__class__ for f in o2o_type_fields}) # Ensure all o2o reverses are o2o for obj in o2o_type_fields: if hasattr(obj, "field"): reverse_field = obj.field self.assertTrue(reverse_field.is_relation and reverse_field.one_to_one) def test_hidden_flag(self): incl_hidden = set(AllFieldsModel._meta.get_fields(include_hidden=True)) no_hidden = set(AllFieldsModel._meta.get_fields()) fields_that_should_be_hidden = incl_hidden - no_hidden for f in incl_hidden: self.assertEqual(f in fields_that_should_be_hidden, f.hidden) def test_model_and_reverse_model_should_equal_on_relations(self): for field in AllFieldsModel._meta.get_fields(): is_concrete_forward_field = field.concrete and field.related_model if is_concrete_forward_field or field.many_to_many: reverse_field = field.remote_field self.assertEqual(field.model, reverse_field.related_model) self.assertEqual(field.related_model, reverse_field.model) def test_null(self): # null isn't well defined for a ManyToManyField, but changing it to # True causes backwards compatibility problems (#25320). self.assertFalse(AllFieldsModel._meta.get_field("m2m").null) self.assertTrue(AllFieldsModel._meta.get_field("reverse2").null)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_fields/test_imagefield.py
tests/model_fields/test_imagefield.py
import os import shutil from unittest import skipIf from django.core.exceptions import ImproperlyConfigured from django.core.files import File from django.core.files.images import ImageFile from django.db.models import signals from django.test import TestCase from django.test.testcases import SerializeMixin try: from .models import Image except ImproperlyConfigured: Image = None if Image: from .models import ( Person, PersonDimensionsFirst, PersonNoReadImage, PersonTwoImages, PersonWithHeight, PersonWithHeightAndWidth, TestImageFieldFile, temp_storage_dir, ) else: # Pillow not available, create dummy classes (tests will be skipped anyway) class Person: pass PersonWithHeight = PersonWithHeightAndWidth = PersonDimensionsFirst = Person PersonTwoImages = PersonNoReadImage = Person class ImageFieldTestMixin(SerializeMixin): """ Mixin class to provide common functionality to ImageField test classes. """ lockfile = __file__ # Person model to use for tests. PersonModel = PersonWithHeightAndWidth # File class to use for file instances. File = ImageFile def setUp(self): """ Creates a pristine temp directory (or deletes and recreates if it already exists) that the model uses as its storage directory. Sets up two ImageFile instances for use in tests. """ if os.path.exists(temp_storage_dir): shutil.rmtree(temp_storage_dir) os.mkdir(temp_storage_dir) self.addCleanup(shutil.rmtree, temp_storage_dir) file_path1 = os.path.join(os.path.dirname(__file__), "4x8.png") self.file1 = self.File(open(file_path1, "rb"), name="4x8.png") self.addCleanup(self.file1.close) file_path2 = os.path.join(os.path.dirname(__file__), "8x4.png") self.file2 = self.File(open(file_path2, "rb"), name="8x4.png") self.addCleanup(self.file2.close) def check_dimensions(self, instance, width, height, field_name="mugshot"): """ Asserts that the given width and height values match both the field's height and width attributes and the height and width fields (if defined) the image field is caching to. Note, this method will check for dimension fields named by adding "_width" or "_height" to the name of the ImageField. So, the models used in these tests must have their fields named accordingly. By default, we check the field named "mugshot", but this can be specified by passing the field_name parameter. """ field = getattr(instance, field_name) # Check height/width attributes of field. if width is None and height is None: with self.assertRaises(ValueError): getattr(field, "width") with self.assertRaises(ValueError): getattr(field, "height") else: self.assertEqual(field.width, width) self.assertEqual(field.height, height) # Check height/width fields of model, if defined. width_field_name = field_name + "_width" if hasattr(instance, width_field_name): self.assertEqual(getattr(instance, width_field_name), width) height_field_name = field_name + "_height" if hasattr(instance, height_field_name): self.assertEqual(getattr(instance, height_field_name), height) @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldTests(ImageFieldTestMixin, TestCase): """ Tests for ImageField that don't need to be run with each of the different test model classes. """ def test_equal_notequal_hash(self): """ Bug #9786: Ensure '==' and '!=' work correctly. Bug #9508: make sure hash() works as expected (equal items must hash to the same value). """ # Create two Persons with different mugshots. p1 = self.PersonModel(name="Joe") p1.mugshot.save("mug", self.file1) p2 = self.PersonModel(name="Bob") p2.mugshot.save("mug", self.file2) self.assertIs(p1.mugshot == p2.mugshot, False) self.assertIs(p1.mugshot != p2.mugshot, True) # Test again with an instance fetched from the db. p1_db = self.PersonModel.objects.get(name="Joe") self.assertIs(p1_db.mugshot == p2.mugshot, False) self.assertIs(p1_db.mugshot != p2.mugshot, True) # Instance from db should match the local instance. self.assertIs(p1_db.mugshot == p1.mugshot, True) self.assertEqual(hash(p1_db.mugshot), hash(p1.mugshot)) self.assertIs(p1_db.mugshot != p1.mugshot, False) def test_instantiate_missing(self): """ If the underlying file is unavailable, still create instantiate the object without error. """ p = self.PersonModel(name="Joan") p.mugshot.save("shot", self.file1) p = self.PersonModel.objects.get(name="Joan") path = p.mugshot.path shutil.move(path, path + ".moved") self.PersonModel.objects.get(name="Joan") def test_delete_when_missing(self): """ Bug #8175: correctly delete an object where the file no longer exists on the file system. """ p = self.PersonModel(name="Fred") p.mugshot.save("shot", self.file1) os.remove(p.mugshot.path) p.delete() def test_size_method(self): """ Bug #8534: FileField.size should not leave the file open. """ p = self.PersonModel(name="Joan") p.mugshot.save("shot", self.file1) # Get a "clean" model instance p = self.PersonModel.objects.get(name="Joan") # It won't have an opened file. self.assertIs(p.mugshot.closed, True) # After asking for the size, the file should still be closed. p.mugshot.size self.assertIs(p.mugshot.closed, True) def test_pickle(self): """ ImageField can be pickled, unpickled, and that the image of the unpickled version is the same as the original. """ import pickle p = Person(name="Joe") p.mugshot.save("mug", self.file1) dump = pickle.dumps(p) loaded_p = pickle.loads(dump) self.assertEqual(p.mugshot, loaded_p.mugshot) self.assertEqual(p.mugshot.url, loaded_p.mugshot.url) self.assertEqual(p.mugshot.storage, loaded_p.mugshot.storage) self.assertEqual(p.mugshot.instance, loaded_p.mugshot.instance) self.assertEqual(p.mugshot.field, loaded_p.mugshot.field) mugshot_dump = pickle.dumps(p.mugshot) loaded_mugshot = pickle.loads(mugshot_dump) self.assertEqual(p.mugshot, loaded_mugshot) self.assertEqual(p.mugshot.url, loaded_mugshot.url) self.assertEqual(p.mugshot.storage, loaded_mugshot.storage) self.assertEqual(p.mugshot.instance, loaded_mugshot.instance) self.assertEqual(p.mugshot.field, loaded_mugshot.field) def test_defer(self): self.PersonModel.objects.create(name="Joe", mugshot=self.file1) with self.assertNumQueries(1): qs = list(self.PersonModel.objects.defer("mugshot")) with self.assertNumQueries(0): self.assertEqual(qs[0].name, "Joe") @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldTwoDimensionsTests(ImageFieldTestMixin, TestCase): """ Tests behavior of an ImageField and its dimensions fields. """ def test_constructor(self): """ Tests assigning an image field through the model's constructor. """ p = self.PersonModel(name="Joe", mugshot=self.file1) self.check_dimensions(p, 4, 8) p.save() self.check_dimensions(p, 4, 8) def test_image_after_constructor(self): """ Tests behavior when image is not passed in constructor. """ p = self.PersonModel(name="Joe") # TestImageField value will default to being an instance of its # attr_class, a TestImageFieldFile, with name == None, which will # cause it to evaluate as False. self.assertIsInstance(p.mugshot, TestImageFieldFile) self.assertFalse(p.mugshot) # Test setting a fresh created model instance. p = self.PersonModel(name="Joe") p.mugshot = self.file1 self.check_dimensions(p, 4, 8) def test_create(self): """ Tests assigning an image in Manager.create(). """ p = self.PersonModel.objects.create(name="Joe", mugshot=self.file1) self.check_dimensions(p, 4, 8) def test_default_value(self): """ The default value for an ImageField is an instance of the field's attr_class (TestImageFieldFile in this case) with no name (name set to None). """ p = self.PersonModel() self.assertIsInstance(p.mugshot, TestImageFieldFile) self.assertFalse(p.mugshot) def test_assignment_to_None(self): """ Assigning ImageField to None clears dimensions. """ p = self.PersonModel(name="Joe", mugshot=self.file1) self.check_dimensions(p, 4, 8) # If image assigned to None, dimension fields should be cleared. p.mugshot = None self.check_dimensions(p, None, None) p.mugshot = self.file2 self.check_dimensions(p, 8, 4) def test_field_save_and_delete_methods(self): """ Tests assignment using the field's save method and deletion using the field's delete method. """ p = self.PersonModel(name="Joe") p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8) # A new file should update dimensions. p.mugshot.save("mug", self.file2) self.check_dimensions(p, 8, 4) # Field and dimensions should be cleared after a delete. p.mugshot.delete(save=False) self.assertIsNone(p.mugshot.name) self.check_dimensions(p, None, None) def test_dimensions(self): """ Dimensions are updated correctly in various situations. """ p = self.PersonModel(name="Joe") # Dimensions should get set if file is saved. p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8) # Test dimensions after fetching from database. p = self.PersonModel.objects.get(name="Joe") # Bug 11084: Dimensions should not get recalculated if file is # coming from the database. We test this by checking if the file # was opened. self.assertIs(p.mugshot.was_opened, False) self.check_dimensions(p, 4, 8) # After checking dimensions on the image field, the file will have # opened. self.assertIs(p.mugshot.was_opened, True) # Dimensions should now be cached, and if we reset was_opened and # check dimensions again, the file should not have opened. p.mugshot.was_opened = False self.check_dimensions(p, 4, 8) self.assertIs(p.mugshot.was_opened, False) # If we assign a new image to the instance, the dimensions should # update. p.mugshot = self.file2 self.check_dimensions(p, 8, 4) # Dimensions were recalculated, and hence file should have opened. self.assertIs(p.mugshot.was_opened, True) @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldNoDimensionsTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField with no dimension fields. """ PersonModel = Person def test_post_init_not_connected(self): person_model_id = id(self.PersonModel) self.assertNotIn( person_model_id, [sender_id for (_, sender_id), *_ in signals.post_init.receivers], ) def test_save_does_not_close_file(self): p = self.PersonModel(name="Joe") p.mugshot.save("mug", self.file1) with p.mugshot as f: # Underlying file object wasn’t closed. self.assertEqual(f.tell(), 0) @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldOneDimensionTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField with one dimensions field. """ PersonModel = PersonWithHeight @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldDimensionsFirstTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField where the dimensions fields are defined before the ImageField. """ PersonModel = PersonDimensionsFirst @skipIf(Image is None, "Pillow is required to test ImageField") class ImageFieldUsingFileTests(ImageFieldTwoDimensionsTests): """ Tests behavior of an ImageField when assigning it a File instance rather than an ImageFile instance. """ PersonModel = PersonDimensionsFirst File = File @skipIf(Image is None, "Pillow is required to test ImageField") class TwoImageFieldTests(ImageFieldTestMixin, TestCase): """ Tests a model with two ImageFields. """ PersonModel = PersonTwoImages def test_constructor(self): p = self.PersonModel(mugshot=self.file1, headshot=self.file2) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") p.save() self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") def test_create(self): p = self.PersonModel.objects.create(mugshot=self.file1, headshot=self.file2) self.check_dimensions(p, 4, 8) self.check_dimensions(p, 8, 4, "headshot") def test_assignment(self): p = self.PersonModel() self.check_dimensions(p, None, None, "mugshot") self.check_dimensions(p, None, None, "headshot") p.mugshot = self.file1 self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, None, None, "headshot") p.headshot = self.file2 self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") # Clear the ImageFields one at a time. p.mugshot = None self.check_dimensions(p, None, None, "mugshot") self.check_dimensions(p, 8, 4, "headshot") p.headshot = None self.check_dimensions(p, None, None, "mugshot") self.check_dimensions(p, None, None, "headshot") def test_field_save_and_delete_methods(self): p = self.PersonModel(name="Joe") p.mugshot.save("mug", self.file1) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, None, None, "headshot") p.headshot.save("head", self.file2) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") # We can use save=True when deleting the image field with null=True # dimension fields and the other field has an image. p.headshot.delete(save=True) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, None, None, "headshot") p.mugshot.delete(save=False) self.check_dimensions(p, None, None, "mugshot") self.check_dimensions(p, None, None, "headshot") def test_dimensions(self): """ Dimensions are updated correctly in various situations. """ p = self.PersonModel(name="Joe") # Dimensions should get set for the saved file. p.mugshot.save("mug", self.file1) p.headshot.save("head", self.file2) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") # Test dimensions after fetching from database. p = self.PersonModel.objects.get(name="Joe") # Bug 11084: Dimensions should not get recalculated if file is # coming from the database. We test this by checking if the file # was opened. self.assertIs(p.mugshot.was_opened, False) self.assertIs(p.headshot.was_opened, False) self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") # After checking dimensions on the image fields, the files will # have been opened. self.assertIs(p.mugshot.was_opened, True) self.assertIs(p.headshot.was_opened, True) # Dimensions should now be cached, and if we reset was_opened and # check dimensions again, the file should not have opened. p.mugshot.was_opened = False p.headshot.was_opened = False self.check_dimensions(p, 4, 8, "mugshot") self.check_dimensions(p, 8, 4, "headshot") self.assertIs(p.mugshot.was_opened, False) self.assertIs(p.headshot.was_opened, False) # If we assign a new image to the instance, the dimensions should # update. p.mugshot = self.file2 p.headshot = self.file1 self.check_dimensions(p, 8, 4, "mugshot") self.check_dimensions(p, 4, 8, "headshot") # Dimensions were recalculated, and hence file should have opened. self.assertIs(p.mugshot.was_opened, True) self.assertIs(p.headshot.was_opened, True) @skipIf(Image is None, "Pillow is required to test ImageField") class NoReadTests(ImageFieldTestMixin, TestCase): def test_width_height_correct_name_mangling_correct(self): instance1 = PersonNoReadImage() instance1.mugshot.save("mug", self.file1) self.assertEqual(instance1.mugshot_width, 4) self.assertEqual(instance1.mugshot_height, 8) instance1.save() self.assertEqual(instance1.mugshot_width, 4) self.assertEqual(instance1.mugshot_height, 8) instance2 = PersonNoReadImage() instance2.mugshot.save("mug", self.file1) instance2.save() self.assertNotEqual(instance1.mugshot.name, instance2.mugshot.name) self.assertEqual(instance1.mugshot_width, instance2.mugshot_width) self.assertEqual(instance1.mugshot_height, instance2.mugshot_height)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_fields/test_filefield.py
tests/model_fields/test_filefield.py
import os import pickle import sys import tempfile import unittest from pathlib import Path from django.core.exceptions import FieldError, SuspiciousFileOperation from django.core.files import File, temp from django.core.files.base import ContentFile from django.core.files.uploadedfile import TemporaryUploadedFile from django.db import IntegrityError, models from django.test import TestCase, override_settings from django.test.utils import isolate_apps from .models import Document class FileFieldTests(TestCase): def test_clearable(self): """ FileField.save_form_data() will clear its instance attribute value if passed False. """ d = Document(myfile="something.txt") self.assertEqual(d.myfile, "something.txt") field = d._meta.get_field("myfile") field.save_form_data(d, False) self.assertEqual(d.myfile, "") def test_unchanged(self): """ FileField.save_form_data() considers None to mean "no change" rather than "clear". """ d = Document(myfile="something.txt") self.assertEqual(d.myfile, "something.txt") field = d._meta.get_field("myfile") field.save_form_data(d, None) self.assertEqual(d.myfile, "something.txt") def test_changed(self): """ FileField.save_form_data(), if passed a truthy value, updates its instance attribute. """ d = Document(myfile="something.txt") self.assertEqual(d.myfile, "something.txt") field = d._meta.get_field("myfile") field.save_form_data(d, "else.txt") self.assertEqual(d.myfile, "else.txt") def test_delete_when_file_unset(self): """ Calling delete on an unset FileField should not call the file deletion process, but fail silently (#20660). """ d = Document() d.myfile.delete() def test_refresh_from_db(self): d = Document.objects.create(myfile="something.txt") d.refresh_from_db() self.assertIs(d.myfile.instance, d) @unittest.skipIf(sys.platform == "win32", "Crashes with OSError on Windows.") def test_save_without_name(self): with tempfile.NamedTemporaryFile(suffix=".txt") as tmp: document = Document.objects.create(myfile="something.txt") document.myfile = File(tmp) msg = f"Detected path traversal attempt in '{tmp.name}'" with self.assertRaisesMessage(SuspiciousFileOperation, msg): document.save() def test_save_content_file_without_name(self): d = Document() d.myfile = ContentFile(b"") msg = "File for myfile must have the name attribute specified to be saved." with self.assertRaisesMessage(FieldError, msg) as cm: d.save() self.assertEqual( cm.exception.__notes__, ["Pass a 'name' argument to ContentFile."] ) def test_delete_content_file(self): file = ContentFile(b"", name="foo") d = Document.objects.create(myfile=file) d.myfile.delete() self.assertIsNone(d.myfile.name) msg = "The 'myfile' attribute has no file associated with it." with self.assertRaisesMessage(ValueError, msg): getattr(d.myfile, "file") def test_defer(self): Document.objects.create(myfile="something.txt") self.assertEqual(Document.objects.defer("myfile")[0].myfile, "something.txt") def test_unique_when_same_filename(self): """ A FileField with unique=True shouldn't allow two instances with the same name to be saved. """ Document.objects.create(myfile="something.txt") with self.assertRaises(IntegrityError): Document.objects.create(myfile="something.txt") @unittest.skipIf( sys.platform == "win32", "Windows doesn't support moving open files." ) # The file's source and destination must be on the same filesystem. @override_settings(MEDIA_ROOT=temp.gettempdir()) def test_move_temporary_file(self): """ The temporary uploaded file is moved rather than copied to the destination. """ with TemporaryUploadedFile( "something.txt", "text/plain", 0, "UTF-8" ) as tmp_file: tmp_file_path = tmp_file.temporary_file_path() Document.objects.create(myfile=tmp_file) self.assertFalse( os.path.exists(tmp_file_path), "Temporary file still exists" ) def test_open_returns_self(self): """ FieldField.open() returns self so it can be used as a context manager. """ d = Document.objects.create(myfile="something.txt") # Replace the FileField's file with an in-memory ContentFile, so that # open() doesn't write to disk. d.myfile.file = ContentFile(b"", name="bla") self.assertEqual(d.myfile, d.myfile.open()) def test_media_root_pathlib(self): with tempfile.TemporaryDirectory() as tmp_dir: with override_settings(MEDIA_ROOT=Path(tmp_dir)): with TemporaryUploadedFile( "foo.txt", "text/plain", 1, "utf-8" ) as tmp_file: document = Document.objects.create(myfile=tmp_file) self.assertIs( document.myfile.storage.exists( os.path.join("unused", "foo.txt") ), True, ) def test_pickle(self): with tempfile.TemporaryDirectory() as tmp_dir: with override_settings(MEDIA_ROOT=Path(tmp_dir)): with open(__file__, "rb") as fp: file1 = File(fp, name="test_file.py") document = Document(myfile="test_file.py") document.myfile.save("test_file.py", file1) try: dump = pickle.dumps(document) loaded_document = pickle.loads(dump) self.assertEqual(document.myfile, loaded_document.myfile) self.assertEqual( document.myfile.url, loaded_document.myfile.url, ) self.assertEqual( document.myfile.storage, loaded_document.myfile.storage, ) self.assertEqual( document.myfile.instance, loaded_document.myfile.instance, ) self.assertEqual( document.myfile.field, loaded_document.myfile.field, ) myfile_dump = pickle.dumps(document.myfile) loaded_myfile = pickle.loads(myfile_dump) self.assertEqual(document.myfile, loaded_myfile) self.assertEqual(document.myfile.url, loaded_myfile.url) self.assertEqual( document.myfile.storage, loaded_myfile.storage, ) self.assertEqual( document.myfile.instance, loaded_myfile.instance, ) self.assertEqual(document.myfile.field, loaded_myfile.field) finally: document.myfile.delete() @isolate_apps("model_fields") def test_abstract_filefield_model(self): """ FileField.model returns the concrete model for fields defined in an abstract model. """ class AbstractMyDocument(models.Model): myfile = models.FileField(upload_to="unused") class Meta: abstract = True class MyDocument(AbstractMyDocument): pass document = MyDocument(myfile="test_file.py") self.assertEqual(document.myfile.field.model, MyDocument)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/logging_tests/views.py
tests/logging_tests/views.py
from django.core.exceptions import DisallowedHost, PermissionDenied, SuspiciousOperation from django.http import ( Http404, HttpResponse, HttpResponseRedirect, HttpResponseServerError, ) from django.http.multipartparser import MultiPartParserError def innocent(request): return HttpResponse("innocent") def redirect(request): return HttpResponseRedirect("/") def suspicious(request): raise SuspiciousOperation("dubious") def suspicious_spec(request): raise DisallowedHost("dubious") class UncaughtException(Exception): pass def uncaught_exception(request): raise UncaughtException("Uncaught exception") def internal_server_error(request): status = request.GET.get("status", 500) return HttpResponseServerError("Server Error", status=int(status)) def permission_denied(request): raise PermissionDenied() def multi_part_parser_error(request): raise MultiPartParserError("parsing error") def does_not_exist_raised(request): raise Http404("Not Found")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/logging_tests/logconfig.py
tests/logging_tests/logconfig.py
import logging from django.conf import settings from django.core.mail.backends.base import BaseEmailBackend from django.views.debug import ExceptionReporter class MyHandler(logging.Handler): def __init__(self): logging.Handler.__init__(self) self.config = settings.LOGGING class MyEmailBackend(BaseEmailBackend): def send_messages(self, email_messages): pass class CustomExceptionReporter(ExceptionReporter): def get_traceback_text(self): return "custom traceback text"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/logging_tests/urls_i18n.py
tests/logging_tests/urls_i18n.py
from django.conf.urls.i18n import i18n_patterns from django.http import HttpResponse from django.urls import path urlpatterns = i18n_patterns( path("exists/", lambda r: HttpResponse()), )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/logging_tests/__init__.py
tests/logging_tests/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/logging_tests/tests.py
tests/logging_tests/tests.py
import logging from contextlib import contextmanager from io import StringIO from unittest import TestCase, mock from admin_scripts.tests import AdminScriptTestCase from django.conf import settings from django.core import mail from django.core.exceptions import DisallowedHost, PermissionDenied, SuspiciousOperation from django.core.files.temp import NamedTemporaryFile from django.core.management import color from django.http import HttpResponse from django.http.multipartparser import MultiPartParserError from django.test import RequestFactory, SimpleTestCase, override_settings from django.test.utils import LoggingCaptureMixin from django.utils.log import ( DEFAULT_LOGGING, AdminEmailHandler, CallbackFilter, RequireDebugFalse, RequireDebugTrue, ServerFormatter, log_response, ) from django.views.debug import ExceptionReporter from . import views from .logconfig import MyEmailBackend class LoggingFiltersTest(SimpleTestCase): def test_require_debug_false_filter(self): """ Test the RequireDebugFalse filter class. """ filter_ = RequireDebugFalse() with self.settings(DEBUG=True): self.assertIs(filter_.filter("record is not used"), False) with self.settings(DEBUG=False): self.assertIs(filter_.filter("record is not used"), True) def test_require_debug_true_filter(self): """ Test the RequireDebugTrue filter class. """ filter_ = RequireDebugTrue() with self.settings(DEBUG=True): self.assertIs(filter_.filter("record is not used"), True) with self.settings(DEBUG=False): self.assertIs(filter_.filter("record is not used"), False) class SetupDefaultLoggingMixin: @classmethod def setUpClass(cls): super().setUpClass() logging.config.dictConfig(DEFAULT_LOGGING) cls.addClassCleanup(logging.config.dictConfig, settings.LOGGING) class DefaultLoggingTests( SetupDefaultLoggingMixin, LoggingCaptureMixin, SimpleTestCase ): def test_django_logger(self): """ The 'django' base logger only output anything when DEBUG=True. """ self.logger.error("Hey, this is an error.") self.assertEqual(self.logger_output.getvalue(), "") with self.settings(DEBUG=True): self.logger.error("Hey, this is an error.") self.assertEqual(self.logger_output.getvalue(), "Hey, this is an error.\n") @override_settings(DEBUG=True) def test_django_logger_warning(self): self.logger.warning("warning") self.assertEqual(self.logger_output.getvalue(), "warning\n") @override_settings(DEBUG=True) def test_django_logger_info(self): self.logger.info("info") self.assertEqual(self.logger_output.getvalue(), "info\n") @override_settings(DEBUG=True) def test_django_logger_debug(self): self.logger.debug("debug") self.assertEqual(self.logger_output.getvalue(), "") class LoggingAssertionMixin: def assertLogRecord( self, logger_cm, msg, levelno, status_code, request=None, exc_class=None, ): self.assertEqual( records_len := len(logger_cm.records), 1, f"Wrong number of calls for {logger_cm=} in {levelno=} (expected 1, got " f"{records_len}).", ) record = logger_cm.records[0] self.assertEqual(record.getMessage(), msg) self.assertEqual(record.levelno, levelno) self.assertEqual(record.status_code, status_code) if request is not None: self.assertEqual(record.request, request) if exc_class: self.assertIsNotNone(record.exc_info) self.assertEqual(record.exc_info[0], exc_class) return record def assertLogsRequest( self, url, level, msg, status_code, logger="django.request", exc_class=None ): with self.assertLogs(logger, level) as cm: try: self.client.get(url) except views.UncaughtException: pass self.assertLogRecord( cm, msg, getattr(logging, level), status_code, exc_class=exc_class ) @override_settings(DEBUG=True, ROOT_URLCONF="logging_tests.urls") class HandlerLoggingTests( SetupDefaultLoggingMixin, LoggingAssertionMixin, LoggingCaptureMixin, SimpleTestCase ): def test_page_found_no_warning(self): self.client.get("/innocent/") self.assertEqual(self.logger_output.getvalue(), "") def test_redirect_no_warning(self): self.client.get("/redirect/") self.assertEqual(self.logger_output.getvalue(), "") def test_page_not_found_warning(self): self.assertLogsRequest( url="/does_not_exist/", level="WARNING", status_code=404, msg="Not Found: /does_not_exist/", ) def test_control_chars_escaped(self): self.assertLogsRequest( url="/%1B[1;31mNOW IN RED!!!1B[0m/", level="WARNING", status_code=404, msg=r"Not Found: /\x1b[1;31mNOW IN RED!!!1B[0m/", ) async def test_async_page_not_found_warning(self): with self.assertLogs("django.request", "WARNING") as cm: await self.async_client.get("/does_not_exist/") self.assertLogRecord(cm, "Not Found: /does_not_exist/", logging.WARNING, 404) async def test_async_control_chars_escaped(self): with self.assertLogs("django.request", "WARNING") as cm: await self.async_client.get(r"/%1B[1;31mNOW IN RED!!!1B[0m/") self.assertLogRecord( cm, r"Not Found: /\x1b[1;31mNOW IN RED!!!1B[0m/", logging.WARNING, 404 ) def test_page_not_found_raised(self): self.assertLogsRequest( url="/does_not_exist_raised/", level="WARNING", status_code=404, msg="Not Found: /does_not_exist_raised/", ) def test_uncaught_exception(self): self.assertLogsRequest( url="/uncaught_exception/", level="ERROR", status_code=500, msg="Internal Server Error: /uncaught_exception/", exc_class=views.UncaughtException, ) def test_internal_server_error(self): self.assertLogsRequest( url="/internal_server_error/", level="ERROR", status_code=500, msg="Internal Server Error: /internal_server_error/", ) def test_internal_server_error_599(self): self.assertLogsRequest( url="/internal_server_error/?status=599", level="ERROR", status_code=599, msg="Unknown Status Code: /internal_server_error/", ) def test_permission_denied(self): self.assertLogsRequest( url="/permission_denied/", level="WARNING", status_code=403, msg="Forbidden (Permission denied): /permission_denied/", exc_class=PermissionDenied, ) def test_multi_part_parser_error(self): self.assertLogsRequest( url="/multi_part_parser_error/", level="WARNING", status_code=400, msg="Bad request (Unable to parse request body): /multi_part_parser_error/", exc_class=MultiPartParserError, ) @override_settings( DEBUG=True, USE_I18N=True, LANGUAGES=[("en", "English")], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="logging_tests.urls_i18n", ) class I18nLoggingTests(SetupDefaultLoggingMixin, LoggingCaptureMixin, SimpleTestCase): def test_i18n_page_found_no_warning(self): self.client.get("/exists/") self.client.get("/en/exists/") self.assertEqual(self.logger_output.getvalue(), "") def test_i18n_page_not_found_warning(self): self.client.get("/this_does_not/") self.client.get("/en/nor_this/") self.assertEqual( self.logger_output.getvalue(), "Not Found: /this_does_not/\nNot Found: /en/nor_this/\n", ) class CallbackFilterTest(SimpleTestCase): def test_sense(self): f_false = CallbackFilter(lambda r: False) f_true = CallbackFilter(lambda r: True) self.assertFalse(f_false.filter("record")) self.assertTrue(f_true.filter("record")) def test_passes_on_record(self): collector = [] def _callback(record): collector.append(record) return True f = CallbackFilter(_callback) f.filter("a record") self.assertEqual(collector, ["a record"]) class AdminEmailHandlerTest(SimpleTestCase): logger = logging.getLogger("django") request_factory = RequestFactory() def get_admin_email_handler(self, logger): # AdminEmailHandler does not get filtered out # even with DEBUG=True. return [ h for h in logger.handlers if h.__class__.__name__ == "AdminEmailHandler" ][0] def test_fail_silently(self): admin_email_handler = self.get_admin_email_handler(self.logger) self.assertTrue(admin_email_handler.connection().fail_silently) @override_settings( ADMINS=["admin@example.com"], EMAIL_SUBJECT_PREFIX="-SuperAwesomeSubject-", ) def test_accepts_args(self): """ User-supplied arguments and the EMAIL_SUBJECT_PREFIX setting are used to compose the email subject (#16736). """ message = "Custom message that says '%s' and '%s'" token1 = "ping" token2 = "pong" admin_email_handler = self.get_admin_email_handler(self.logger) # Backup then override original filters orig_filters = admin_email_handler.filters try: admin_email_handler.filters = [] self.logger.error(message, token1, token2) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ["admin@example.com"]) self.assertEqual( mail.outbox[0].subject, "-SuperAwesomeSubject-ERROR: " "Custom message that says 'ping' and 'pong'", ) finally: # Restore original filters admin_email_handler.filters = orig_filters @override_settings( ADMINS=["admin@example.com"], EMAIL_SUBJECT_PREFIX="-SuperAwesomeSubject-", INTERNAL_IPS=["127.0.0.1"], ) def test_accepts_args_and_request(self): """ The subject is also handled if being passed a request object. """ message = "Custom message that says '%s' and '%s'" token1 = "ping" token2 = "pong" admin_email_handler = self.get_admin_email_handler(self.logger) # Backup then override original filters orig_filters = admin_email_handler.filters try: admin_email_handler.filters = [] request = self.request_factory.get("/") self.logger.error( message, token1, token2, extra={ "status_code": 403, "request": request, }, ) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ["admin@example.com"]) self.assertEqual( mail.outbox[0].subject, "-SuperAwesomeSubject-ERROR (internal IP): " "Custom message that says 'ping' and 'pong'", ) finally: # Restore original filters admin_email_handler.filters = orig_filters @override_settings( ADMINS=["admin@example.com"], EMAIL_SUBJECT_PREFIX="", DEBUG=False, ) def test_subject_accepts_newlines(self): """ Newlines in email reports' subjects are escaped to prevent AdminErrorHandler from failing (#17281). """ message = "Message \r\n with newlines" expected_subject = "ERROR: Message \\r\\n with newlines" self.assertEqual(len(mail.outbox), 0) self.logger.error(message) self.assertEqual(len(mail.outbox), 1) self.assertNotIn("\n", mail.outbox[0].subject) self.assertNotIn("\r", mail.outbox[0].subject) self.assertEqual(mail.outbox[0].subject, expected_subject) @override_settings( ADMINS=["admin@example.com"], DEBUG=False, ) def test_uses_custom_email_backend(self): """ Refs #19325 """ message = "All work and no play makes Jack a dull boy" admin_email_handler = self.get_admin_email_handler(self.logger) mail_admins_called = {"called": False} def my_mail_admins(*args, **kwargs): connection = kwargs["connection"] self.assertIsInstance(connection, MyEmailBackend) mail_admins_called["called"] = True # Monkeypatches orig_mail_admins = mail.mail_admins orig_email_backend = admin_email_handler.email_backend mail.mail_admins = my_mail_admins admin_email_handler.email_backend = "logging_tests.logconfig.MyEmailBackend" try: self.logger.error(message) self.assertTrue(mail_admins_called["called"]) finally: # Revert Monkeypatches mail.mail_admins = orig_mail_admins admin_email_handler.email_backend = orig_email_backend @override_settings( ADMINS=["admin@example.com"], ) def test_emit_non_ascii(self): """ #23593 - AdminEmailHandler should allow Unicode characters in the request. """ handler = self.get_admin_email_handler(self.logger) record = self.logger.makeRecord( "name", logging.ERROR, "function", "lno", "message", None, None ) url_path = "/º" record.request = self.request_factory.get(url_path) handler.emit(record) self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] self.assertEqual(msg.to, ["admin@example.com"]) self.assertEqual(msg.subject, "[Django] ERROR (EXTERNAL IP): message") self.assertIn("Report at %s" % url_path, msg.body) @override_settings( MANAGERS=["manager@example.com"], DEBUG=False, ) def test_customize_send_mail_method(self): class ManagerEmailHandler(AdminEmailHandler): def send_mail(self, subject, message, *args, **kwargs): mail.mail_managers( subject, message, *args, connection=self.connection(), **kwargs ) handler = ManagerEmailHandler() record = self.logger.makeRecord( "name", logging.ERROR, "function", "lno", "message", None, None ) self.assertEqual(len(mail.outbox), 0) handler.emit(record) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].to, ["manager@example.com"]) @override_settings(ALLOWED_HOSTS="example.com") def test_disallowed_host_doesnt_crash(self): admin_email_handler = self.get_admin_email_handler(self.logger) old_include_html = admin_email_handler.include_html # Text email admin_email_handler.include_html = False try: self.client.get("/", headers={"host": "evil.com"}) finally: admin_email_handler.include_html = old_include_html # HTML email admin_email_handler.include_html = True try: self.client.get("/", headers={"host": "evil.com"}) finally: admin_email_handler.include_html = old_include_html def test_default_exception_reporter_class(self): admin_email_handler = self.get_admin_email_handler(self.logger) self.assertEqual(admin_email_handler.reporter_class, ExceptionReporter) @override_settings(ADMINS=["admin@example.com"]) def test_custom_exception_reporter_is_used(self): record = self.logger.makeRecord( "name", logging.ERROR, "function", "lno", "message", None, None ) record.request = self.request_factory.get("/") handler = AdminEmailHandler( reporter_class="logging_tests.logconfig.CustomExceptionReporter" ) handler.emit(record) self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] self.assertEqual(msg.body, "message\n\ncustom traceback text") @override_settings(ADMINS=["admin@example.com"]) def test_emit_no_form_tag(self): """HTML email doesn't contain forms.""" handler = AdminEmailHandler(include_html=True) record = self.logger.makeRecord( "name", logging.ERROR, "function", "lno", "message", None, None, ) handler.emit(record) self.assertEqual(len(mail.outbox), 1) msg = mail.outbox[0] self.assertEqual(msg.subject, "[Django] ERROR: message") self.assertEqual(len(msg.alternatives), 1) body_html = str(msg.alternatives[0].content) self.assertIn('<div id="traceback">', body_html) self.assertNotIn("<form", body_html) @override_settings(ADMINS=[]) def test_emit_no_admins(self): handler = AdminEmailHandler() record = self.logger.makeRecord( "name", logging.ERROR, "function", "lno", "message", None, None, ) with mock.patch.object( handler, "format_subject", side_effect=AssertionError("Should not be called"), ): handler.emit(record) self.assertEqual(len(mail.outbox), 0) class SettingsConfigTest(AdminScriptTestCase): """ Accessing settings in a custom logging handler does not trigger a circular import error. """ def setUp(self): super().setUp() log_config = """{ 'version': 1, 'handlers': { 'custom_handler': { 'level': 'INFO', 'class': 'logging_tests.logconfig.MyHandler', } } }""" self.write_settings("settings.py", sdict={"LOGGING": log_config}) def test_circular_dependency(self): # validate is just an example command to trigger settings configuration out, err = self.run_manage(["check"]) self.assertNoOutput(err) self.assertOutput(out, "System check identified no issues (0 silenced).") def dictConfig(config): dictConfig.called = True dictConfig.called = False class SetupConfigureLogging(SimpleTestCase): """ Calling django.setup() initializes the logging configuration. """ def test_configure_initializes_logging(self): from django import setup try: with override_settings( LOGGING_CONFIG="logging_tests.tests.dictConfig", ): setup() finally: # Restore logging from settings. setup() self.assertTrue(dictConfig.called) @override_settings(DEBUG=True, ROOT_URLCONF="logging_tests.urls") class SecurityLoggerTest(LoggingAssertionMixin, SimpleTestCase): def test_suspicious_operation_creates_log_message(self): self.assertLogsRequest( url="/suspicious/", level="ERROR", msg="dubious", status_code=400, logger="django.security.SuspiciousOperation", exc_class=SuspiciousOperation, ) def test_suspicious_operation_uses_sublogger(self): self.assertLogsRequest( url="/suspicious_spec/", level="ERROR", msg="dubious", status_code=400, logger="django.security.DisallowedHost", exc_class=DisallowedHost, ) @override_settings( ADMINS=["admin@example.com"], DEBUG=False, ) def test_suspicious_email_admins(self): self.client.get("/suspicious/") self.assertEqual(len(mail.outbox), 1) self.assertIn("SuspiciousOperation at /suspicious/", mail.outbox[0].body) def test_response_logged(self): with self.assertLogs("django.security.SuspiciousOperation", "ERROR") as handler: response = self.client.get("/suspicious/") self.assertLogRecord( handler, "dubious", logging.ERROR, 400, request=response.wsgi_request ) self.assertEqual(response.status_code, 400) class SettingsCustomLoggingTest(AdminScriptTestCase): """ Using a logging defaults are still applied when using a custom callable in LOGGING_CONFIG (i.e., logging.config.fileConfig). """ def setUp(self): super().setUp() logging_conf = """ [loggers] keys=root [handlers] keys=stream [formatters] keys=simple [logger_root] handlers=stream [handler_stream] class=StreamHandler formatter=simple args=(sys.stdout,) [formatter_simple] format=%(message)s """ temp_file = NamedTemporaryFile() temp_file.write(logging_conf.encode()) temp_file.flush() self.addCleanup(temp_file.close) self.write_settings( "settings.py", sdict={ "LOGGING_CONFIG": '"logging.config.fileConfig"', "LOGGING": 'r"%s"' % temp_file.name, }, ) def test_custom_logging(self): out, err = self.run_manage(["check"]) self.assertNoOutput(err) self.assertOutput(out, "System check identified no issues (0 silenced).") class LogFormattersTests(SimpleTestCase): def test_server_formatter_styles(self): color_style = color.make_style("") formatter = ServerFormatter() formatter.style = color_style log_msg = "log message" status_code_styles = [ (200, "HTTP_SUCCESS"), (100, "HTTP_INFO"), (304, "HTTP_NOT_MODIFIED"), (300, "HTTP_REDIRECT"), (404, "HTTP_NOT_FOUND"), (400, "HTTP_BAD_REQUEST"), (500, "HTTP_SERVER_ERROR"), ] for status_code, style in status_code_styles: record = logging.makeLogRecord({"msg": log_msg, "status_code": status_code}) self.assertEqual( formatter.format(record), getattr(color_style, style)(log_msg) ) record = logging.makeLogRecord({"msg": log_msg}) self.assertEqual(formatter.format(record), log_msg) def test_server_formatter_default_format(self): server_time = "2016-09-25 10:20:30" log_msg = "log message" logger = logging.getLogger("django.server") @contextmanager def patch_django_server_logger(): old_stream = logger.handlers[0].stream new_stream = StringIO() logger.handlers[0].stream = new_stream yield new_stream logger.handlers[0].stream = old_stream with patch_django_server_logger() as logger_output: logger.info(log_msg, extra={"server_time": server_time}) self.assertEqual( "[%s] %s\n" % (server_time, log_msg), logger_output.getvalue() ) with patch_django_server_logger() as logger_output: logger.info(log_msg) self.assertRegex( logger_output.getvalue(), r"^\[[/:,\w\s\d]+\] %s\n" % log_msg ) class LogResponseRealLoggerTests(LoggingAssertionMixin, TestCase): request = RequestFactory().get("/test-path/") def test_missing_response_raises_attribute_error(self): with self.assertRaises(AttributeError): log_response("No response provided", response=None, request=self.request) def test_missing_request_logs_with_none(self): response = HttpResponse(status=403) with self.assertLogs("django.request", level="INFO") as cm: log_response(msg := "Missing request", response=response, request=None) self.assertLogRecord(cm, msg, logging.WARNING, 403, request=None) def test_logs_5xx_as_error(self): response = HttpResponse(status=508) with self.assertLogs("django.request", level="ERROR") as cm: log_response( msg := "Server error occurred", response=response, request=self.request ) self.assertLogRecord(cm, msg, logging.ERROR, 508, self.request) def test_logs_4xx_as_warning(self): response = HttpResponse(status=418) with self.assertLogs("django.request", level="WARNING") as cm: log_response( msg := "This is a teapot!", response=response, request=self.request ) self.assertLogRecord(cm, msg, logging.WARNING, 418, self.request) def test_logs_2xx_as_info(self): response = HttpResponse(status=201) with self.assertLogs("django.request", level="INFO") as cm: log_response(msg := "OK response", response=response, request=self.request) self.assertLogRecord(cm, msg, logging.INFO, 201, self.request) def test_custom_log_level(self): response = HttpResponse(status=403) with self.assertLogs("django.request", level="DEBUG") as cm: log_response( msg := "Debug level log", response=response, request=self.request, level="debug", ) self.assertLogRecord(cm, msg, logging.DEBUG, 403, self.request) def test_logs_only_once_per_response(self): response = HttpResponse(status=500) with self.assertLogs("django.request", level="ERROR") as cm: log_response("First log", response=response, request=self.request) log_response("Second log", response=response, request=self.request) self.assertLogRecord(cm, "First log", logging.ERROR, 500, self.request) def test_exc_info_output(self): response = HttpResponse(status=500) try: raise ValueError("Simulated failure") except ValueError as exc: with self.assertLogs("django.request", level="ERROR") as cm: log_response( "With exception", response=response, request=self.request, exception=exc, ) self.assertLogRecord(cm, "With exception", logging.ERROR, 500, self.request) self.assertIn("ValueError", "\n".join(cm.output)) # Stack trace included def test_format_args_are_applied(self): response = HttpResponse(status=500) with self.assertLogs("django.request", level="ERROR") as cm: log_response( "Something went wrong: %s (%d)", "DB error", 42, response=response, request=self.request, ) msg = "Something went wrong: DB error (42)" self.assertLogRecord(cm, msg, logging.ERROR, 500, self.request) def test_logs_with_custom_logger(self): handler = logging.StreamHandler(log_stream := StringIO()) handler.setFormatter(logging.Formatter("%(levelname)s:%(name)s:%(message)s")) custom_logger = logging.getLogger("my.custom.logger") custom_logger.setLevel(logging.DEBUG) custom_logger.addHandler(handler) self.addCleanup(custom_logger.removeHandler, handler) response = HttpResponse(status=404) log_response( msg := "Handled by custom logger", response=response, request=self.request, logger=custom_logger, ) self.assertEqual( f"WARNING:my.custom.logger:{msg}", log_stream.getvalue().strip() ) def test_unicode_escape_escaping(self): test_cases = [ # Control characters. ("line\nbreak", "line\\nbreak"), ("carriage\rreturn", "carriage\\rreturn"), ("tab\tseparated", "tab\\tseparated"), ("formfeed\f", "formfeed\\x0c"), ("bell\a", "bell\\x07"), ("multi\nline\ntext", "multi\\nline\\ntext"), # Slashes. ("slash\\test", "slash\\\\test"), ("back\\slash", "back\\\\slash"), # Quotes. ('quote"test"', 'quote"test"'), ("quote'test'", "quote'test'"), # Accented, composed characters, emojis and symbols. ("café", "caf\\xe9"), ("e\u0301", "e\\u0301"), # e + combining acute ("smile🙂", "smile\\U0001f642"), ("weird ☃️", "weird \\u2603\\ufe0f"), # Non-Latin alphabets. ("Привет", "\\u041f\\u0440\\u0438\\u0432\\u0435\\u0442"), ("你好", "\\u4f60\\u597d"), # ANSI escape sequences. ("escape\x1b[31mred\x1b[0m", "escape\\x1b[31mred\\x1b[0m"), ( "/\x1b[1;31mCAUTION!!YOU ARE PWNED\x1b[0m/", "/\\x1b[1;31mCAUTION!!YOU ARE PWNED\\x1b[0m/", ), ( "/\r\n\r\n1984-04-22 INFO Listening on 0.0.0.0:8080\r\n\r\n", "/\\r\\n\\r\\n1984-04-22 INFO Listening on 0.0.0.0:8080\\r\\n\\r\\n", ), # Plain safe input. ("normal-path", "normal-path"), ("slash/colon:", "slash/colon:"), # Non strings. (0, "0"), ([1, 2, 3], "[1, 2, 3]"), ({"test": "🙂"}, "{'test': '🙂'}"), ] msg = "Test message: %s" for case, expected in test_cases: with ( self.assertLogs("django.request", level="ERROR") as cm, self.subTest(case=case), ): response = HttpResponse(status=318) log_response(msg, case, response=response, level="error") record = self.assertLogRecord( cm, msg % expected, levelno=logging.ERROR, status_code=318, request=None, ) # Log record is always a single line. self.assertEqual(len(record.getMessage().splitlines()), 1)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/logging_tests/urls.py
tests/logging_tests/urls.py
from django.urls import path from . import views urlpatterns = [ path("innocent/", views.innocent), path("redirect/", views.redirect), path("suspicious/", views.suspicious), path("suspicious_spec/", views.suspicious_spec), path("internal_server_error/", views.internal_server_error), path("uncaught_exception/", views.uncaught_exception), path("permission_denied/", views.permission_denied), path("multi_part_parser_error/", views.multi_part_parser_error), path("does_not_exist_raised/", views.does_not_exist_raised), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/null_fk/models.py
tests/null_fk/models.py
""" Regression tests for proper working of ForeignKey(null=True). """ from django.db import models class SystemDetails(models.Model): details = models.TextField() class SystemInfo(models.Model): system_details = models.ForeignKey(SystemDetails, models.CASCADE) system_name = models.CharField(max_length=32) class Forum(models.Model): system_info = models.ForeignKey(SystemInfo, models.CASCADE) forum_name = models.CharField(max_length=32) class Post(models.Model): forum = models.ForeignKey(Forum, models.SET_NULL, null=True) title = models.CharField(max_length=32) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, models.SET_NULL, null=True) comment_text = models.CharField(max_length=250) class Meta: ordering = ("comment_text",) # Ticket 15823 class Item(models.Model): title = models.CharField(max_length=100) class PropertyValue(models.Model): label = models.CharField(max_length=100) class Property(models.Model): item = models.ForeignKey(Item, models.CASCADE, related_name="props") key = models.CharField(max_length=100) value = models.ForeignKey(PropertyValue, models.SET_NULL, null=True)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/null_fk/__init__.py
tests/null_fk/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/null_fk/tests.py
tests/null_fk/tests.py
from django.db.models import Q from django.test import TestCase from .models import Comment, Forum, Item, Post, PropertyValue, SystemDetails, SystemInfo class NullFkTests(TestCase): def test_null_fk(self): d = SystemDetails.objects.create(details="First details") s = SystemInfo.objects.create(system_name="First forum", system_details=d) f = Forum.objects.create(system_info=s, forum_name="First forum") p = Post.objects.create(forum=f, title="First Post") c1 = Comment.objects.create(post=p, comment_text="My first comment") c2 = Comment.objects.create(comment_text="My second comment") # Starting from comment, make sure that a .select_related(...) with a # specified set of fields will properly LEFT JOIN multiple levels of # NULLs (and the things that come after the NULLs, or else data that # should exist won't). Regression test for #7369. c = Comment.objects.select_related().get(id=c1.id) self.assertEqual(c.post, p) self.assertIsNone(Comment.objects.select_related().get(id=c2.id).post) self.assertQuerySetEqual( Comment.objects.select_related("post__forum__system_info").all(), [ (c1.id, "My first comment", "<Post: First Post>"), (c2.id, "My second comment", "None"), ], transform=lambda c: (c.id, c.comment_text, repr(c.post)), ) # Regression test for #7530, #7716. self.assertIsNone( Comment.objects.select_related("post").filter(post__isnull=True)[0].post ) self.assertQuerySetEqual( Comment.objects.select_related("post__forum__system_info__system_details"), [ (c1.id, "My first comment", "<Post: First Post>"), (c2.id, "My second comment", "None"), ], transform=lambda c: (c.id, c.comment_text, repr(c.post)), ) def test_combine_isnull(self): item = Item.objects.create(title="Some Item") pv = PropertyValue.objects.create(label="Some Value") item.props.create(key="a", value=pv) item.props.create(key="b") # value=NULL q1 = Q(props__key="a", props__value=pv) q2 = Q(props__key="b", props__value__isnull=True) # Each of these individually should return the item. self.assertEqual(Item.objects.get(q1), item) self.assertEqual(Item.objects.get(q2), item) # Logically, qs1 and qs2, and qs3 and qs4 should be the same. qs1 = Item.objects.filter(q1) & Item.objects.filter(q2) qs2 = Item.objects.filter(q2) & Item.objects.filter(q1) qs3 = Item.objects.filter(q1) | Item.objects.filter(q2) qs4 = Item.objects.filter(q2) | Item.objects.filter(q1) # Regression test for #15823. self.assertEqual(list(qs1), list(qs2)) self.assertEqual(list(qs3), list(qs4))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/delete_regress/models.py
tests/delete_regress/models.py
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Award(models.Model): name = models.CharField(max_length=25) object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType, models.CASCADE) content_object = GenericForeignKey() class AwardNote(models.Model): award = models.ForeignKey(Award, models.CASCADE) note = models.CharField(max_length=100) class Person(models.Model): name = models.CharField(max_length=25) awards = GenericRelation(Award) class Book(models.Model): pagecount = models.IntegerField() owner = models.ForeignKey("Child", models.CASCADE, null=True) class Toy(models.Model): name = models.CharField(max_length=50) class Child(models.Model): name = models.CharField(max_length=50) toys = models.ManyToManyField(Toy, through="PlayedWith") class PlayedWith(models.Model): child = models.ForeignKey(Child, models.CASCADE) toy = models.ForeignKey(Toy, models.CASCADE) date = models.DateField(db_column="date_col") class PlayedWithNote(models.Model): played = models.ForeignKey(PlayedWith, models.CASCADE) note = models.TextField() class Contact(models.Model): label = models.CharField(max_length=100) class Email(Contact): email_address = models.EmailField(max_length=100) class Researcher(models.Model): contacts = models.ManyToManyField(Contact, related_name="research_contacts") primary_contact = models.ForeignKey( Contact, models.SET_NULL, null=True, related_name="primary_contacts" ) secondary_contact = models.ForeignKey( Contact, models.SET_NULL, null=True, related_name="secondary_contacts" ) class Food(models.Model): name = models.CharField(max_length=20, unique=True) class Eaten(models.Model): food = models.ForeignKey(Food, models.CASCADE, to_field="name") meal = models.CharField(max_length=20) # Models for #15776 class Policy(models.Model): policy_number = models.CharField(max_length=10) class Version(models.Model): policy = models.ForeignKey(Policy, models.CASCADE) class Location(models.Model): version = models.ForeignKey(Version, models.SET_NULL, blank=True, null=True) class Item(models.Model): version = models.ForeignKey(Version, models.CASCADE) location = models.ForeignKey(Location, models.SET_NULL, blank=True, null=True) location_value = models.ForeignKey( Location, models.SET(42), default=1, db_constraint=False, related_name="+" ) # Models for #16128 class File(models.Model): pass class Image(File): class Meta: proxy = True class Photo(Image): class Meta: proxy = True class FooImage(models.Model): my_image = models.ForeignKey(Image, models.CASCADE) class FooFile(models.Model): my_file = models.ForeignKey(File, models.CASCADE) class FooPhoto(models.Model): my_photo = models.ForeignKey(Photo, models.CASCADE) class FooFileProxy(FooFile): class Meta: proxy = True class OrgUnit(models.Model): name = models.CharField(max_length=64, unique=True) class Login(models.Model): description = models.CharField(max_length=32) orgunit = models.ForeignKey(OrgUnit, models.CASCADE) class House(models.Model): address = models.CharField(max_length=32) class OrderedPerson(models.Model): name = models.CharField(max_length=32) lives_in = models.ForeignKey(House, models.CASCADE) class Meta: ordering = ["name"] def get_best_toy(): toy, _ = Toy.objects.get_or_create(name="best") return toy def get_worst_toy(): toy, _ = Toy.objects.get_or_create(name="worst") return toy class Collector(models.Model): best_toy = models.ForeignKey( Toy, default=get_best_toy, on_delete=models.SET_DEFAULT, related_name="toys" ) worst_toy = models.ForeignKey( Toy, models.SET(get_worst_toy), related_name="bad_toys" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/delete_regress/__init__.py
tests/delete_regress/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/delete_regress/tests.py
tests/delete_regress/tests.py
import datetime from django.db import connection, models, transaction from django.db.models import Exists, OuterRef from django.test import ( SimpleTestCase, 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) # Close down the second connection. self.addCleanup(self.conn2.close) self.addCleanup(self.conn2.rollback) 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="carl@science.edu" ) 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): """ 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") 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) def test_self_reference_with_through_m2m_at_second_level(self): toy = Toy.objects.create(name="Paints") child = Child.objects.create(name="Juan") Book.objects.create(pagecount=500, owner=child) PlayedWith.objects.create(child=child, toy=toy, date=datetime.date.today()) with self.assertNumQueries(1) as ctx: Book.objects.filter( Exists( Book.objects.filter( pk=OuterRef("pk"), owner__toys=toy.pk, ), ) ).delete() self.assertIs(Book.objects.exists(), False) sql = ctx.captured_queries[0]["sql"].lower() if connection.features.delete_can_self_reference_subquery: self.assertEqual(sql.count("select"), 1) class DeleteDistinct(SimpleTestCase): def test_disallowed_delete_distinct_on(self): msg = "Cannot call delete() after .distinct(*fields)." with self.assertRaisesMessage(TypeError, msg): Book.objects.distinct("id").delete() class SetQueryCountTests(TestCase): def test_set_querycount(self): policy = Policy.objects.create() version = Version.objects.create(policy=policy) location = Location.objects.create(version=version) Item.objects.create( version=version, location=location, location_value=location, ) # 2 UPDATEs for SET of item values and one for DELETE locations. with self.assertNumQueries(3): location.delete() class SetCallableCollectorDefaultTests(TestCase): def test_set(self): # Collector doesn't call callables used by models.SET and # models.SET_DEFAULT if not necessary. Toy.objects.create(name="test") Toy.objects.all().delete() self.assertSequenceEqual(Toy.objects.all(), [])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/httpwrappers/__init__.py
tests/httpwrappers/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/httpwrappers/tests.py
tests/httpwrappers/tests.py
import copy import json import os import pickle import unittest import uuid from django.core.exceptions import DisallowedRedirect from django.core.serializers.json import DjangoJSONEncoder from django.core.signals import request_finished from django.db import close_old_connections from django.http import ( BadHeaderError, HttpResponse, HttpResponseNotAllowed, HttpResponseNotModified, HttpResponsePermanentRedirect, HttpResponseRedirect, JsonResponse, QueryDict, SimpleCookie, StreamingHttpResponse, parse_cookie, ) from django.test import SimpleTestCase from django.utils.functional import lazystr from django.utils.http import MAX_URL_REDIRECT_LENGTH class QueryDictTests(SimpleTestCase): def test_create_with_no_args(self): self.assertEqual(QueryDict(), QueryDict("")) def test_missing_key(self): q = QueryDict() with self.assertRaises(KeyError): q.__getitem__("foo") def test_immutability(self): q = QueryDict() with self.assertRaises(AttributeError): q.__setitem__("something", "bar") with self.assertRaises(AttributeError): q.setlist("foo", ["bar"]) with self.assertRaises(AttributeError): q.appendlist("foo", ["bar"]) with self.assertRaises(AttributeError): q.update({"foo": "bar"}) with self.assertRaises(AttributeError): q.pop("foo") with self.assertRaises(AttributeError): q.popitem() with self.assertRaises(AttributeError): q.clear() def test_immutable_get_with_default(self): q = QueryDict() self.assertEqual(q.get("foo", "default"), "default") def test_immutable_basic_operations(self): q = QueryDict() self.assertEqual(q.getlist("foo"), []) self.assertNotIn("foo", q) self.assertEqual(list(q), []) self.assertEqual(list(q.items()), []) self.assertEqual(list(q.lists()), []) self.assertEqual(list(q.keys()), []) self.assertEqual(list(q.values()), []) self.assertEqual(len(q), 0) self.assertEqual(q.urlencode(), "") def test_single_key_value(self): """Test QueryDict with one key/value pair""" q = QueryDict("foo=bar") self.assertEqual(q["foo"], "bar") with self.assertRaises(KeyError): q.__getitem__("bar") with self.assertRaises(AttributeError): q.__setitem__("something", "bar") self.assertEqual(q.get("foo", "default"), "bar") self.assertEqual(q.get("bar", "default"), "default") self.assertEqual(q.getlist("foo"), ["bar"]) self.assertEqual(q.getlist("bar"), []) with self.assertRaises(AttributeError): q.setlist("foo", ["bar"]) with self.assertRaises(AttributeError): q.appendlist("foo", ["bar"]) self.assertIn("foo", q) self.assertNotIn("bar", q) self.assertEqual(list(q), ["foo"]) self.assertEqual(list(q.items()), [("foo", "bar")]) self.assertEqual(list(q.lists()), [("foo", ["bar"])]) self.assertEqual(list(q.keys()), ["foo"]) self.assertEqual(list(q.values()), ["bar"]) self.assertEqual(len(q), 1) with self.assertRaises(AttributeError): q.update({"foo": "bar"}) with self.assertRaises(AttributeError): q.pop("foo") with self.assertRaises(AttributeError): q.popitem() with self.assertRaises(AttributeError): q.clear() with self.assertRaises(AttributeError): q.setdefault("foo", "bar") self.assertEqual(q.urlencode(), "foo=bar") def test_urlencode(self): q = QueryDict(mutable=True) q["next"] = "/a&b/" self.assertEqual(q.urlencode(), "next=%2Fa%26b%2F") self.assertEqual(q.urlencode(safe="/"), "next=/a%26b/") q = QueryDict(mutable=True) q["next"] = "/t\xebst&key/" self.assertEqual(q.urlencode(), "next=%2Ft%C3%ABst%26key%2F") self.assertEqual(q.urlencode(safe="/"), "next=/t%C3%ABst%26key/") def test_urlencode_int(self): # Normally QueryDict doesn't contain non-string values but lazily # written tests may make that mistake. q = QueryDict(mutable=True) q["a"] = 1 self.assertEqual(q.urlencode(), "a=1") def test_mutable_copy(self): """A copy of a QueryDict is mutable.""" q = QueryDict().copy() with self.assertRaises(KeyError): q.__getitem__("foo") q["name"] = "john" self.assertEqual(q["name"], "john") def test_mutable_delete(self): q = QueryDict(mutable=True) q["name"] = "john" del q["name"] self.assertNotIn("name", q) def test_basic_mutable_operations(self): q = QueryDict(mutable=True) q["name"] = "john" self.assertEqual(q.get("foo", "default"), "default") self.assertEqual(q.get("name", "default"), "john") self.assertEqual(q.getlist("name"), ["john"]) self.assertEqual(q.getlist("foo"), []) q.setlist("foo", ["bar", "baz"]) self.assertEqual(q.get("foo", "default"), "baz") self.assertEqual(q.getlist("foo"), ["bar", "baz"]) q.appendlist("foo", "another") self.assertEqual(q.getlist("foo"), ["bar", "baz", "another"]) self.assertEqual(q["foo"], "another") self.assertIn("foo", q) self.assertCountEqual(q, ["foo", "name"]) self.assertCountEqual(q.items(), [("foo", "another"), ("name", "john")]) self.assertCountEqual( q.lists(), [("foo", ["bar", "baz", "another"]), ("name", ["john"])] ) self.assertCountEqual(q.keys(), ["foo", "name"]) self.assertCountEqual(q.values(), ["another", "john"]) q.update({"foo": "hello"}) self.assertEqual(q["foo"], "hello") self.assertEqual(q.get("foo", "not available"), "hello") self.assertEqual(q.getlist("foo"), ["bar", "baz", "another", "hello"]) self.assertEqual(q.pop("foo"), ["bar", "baz", "another", "hello"]) self.assertEqual(q.pop("foo", "not there"), "not there") self.assertEqual(q.get("foo", "not there"), "not there") self.assertEqual(q.setdefault("foo", "bar"), "bar") self.assertEqual(q["foo"], "bar") self.assertEqual(q.getlist("foo"), ["bar"]) self.assertIn(q.urlencode(), ["foo=bar&name=john", "name=john&foo=bar"]) q.clear() self.assertEqual(len(q), 0) def test_multiple_keys(self): """Test QueryDict with two key/value pairs with same keys.""" q = QueryDict("vote=yes&vote=no") self.assertEqual(q["vote"], "no") with self.assertRaises(AttributeError): q.__setitem__("something", "bar") self.assertEqual(q.get("vote", "default"), "no") self.assertEqual(q.get("foo", "default"), "default") self.assertEqual(q.getlist("vote"), ["yes", "no"]) self.assertEqual(q.getlist("foo"), []) with self.assertRaises(AttributeError): q.setlist("foo", ["bar", "baz"]) with self.assertRaises(AttributeError): q.setlist("foo", ["bar", "baz"]) with self.assertRaises(AttributeError): q.appendlist("foo", ["bar"]) self.assertIn("vote", q) self.assertNotIn("foo", q) self.assertEqual(list(q), ["vote"]) self.assertEqual(list(q.items()), [("vote", "no")]) self.assertEqual(list(q.lists()), [("vote", ["yes", "no"])]) self.assertEqual(list(q.keys()), ["vote"]) self.assertEqual(list(q.values()), ["no"]) self.assertEqual(len(q), 1) with self.assertRaises(AttributeError): q.update({"foo": "bar"}) with self.assertRaises(AttributeError): q.pop("foo") with self.assertRaises(AttributeError): q.popitem() with self.assertRaises(AttributeError): q.clear() with self.assertRaises(AttributeError): q.setdefault("foo", "bar") with self.assertRaises(AttributeError): q.__delitem__("vote") def test_pickle(self): q = QueryDict() q1 = pickle.loads(pickle.dumps(q, 2)) self.assertEqual(q, q1) q = QueryDict("a=b&c=d") q1 = pickle.loads(pickle.dumps(q, 2)) self.assertEqual(q, q1) q = QueryDict("a=b&c=d&a=1") q1 = pickle.loads(pickle.dumps(q, 2)) self.assertEqual(q, q1) def test_update_from_querydict(self): """Regression test for #8278: QueryDict.update(QueryDict)""" x = QueryDict("a=1&a=2", mutable=True) y = QueryDict("a=3&a=4") x.update(y) self.assertEqual(x.getlist("a"), ["1", "2", "3", "4"]) def test_non_default_encoding(self): """#13572 - QueryDict with a non-default encoding""" q = QueryDict("cur=%A4", encoding="iso-8859-15") self.assertEqual(q.encoding, "iso-8859-15") self.assertEqual(list(q.items()), [("cur", "€")]) self.assertEqual(q.urlencode(), "cur=%A4") q = q.copy() self.assertEqual(q.encoding, "iso-8859-15") self.assertEqual(list(q.items()), [("cur", "€")]) self.assertEqual(q.urlencode(), "cur=%A4") self.assertEqual(copy.copy(q).encoding, "iso-8859-15") self.assertEqual(copy.deepcopy(q).encoding, "iso-8859-15") def test_querydict_fromkeys(self): self.assertEqual( QueryDict.fromkeys(["key1", "key2", "key3"]), QueryDict("key1&key2&key3") ) def test_fromkeys_with_nonempty_value(self): self.assertEqual( QueryDict.fromkeys(["key1", "key2", "key3"], value="val"), QueryDict("key1=val&key2=val&key3=val"), ) def test_fromkeys_is_immutable_by_default(self): # Match behavior of __init__() which is also immutable by default. q = QueryDict.fromkeys(["key1", "key2", "key3"]) with self.assertRaisesMessage( AttributeError, "This QueryDict instance is immutable" ): q["key4"] = "nope" def test_fromkeys_mutable_override(self): q = QueryDict.fromkeys(["key1", "key2", "key3"], mutable=True) q["key4"] = "yep" self.assertEqual(q, QueryDict("key1&key2&key3&key4=yep")) def test_duplicates_in_fromkeys_iterable(self): self.assertEqual(QueryDict.fromkeys("xyzzy"), QueryDict("x&y&z&z&y")) def test_fromkeys_with_nondefault_encoding(self): key_utf16 = b"\xff\xfe\x8e\x02\xdd\x01\x9e\x02" value_utf16 = b"\xff\xfe\xdd\x01n\x00l\x00P\x02\x8c\x02" q = QueryDict.fromkeys([key_utf16], value=value_utf16, encoding="utf-16") expected = QueryDict("", mutable=True) expected["ʎǝʞ"] = "ǝnlɐʌ" self.assertEqual(q, expected) def test_fromkeys_empty_iterable(self): self.assertEqual(QueryDict.fromkeys([]), QueryDict("")) def test_fromkeys_noniterable(self): with self.assertRaises(TypeError): QueryDict.fromkeys(0) class HttpResponseTests(SimpleTestCase): def test_headers_type(self): r = HttpResponse() # ASCII strings or bytes values are converted to strings. r.headers["key"] = "test" self.assertEqual(r.headers["key"], "test") r.headers["key"] = b"test" self.assertEqual(r.headers["key"], "test") self.assertIn(b"test", r.serialize_headers()) # Non-ASCII values are serialized to Latin-1. r.headers["key"] = "café" self.assertIn("café".encode("latin-1"), r.serialize_headers()) # Other Unicode values are MIME-encoded (there's no way to pass them as # bytes). r.headers["key"] = "†" self.assertEqual(r.headers["key"], "=?utf-8?b?4oCg?=") self.assertIn(b"=?utf-8?b?4oCg?=", r.serialize_headers()) # The response also converts string or bytes keys to strings, but # requires them to contain ASCII r = HttpResponse() del r.headers["Content-Type"] r.headers["foo"] = "bar" headers = list(r.headers.items()) self.assertEqual(len(headers), 1) self.assertEqual(headers[0], ("foo", "bar")) r = HttpResponse() del r.headers["Content-Type"] r.headers[b"foo"] = "bar" headers = list(r.headers.items()) self.assertEqual(len(headers), 1) self.assertEqual(headers[0], ("foo", "bar")) self.assertIsInstance(headers[0][0], str) r = HttpResponse() with self.assertRaises(UnicodeError): r.headers.__setitem__("føø", "bar") with self.assertRaises(UnicodeError): r.headers.__setitem__("føø".encode(), "bar") def test_long_line(self): # Bug #20889: long lines trigger newlines to be added to headers # (which is not allowed due to bug #10188) h = HttpResponse() f = b"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz a\xcc\x88" f = f.decode("utf-8") h.headers["Content-Disposition"] = 'attachment; filename="%s"' % f # This one is triggering https://bugs.python.org/issue20747, that is # Python will itself insert a newline in the header h.headers["Content-Disposition"] = ( 'attachment; filename="EdelRot_Blu\u0308te (3)-0.JPG"' ) def test_newlines_in_headers(self): # Bug #10188: Do not allow newlines in headers (CR or LF) r = HttpResponse() with self.assertRaises(BadHeaderError): r.headers.__setitem__("test\rstr", "test") with self.assertRaises(BadHeaderError): r.headers.__setitem__("test\nstr", "test") def test_encoded_with_newlines_in_headers(self): """ Keys & values which throw a UnicodeError when encoding/decoding should still be checked for newlines and re-raised as a BadHeaderError. These specifically would still throw BadHeaderError after decoding successfully, because the newlines are sandwiched in the middle of the string and email.Header leaves those as they are. """ r = HttpResponse() pairs = ( ("†\nother", "test"), ("test", "†\nother"), (b"\xe2\x80\xa0\nother", "test"), ("test", b"\xe2\x80\xa0\nother"), ) msg = "Header values can't contain newlines" for key, value in pairs: with self.subTest(key=key, value=value): with self.assertRaisesMessage(BadHeaderError, msg): r[key] = value def test_dict_behavior(self): """ Test for bug #14020: Make HttpResponse.get work like dict.get """ r = HttpResponse() self.assertIsNone(r.get("test")) def test_non_string_content(self): # Bug 16494: HttpResponse should behave consistently with non-strings r = HttpResponse(12345) self.assertEqual(r.content, b"12345") # test content via property r = HttpResponse() r.content = 12345 self.assertEqual(r.content, b"12345") def test_memoryview_content(self): r = HttpResponse(memoryview(b"memoryview")) self.assertEqual(r.content, b"memoryview") def test_iter_content(self): r = HttpResponse(["abc", "def", "ghi"]) self.assertEqual(r.content, b"abcdefghi") # test iter content via property r = HttpResponse() r.content = ["idan", "alex", "jacob"] self.assertEqual(r.content, b"idanalexjacob") r = HttpResponse() r.content = [1, 2, 3] self.assertEqual(r.content, b"123") # test odd inputs r = HttpResponse() r.content = ["1", "2", 3, "\u079e"] # '\xde\x9e' == unichr(1950).encode() self.assertEqual(r.content, b"123\xde\x9e") # .content can safely be accessed multiple times. r = HttpResponse(iter(["hello", "world"])) self.assertEqual(r.content, r.content) self.assertEqual(r.content, b"helloworld") # __iter__ can safely be called multiple times (#20187). self.assertEqual(b"".join(r), b"helloworld") self.assertEqual(b"".join(r), b"helloworld") # Accessing .content still works. self.assertEqual(r.content, b"helloworld") # Accessing .content also works if the response was iterated first. r = HttpResponse(iter(["hello", "world"])) self.assertEqual(b"".join(r), b"helloworld") self.assertEqual(r.content, b"helloworld") # Additional content can be written to the response. r = HttpResponse(iter(["hello", "world"])) self.assertEqual(r.content, b"helloworld") r.write("!") self.assertEqual(r.content, b"helloworld!") def test_iterator_isnt_rewound(self): # Regression test for #13222 r = HttpResponse("abc") i = iter(r) self.assertEqual(list(i), [b"abc"]) self.assertEqual(list(i), []) def test_lazy_content(self): r = HttpResponse(lazystr("helloworld")) self.assertEqual(r.content, b"helloworld") def test_file_interface(self): r = HttpResponse() r.write(b"hello") self.assertEqual(r.tell(), 5) r.write("привет") self.assertEqual(r.tell(), 17) r = HttpResponse(["abc"]) r.write("def") self.assertEqual(r.tell(), 6) self.assertEqual(r.content, b"abcdef") # with Content-Encoding header r = HttpResponse() r.headers["Content-Encoding"] = "winning" r.write(b"abc") r.write(b"def") self.assertEqual(r.content, b"abcdef") def test_stream_interface(self): r = HttpResponse("asdf") self.assertEqual(r.getvalue(), b"asdf") r = HttpResponse() self.assertIs(r.writable(), True) r.writelines(["foo\n", "bar\n", "baz\n"]) self.assertEqual(r.content, b"foo\nbar\nbaz\n") def test_redirect_url_max_length(self): base_url = "https://example.com/" for length in ( MAX_URL_REDIRECT_LENGTH - 1, MAX_URL_REDIRECT_LENGTH, ): long_url = base_url + "x" * (length - len(base_url)) with self.subTest(length=length): response = HttpResponseRedirect(long_url) self.assertEqual(response.url, long_url) response = HttpResponsePermanentRedirect(long_url) self.assertEqual(response.url, long_url) def test_unsafe_redirect(self): bad_urls = [ 'data:text/html,<script>window.alert("xss")</script>', "mailto:test@example.com", "file:///etc/passwd", "é" * (MAX_URL_REDIRECT_LENGTH + 1), ] for url in bad_urls: with self.assertRaises(DisallowedRedirect): HttpResponseRedirect(url) with self.assertRaises(DisallowedRedirect): HttpResponsePermanentRedirect(url) def test_header_deletion(self): r = HttpResponse("hello") r.headers["X-Foo"] = "foo" del r.headers["X-Foo"] self.assertNotIn("X-Foo", r.headers) # del doesn't raise a KeyError on nonexistent headers. del r.headers["X-Foo"] def test_instantiate_with_headers(self): r = HttpResponse("hello", headers={"X-Foo": "foo"}) self.assertEqual(r.headers["X-Foo"], "foo") self.assertEqual(r.headers["x-foo"], "foo") def test_content_type(self): r = HttpResponse("hello", content_type="application/json") self.assertEqual(r.headers["Content-Type"], "application/json") def test_content_type_headers(self): r = HttpResponse("hello", headers={"Content-Type": "application/json"}) self.assertEqual(r.headers["Content-Type"], "application/json") def test_content_type_mutually_exclusive(self): msg = ( "'headers' must not contain 'Content-Type' when the " "'content_type' parameter is provided." ) with self.assertRaisesMessage(ValueError, msg): HttpResponse( "hello", content_type="application/json", headers={"Content-Type": "text/csv"}, ) def test_text_updates_when_content_updates(self): response = HttpResponse("Hello, world!") self.assertEqual(response.text, "Hello, world!") response.content = "Updated content" self.assertEqual(response.text, "Updated content") def test_text_charset(self): for content_type, content in [ (None, b"Ol\xc3\xa1 Mundo"), ("text/plain; charset=utf-8", b"Ol\xc3\xa1 Mundo"), ("text/plain; charset=iso-8859-1", b"Ol\xe1 Mundo"), ]: with self.subTest(content_type=content_type): response = HttpResponse(content, content_type=content_type) self.assertEqual(response.text, "Olá Mundo") class HttpResponseSubclassesTests(SimpleTestCase): def test_redirect(self): response = HttpResponseRedirect("/redirected/") self.assertEqual(response.status_code, 302) # Standard HttpResponse init args can be used response = HttpResponseRedirect( "/redirected/", content="The resource has temporarily moved", ) self.assertContains( response, "The resource has temporarily moved", status_code=302 ) self.assertEqual(response.url, response.headers["Location"]) def test_redirect_lazy(self): """Make sure HttpResponseRedirect works with lazy strings.""" r = HttpResponseRedirect(lazystr("/redirected/")) self.assertEqual(r.url, "/redirected/") def test_redirect_modifiers(self): cases = [ (HttpResponseRedirect, "Moved temporarily", False, 302), (HttpResponseRedirect, "Moved temporarily preserve method", True, 307), (HttpResponsePermanentRedirect, "Moved permanently", False, 301), ( HttpResponsePermanentRedirect, "Moved permanently preserve method", True, 308, ), ] for response_class, content, preserve_request, expected_status_code in cases: with self.subTest(status_code=expected_status_code): response = response_class( "/redirected/", content=content, preserve_request=preserve_request ) self.assertEqual(response.status_code, expected_status_code) self.assertEqual(response.content.decode(), content) self.assertEqual(response.url, response.headers["Location"]) def test_redirect_repr(self): response = HttpResponseRedirect("/redirected/") expected = ( '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", ' 'url="/redirected/">' ) self.assertEqual(repr(response), expected) def test_invalid_redirect_repr(self): """ If HttpResponseRedirect raises DisallowedRedirect, its __repr__() should work (in the debug view, for example). """ response = HttpResponseRedirect.__new__(HttpResponseRedirect) with self.assertRaisesMessage( DisallowedRedirect, "Unsafe redirect to URL with protocol 'ssh'" ): HttpResponseRedirect.__init__(response, "ssh://foo") expected = ( '<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", ' 'url="ssh://foo">' ) self.assertEqual(repr(response), expected) def test_not_modified(self): response = HttpResponseNotModified() self.assertEqual(response.status_code, 304) # 304 responses should not have content/content-type with self.assertRaises(AttributeError): response.content = "Hello dear" self.assertNotIn("content-type", response) def test_not_modified_repr(self): response = HttpResponseNotModified() self.assertEqual(repr(response), "<HttpResponseNotModified status_code=304>") def test_not_allowed(self): response = HttpResponseNotAllowed(["GET"]) self.assertEqual(response.status_code, 405) # Standard HttpResponse init args can be used response = HttpResponseNotAllowed( ["GET"], content="Only the GET method is allowed" ) self.assertContains(response, "Only the GET method is allowed", status_code=405) def test_not_allowed_repr(self): response = HttpResponseNotAllowed(["GET", "OPTIONS"], content_type="text/plain") expected = ( '<HttpResponseNotAllowed [GET, OPTIONS] status_code=405, "text/plain">' ) self.assertEqual(repr(response), expected) def test_not_allowed_repr_no_content_type(self): response = HttpResponseNotAllowed(("GET", "POST")) del response.headers["Content-Type"] self.assertEqual( repr(response), "<HttpResponseNotAllowed [GET, POST] status_code=405>" ) class JsonResponseTests(SimpleTestCase): def test_json_response_non_ascii(self): data = {"key": "łóżko"} response = JsonResponse(data) self.assertEqual(json.loads(response.text), data) def test_json_response_raises_type_error_with_default_setting(self): with self.assertRaisesMessage( TypeError, "In order to allow non-dict objects to be serialized set the " "safe parameter to False", ): JsonResponse([1, 2, 3]) def test_json_response_text(self): response = JsonResponse("foobar", safe=False) self.assertEqual(json.loads(response.text), "foobar") def test_json_response_list(self): response = JsonResponse(["foo", "bar"], safe=False) self.assertEqual(json.loads(response.text), ["foo", "bar"]) def test_json_response_uuid(self): u = uuid.uuid4() response = JsonResponse(u, safe=False) self.assertEqual(json.loads(response.text), str(u)) def test_json_response_custom_encoder(self): class CustomDjangoJSONEncoder(DjangoJSONEncoder): def encode(self, o): return json.dumps({"foo": "bar"}) response = JsonResponse({}, encoder=CustomDjangoJSONEncoder) self.assertEqual(json.loads(response.text), {"foo": "bar"}) def test_json_response_passing_arguments_to_json_dumps(self): response = JsonResponse({"foo": "bar"}, json_dumps_params={"indent": 2}) self.assertEqual(response.text, '{\n "foo": "bar"\n}') class StreamingHttpResponseTests(SimpleTestCase): def test_streaming_response(self): r = StreamingHttpResponse(iter(["hello", "world"])) # iterating over the response itself yields bytestring chunks. chunks = list(r) self.assertEqual(chunks, [b"hello", b"world"]) for chunk in chunks: self.assertIsInstance(chunk, bytes) # and the response can only be iterated once. self.assertEqual(list(r), []) # even when a sequence that can be iterated many times, like a list, # is given as content. r = StreamingHttpResponse(["abc", "def"]) self.assertEqual(list(r), [b"abc", b"def"]) self.assertEqual(list(r), []) # iterating over strings still yields bytestring chunks. r.streaming_content = iter(["hello", "café"]) chunks = list(r) # '\xc3\xa9' == unichr(233).encode() self.assertEqual(chunks, [b"hello", b"caf\xc3\xa9"]) for chunk in chunks: self.assertIsInstance(chunk, bytes) # streaming responses don't have a `content` attribute. self.assertFalse(hasattr(r, "content")) # and you can't accidentally assign to a `content` attribute. with self.assertRaises(AttributeError): r.content = "xyz" # but they do have a `streaming_content` attribute. self.assertTrue(hasattr(r, "streaming_content")) # that exists so we can check if a response is streaming, and wrap or # replace the content iterator. r.streaming_content = iter(["abc", "def"]) r.streaming_content = (chunk.upper() for chunk in r.streaming_content) self.assertEqual(list(r), [b"ABC", b"DEF"]) # coercing a streaming response to bytes doesn't return a complete HTTP # message like a regular response does. it only gives us the headers. r = StreamingHttpResponse(iter(["hello", "world"])) self.assertEqual(bytes(r), b"Content-Type: text/html; charset=utf-8") # and this won't consume its content. self.assertEqual(list(r), [b"hello", b"world"]) # additional content cannot be written to the response. r = StreamingHttpResponse(iter(["hello", "world"])) with self.assertRaises(Exception): r.write("!") # and we can't tell the current position. with self.assertRaises(Exception): r.tell() r = StreamingHttpResponse(iter(["hello", "world"])) self.assertEqual(r.getvalue(), b"helloworld") def test_repr(self): r = StreamingHttpResponse(iter(["hello", "café"])) self.assertEqual( repr(r), '<StreamingHttpResponse status_code=200, "text/html; charset=utf-8">', ) async def test_async_streaming_response(self): async def async_iter(): yield b"hello" yield b"world" r = StreamingHttpResponse(async_iter()) chunks = [] async for chunk in r: chunks.append(chunk) self.assertEqual(chunks, [b"hello", b"world"]) def test_async_streaming_response_warning(self): async def async_iter(): yield b"hello" yield b"world" r = StreamingHttpResponse(async_iter()) msg = ( "StreamingHttpResponse must consume asynchronous iterators in order to " "serve them synchronously. Use a synchronous iterator instead." ) with self.assertWarnsMessage(Warning, msg): self.assertEqual(list(r), [b"hello", b"world"]) async def test_sync_streaming_response_warning(self): r = StreamingHttpResponse(iter(["hello", "world"])) msg = ( "StreamingHttpResponse must consume synchronous iterators in order to " "serve them asynchronously. Use an asynchronous iterator instead." ) with self.assertWarnsMessage(Warning, msg): self.assertEqual(b"hello", await anext(aiter(r))) def test_text_attribute_error(self): r = StreamingHttpResponse(iter(["hello", "world"])) msg = "This %s instance has no `text` attribute." % r.__class__.__name__ with self.assertRaisesMessage(AttributeError, msg): r.text class FileCloseTests(SimpleTestCase): def setUp(self): # Disable the request_finished signal during this test # to avoid interfering with the database connection. request_finished.disconnect(close_old_connections) self.addCleanup(request_finished.connect, close_old_connections) def test_response(self): filename = os.path.join(os.path.dirname(__file__), "abc.txt") # file isn't closed until we close the response. file1 = open(filename) r = HttpResponse(file1) self.assertTrue(file1.closed) r.close() # when multiple file are assigned as content, make sure they are all # closed with the response. file1 = open(filename) file2 = open(filename) r = HttpResponse(file1) r.content = file2 self.assertTrue(file1.closed) self.assertTrue(file2.closed) def test_streaming_response(self): filename = os.path.join(os.path.dirname(__file__), "abc.txt") # file isn't closed until we close the response. file1 = open(filename) r = StreamingHttpResponse(file1) self.assertFalse(file1.closed) r.close() self.assertTrue(file1.closed) # when multiple file are assigned as content, make sure they are all # closed with the response. file1 = open(filename) file2 = open(filename) r = StreamingHttpResponse(file1) r.streaming_content = file2 self.assertFalse(file1.closed) self.assertFalse(file2.closed) r.close()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/null_queries/models.py
tests/null_queries/models.py
from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) class Choice(models.Model): poll = models.ForeignKey(Poll, models.CASCADE) choice = models.CharField(max_length=200) # A set of models with an inner one pointing to two outer ones. class OuterA(models.Model): pass class OuterB(models.Model): data = models.CharField(max_length=10) class Inner(models.Model): first = models.ForeignKey(OuterA, models.CASCADE) # second would clash with the __second lookup. third = models.ForeignKey(OuterB, models.SET_NULL, null=True)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/null_queries/__init__.py
tests/null_queries/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/null_queries/tests.py
tests/null_queries/tests.py
from django.core.exceptions import FieldError from django.test import TestCase from .models import Choice, Inner, OuterA, OuterB, Poll class NullQueriesTests(TestCase): def test_none_as_null(self): """ Regression test for the use of None as a query value. None is interpreted as an SQL NULL, but only in __exact and __iexact queries. Set up some initial polls and choices """ p1 = Poll(question="Why?") p1.save() c1 = Choice(poll=p1, choice="Because.") c1.save() c2 = Choice(poll=p1, choice="Why Not?") c2.save() # Exact query with value None returns nothing ("is NULL" in sql, # but every 'id' field has a value). self.assertSequenceEqual(Choice.objects.filter(choice__exact=None), []) # The same behavior for iexact query. self.assertSequenceEqual(Choice.objects.filter(choice__iexact=None), []) # Excluding the previous result returns everything. self.assertSequenceEqual( Choice.objects.exclude(choice=None).order_by("id"), [c1, c2] ) # Valid query, but fails because foo isn't a keyword msg = ( "Cannot resolve keyword 'foo' into field. Choices are: choice, id, poll, " "poll_id" ) with self.assertRaisesMessage(FieldError, msg): Choice.objects.filter(foo__exact=None) # Can't use None on anything other than __exact and __iexact with self.assertRaisesMessage(ValueError, "Cannot use None as a query value"): Choice.objects.filter(id__gt=None) def test_unsaved(self): poll = Poll(question="How?") msg = ( "'Poll' instance needs to have a primary key value before this " "relationship can be used." ) with self.assertRaisesMessage(ValueError, msg): poll.choice_set.all() def test_reverse_relations(self): """ Querying across reverse relations and then another relation should insert outer joins correctly so as not to exclude results. """ obj = OuterA.objects.create() self.assertSequenceEqual(OuterA.objects.filter(inner__third=None), [obj]) self.assertSequenceEqual(OuterA.objects.filter(inner__third__data=None), [obj]) inner = Inner.objects.create(first=obj) self.assertSequenceEqual( Inner.objects.filter(first__inner__third=None), [inner] ) # Ticket #13815: check if <reverse>_isnull=False does not produce # faulty empty lists outerb = OuterB.objects.create(data="reverse") self.assertSequenceEqual(OuterB.objects.filter(inner__isnull=False), []) Inner.objects.create(first=obj) self.assertSequenceEqual(OuterB.objects.exclude(inner__isnull=False), [outerb])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_adminsite.py
tests/admin_views/test_adminsite.py
from django.contrib import admin from django.contrib.admin.actions import delete_selected from django.contrib.auth.models import User from django.test import SimpleTestCase, TestCase, override_settings from django.test.client import RequestFactory from django.urls import path, reverse from .models import Article site = admin.AdminSite(name="test_adminsite") site.register(User) site.register(Article) class CustomAdminSite(admin.AdminSite): site_title = "Custom title" site_header = "Custom site" custom_site = CustomAdminSite(name="test_custom_adminsite") custom_site.register(User) urlpatterns = [ path("test_admin/admin/", site.urls), path("test_custom_admin/admin/", custom_site.urls), ] @override_settings(ROOT_URLCONF="admin_views.test_adminsite") class SiteEachContextTest(TestCase): """ Check each_context contains the documented variables and that available_apps context variable structure is the expected one. """ request_factory = RequestFactory() @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) def setUp(self): request = self.request_factory.get(reverse("test_adminsite:index")) request.user = self.u1 self.ctx = site.each_context(request) def test_each_context(self): ctx = self.ctx self.assertEqual(ctx["site_header"], "Django administration") self.assertEqual(ctx["site_title"], "Django site admin") self.assertEqual(ctx["site_url"], "/") self.assertIs(ctx["has_permission"], True) def test_custom_admin_titles(self): request = self.request_factory.get(reverse("test_custom_adminsite:index")) request.user = self.u1 ctx = custom_site.each_context(request) self.assertEqual(ctx["site_title"], "Custom title") self.assertEqual(ctx["site_header"], "Custom site") def test_each_context_site_url_with_script_name(self): request = self.request_factory.get( reverse("test_adminsite:index"), SCRIPT_NAME="/my-script-name/" ) request.user = self.u1 self.assertEqual(site.each_context(request)["site_url"], "/my-script-name/") def test_available_apps(self): ctx = self.ctx apps = ctx["available_apps"] # we have registered two models from two different apps self.assertEqual(len(apps), 2) # admin_views.Article admin_views = apps[0] self.assertEqual(admin_views["app_label"], "admin_views") self.assertEqual(len(admin_views["models"]), 1) article = admin_views["models"][0] self.assertEqual(article["object_name"], "Article") self.assertEqual(article["model"], Article) # auth.User auth = apps[1] self.assertEqual(auth["app_label"], "auth") self.assertEqual(len(auth["models"]), 1) user = auth["models"][0] self.assertEqual(user["object_name"], "User") self.assertEqual(user["model"], User) self.assertEqual(auth["app_url"], "/test_admin/admin/auth/") self.assertIs(auth["has_module_perms"], True) self.assertIn("perms", user) self.assertIs(user["perms"]["add"], True) self.assertIs(user["perms"]["change"], True) self.assertIs(user["perms"]["delete"], True) self.assertEqual(user["admin_url"], "/test_admin/admin/auth/user/") self.assertEqual(user["add_url"], "/test_admin/admin/auth/user/add/") self.assertEqual(user["name"], "Users") class SiteActionsTests(SimpleTestCase): def setUp(self): self.site = admin.AdminSite() def test_add_action(self): def test_action(): pass self.site.add_action(test_action) self.assertEqual(self.site.get_action("test_action"), test_action) def test_disable_action(self): action_name = "delete_selected" self.assertEqual(self.site._actions[action_name], delete_selected) self.site.disable_action(action_name) with self.assertRaises(KeyError): self.site._actions[action_name] def test_get_action(self): """AdminSite.get_action() returns an action even if it's disabled.""" action_name = "delete_selected" self.assertEqual(self.site.get_action(action_name), delete_selected) self.site.disable_action(action_name) self.assertEqual(self.site.get_action(action_name), delete_selected)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/custom_has_permission_admin.py
tests/admin_views/custom_has_permission_admin.py
""" A custom AdminSite for AdminViewPermissionsTest.test_login_has_permission(). """ from django.contrib import admin from django.contrib.auth import get_permission_codename from django.contrib.auth.forms import AuthenticationForm from django.core.exceptions import ValidationError from . import admin as base_admin from . import models PERMISSION_NAME = "admin_views.%s" % get_permission_codename( "change", models.Article._meta ) class PermissionAdminAuthenticationForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active or not (user.is_staff or user.has_perm(PERMISSION_NAME)): raise ValidationError("permission denied") class HasPermissionAdmin(admin.AdminSite): login_form = PermissionAdminAuthenticationForm def has_permission(self, request): return request.user.is_active and ( request.user.is_staff or request.user.has_perm(PERMISSION_NAME) ) site = HasPermissionAdmin(name="has_permission_admin") site.register(models.Article, base_admin.ArticleAdmin)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_actions.py
tests/admin_views/test_actions.py
import json from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.views.main import IS_POPUP_VAR from django.contrib.auth.models import Permission, User from django.core import mail from django.db import connection from django.template.loader import render_to_string from django.template.response import TemplateResponse from django.test import TestCase, override_settings from django.test.utils import CaptureQueriesContext from django.urls import reverse from .admin import SubscriberAdmin from .forms import MediaActionForm from .models import ( Actor, Answer, Book, ExternalSubscriber, Question, Subscriber, UnchangeableObject, ) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminActionsTest(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) cls.s1 = ExternalSubscriber.objects.create( name="John Doe", email="john@example.org" ) cls.s2 = Subscriber.objects.create( name="Max Mustermann", email="max@example.org" ) def setUp(self): self.client.force_login(self.superuser) def test_model_admin_custom_action(self): """A custom action defined in a ModelAdmin method.""" action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "mail_admin", "index": 0, } self.client.post( reverse("admin:admin_views_subscriber_changelist"), action_data ) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Greetings from a ModelAdmin action") def test_model_admin_default_delete_action(self): action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk, self.s2.pk], "action": "delete_selected", "index": 0, } delete_confirmation_data = { ACTION_CHECKBOX_NAME: [self.s1.pk, self.s2.pk], "action": "delete_selected", "post": "yes", } confirmation = self.client.post( reverse("admin:admin_views_subscriber_changelist"), action_data ) self.assertIsInstance(confirmation, TemplateResponse) self.assertContains( confirmation, "Are you sure you want to delete the selected subscribers?" ) self.assertContains(confirmation, "<h1>Delete multiple objects</h1>") self.assertContains(confirmation, "<h2>Summary</h2>") self.assertContains(confirmation, "<li>Subscribers: 2</li>") self.assertContains(confirmation, "<li>External subscribers: 1</li>") self.assertContains(confirmation, ACTION_CHECKBOX_NAME, count=2) with CaptureQueriesContext(connection) as ctx: self.client.post( reverse("admin:admin_views_subscriber_changelist"), delete_confirmation_data, ) # Log entries are inserted in bulk. self.assertEqual( len( [ q["sql"] for q in ctx.captured_queries if q["sql"].startswith("INSERT") ] ), 1, ) self.assertEqual(Subscriber.objects.count(), 0) def test_default_delete_action_nonexistent_pk(self): self.assertFalse(Subscriber.objects.filter(id=9998).exists()) action_data = { ACTION_CHECKBOX_NAME: ["9998"], "action": "delete_selected", "index": 0, } response = self.client.post( reverse("admin:admin_views_subscriber_changelist"), action_data ) self.assertContains( response, "Are you sure you want to delete the selected subscribers?" ) self.assertContains(response, "<ul></ul>", html=True) @override_settings(USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=3) def test_non_localized_pk(self): """ If USE_THOUSAND_SEPARATOR is set, the ids for the objects selected for deletion are rendered without separators. """ s = ExternalSubscriber.objects.create(id=9999) action_data = { ACTION_CHECKBOX_NAME: [s.pk, self.s2.pk], "action": "delete_selected", "index": 0, } response = self.client.post( reverse("admin:admin_views_subscriber_changelist"), action_data ) self.assertTemplateUsed(response, "admin/delete_selected_confirmation.html") self.assertContains(response, 'value="9999"') # Instead of 9,999 self.assertContains(response, 'value="%s"' % self.s2.pk) def test_model_admin_default_delete_action_protected(self): """ The default delete action where some related objects are protected from deletion. """ q1 = Question.objects.create(question="Why?") a1 = Answer.objects.create(question=q1, answer="Because.") a2 = Answer.objects.create(question=q1, answer="Yes.") q2 = Question.objects.create(question="Wherefore?") action_data = { ACTION_CHECKBOX_NAME: [q1.pk, q2.pk], "action": "delete_selected", "index": 0, } delete_confirmation_data = action_data.copy() delete_confirmation_data["post"] = "yes" response = self.client.post( reverse("admin:admin_views_question_changelist"), action_data ) self.assertContains( response, "would require deleting the following protected related objects" ) self.assertContains( response, '<li>Answer: <a href="%s">Because.</a></li>' % reverse("admin:admin_views_answer_change", args=(a1.pk,)), html=True, ) self.assertContains( response, '<li>Answer: <a href="%s">Yes.</a></li>' % reverse("admin:admin_views_answer_change", args=(a2.pk,)), html=True, ) # A POST request to delete protected objects displays the page which # says the deletion is prohibited. response = self.client.post( reverse("admin:admin_views_question_changelist"), delete_confirmation_data ) self.assertContains( response, "would require deleting the following protected related objects" ) self.assertEqual(Question.objects.count(), 2) def test_model_admin_default_delete_action_no_change_url(self): """ The default delete action doesn't break if a ModelAdmin removes the change_view URL (#20640). """ obj = UnchangeableObject.objects.create() action_data = { ACTION_CHECKBOX_NAME: obj.pk, "action": "delete_selected", "index": "0", } response = self.client.post( reverse("admin:admin_views_unchangeableobject_changelist"), action_data ) # No 500 caused by NoReverseMatch. The page doesn't display a link to # the nonexistent change page. self.assertContains( response, "<li>Unchangeable object: %s</li>" % obj, 1, html=True ) def test_delete_queryset_hook(self): delete_confirmation_data = { ACTION_CHECKBOX_NAME: [self.s1.pk, self.s2.pk], "action": "delete_selected", "post": "yes", "index": 0, } SubscriberAdmin.overridden = False self.client.post( reverse("admin:admin_views_subscriber_changelist"), delete_confirmation_data ) # SubscriberAdmin.delete_queryset() sets overridden to True. self.assertIs(SubscriberAdmin.overridden, True) self.assertEqual(Subscriber.objects.count(), 0) def test_delete_selected_uses_get_deleted_objects(self): """The delete_selected action uses ModelAdmin.get_deleted_objects().""" book = Book.objects.create(name="Test Book") data = { ACTION_CHECKBOX_NAME: [book.pk], "action": "delete_selected", "index": 0, } response = self.client.post(reverse("admin2:admin_views_book_changelist"), data) # BookAdmin.get_deleted_objects() returns custom text. self.assertContains(response, "a deletable object") def test_custom_function_mail_action(self): """A custom action may be defined in a function.""" action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "external_mail", "index": 0, } self.client.post( reverse("admin:admin_views_externalsubscriber_changelist"), action_data ) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Greetings from a function action") def test_custom_function_action_with_redirect(self): """Another custom action defined in a function.""" action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "redirect_to", "index": 0, } response = self.client.post( reverse("admin:admin_views_externalsubscriber_changelist"), action_data ) self.assertEqual(response.status_code, 302) def test_default_redirect(self): """ Actions which don't return an HttpResponse are redirected to the same page, retaining the querystring (which may contain changelist info). """ action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "external_mail", "index": 0, } url = reverse("admin:admin_views_externalsubscriber_changelist") + "?o=1" response = self.client.post(url, action_data) self.assertRedirects(response, url) def test_custom_function_action_streaming_response(self): """A custom action may return a StreamingHttpResponse.""" action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "download", "index": 0, } response = self.client.post( reverse("admin:admin_views_externalsubscriber_changelist"), action_data ) content = b"".join(list(response)) self.assertEqual(content, b"This is the content of the file") self.assertEqual(response.status_code, 200) def test_custom_function_action_no_perm_response(self): """A custom action may returns an HttpResponse with a 403 code.""" action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "no_perm", "index": 0, } response = self.client.post( reverse("admin:admin_views_externalsubscriber_changelist"), action_data ) self.assertEqual(response.status_code, 403) self.assertEqual(response.content, b"No permission to perform this action") def test_actions_ordering(self): """Actions are ordered as expected.""" response = self.client.get( reverse("admin:admin_views_externalsubscriber_changelist") ) self.assertContains( response, """<label>Action: <select name="action" required> <option value="" selected>---------</option> <option value="delete_selected">Delete selected external subscribers</option> <option value="redirect_to">Redirect to (Awesome action)</option> <option value="external_mail">External mail (Another awesome action)</option> <option value="download">Download subscription</option> <option value="no_perm">No permission to run</option> </select>""", html=True, ) def test_model_without_action(self): """A ModelAdmin might not have any actions.""" response = self.client.get( reverse("admin:admin_views_oldsubscriber_changelist") ) self.assertIsNone(response.context["action_form"]) self.assertNotContains( response, '<input type="checkbox" class="action-select"', msg_prefix="Found an unexpected action toggle checkboxbox in response", ) self.assertNotContains(response, '<input type="checkbox" class="action-select"') def test_model_without_action_still_has_jquery(self): """ A ModelAdmin without any actions still has jQuery included on the page. """ response = self.client.get( reverse("admin:admin_views_oldsubscriber_changelist") ) self.assertIsNone(response.context["action_form"]) self.assertContains( response, "jquery.min.js", msg_prefix=( "jQuery missing from admin pages for model with no admin actions" ), ) def test_action_column_class(self): """The checkbox column class is present in the response.""" response = self.client.get(reverse("admin:admin_views_subscriber_changelist")) self.assertIsNotNone(response.context["action_form"]) self.assertContains(response, "action-checkbox-column") def test_multiple_actions_form(self): """ Actions come from the form whose submit button was pressed (#10618). """ action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], # Two different actions selected on the two forms... "action": ["external_mail", "delete_selected"], # ...but "go" was clicked on the top form. "index": 0, } self.client.post( reverse("admin:admin_views_externalsubscriber_changelist"), action_data ) # The action sends mail rather than deletes. self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Greetings from a function action") def test_media_from_actions_form(self): """ The action form's media is included in the changelist view's media. """ response = self.client.get(reverse("admin:admin_views_subscriber_changelist")) media_path = MediaActionForm.Media.js[0] self.assertIsInstance(response.context["action_form"], MediaActionForm) self.assertIn("media", response.context) self.assertIn(media_path, response.context["media"]._js) self.assertContains(response, media_path) def test_user_message_on_none_selected(self): """ User sees a warning when 'Go' is pressed and no items are selected. """ action_data = { ACTION_CHECKBOX_NAME: [], "action": "delete_selected", "index": 0, } url = reverse("admin:admin_views_subscriber_changelist") response = self.client.post(url, action_data) self.assertRedirects(response, url, fetch_redirect_response=False) response = self.client.get(response.url) msg = ( "Items must be selected in order to perform actions on them. No items have " "been changed." ) self.assertContains(response, msg) self.assertEqual(Subscriber.objects.count(), 2) def test_user_message_on_no_action(self): """ User sees a warning when 'Go' is pressed and no action is selected. """ action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk, self.s2.pk], "action": "", "index": 0, } url = reverse("admin:admin_views_subscriber_changelist") response = self.client.post(url, action_data) self.assertRedirects(response, url, fetch_redirect_response=False) response = self.client.get(response.url) self.assertContains(response, "No action selected.") self.assertEqual(Subscriber.objects.count(), 2) def test_selection_counter(self): """The selection counter is there.""" response = self.client.get(reverse("admin:admin_views_subscriber_changelist")) self.assertContains(response, "0 of 2 selected") def test_popup_actions(self): """Actions aren't shown in popups.""" changelist_url = reverse("admin:admin_views_subscriber_changelist") response = self.client.get(changelist_url) self.assertIsNotNone(response.context["action_form"]) response = self.client.get(changelist_url + "?%s" % IS_POPUP_VAR) self.assertIsNone(response.context["action_form"]) def test_popup_template_response_on_add(self): """ Success on popups shall be rendered from template in order to allow easy customization. """ response = self.client.post( reverse("admin:admin_views_actor_add") + "?%s=1" % IS_POPUP_VAR, {"name": "Troy McClure", "age": "55", IS_POPUP_VAR: "1"}, ) self.assertEqual(response.status_code, 200) self.assertEqual( response.template_name, [ "admin/admin_views/actor/popup_response.html", "admin/admin_views/popup_response.html", "admin/popup_response.html", ], ) self.assertTemplateUsed(response, "admin/popup_response.html") def test_popup_template_response_on_change(self): instance = Actor.objects.create(name="David Tennant", age=45) response = self.client.post( reverse("admin:admin_views_actor_change", args=(instance.pk,)) + "?%s=1" % IS_POPUP_VAR, {"name": "David Tennant", "age": "46", IS_POPUP_VAR: "1"}, ) self.assertEqual(response.status_code, 200) self.assertEqual( response.template_name, [ "admin/admin_views/actor/popup_response.html", "admin/admin_views/popup_response.html", "admin/popup_response.html", ], ) self.assertTemplateUsed(response, "admin/popup_response.html") def test_popup_template_response_on_delete(self): instance = Actor.objects.create(name="David Tennant", age=45) response = self.client.post( reverse("admin:admin_views_actor_delete", args=(instance.pk,)) + "?%s=1" % IS_POPUP_VAR, {IS_POPUP_VAR: "1"}, ) self.assertEqual(response.status_code, 200) self.assertEqual( response.template_name, [ "admin/admin_views/actor/popup_response.html", "admin/admin_views/popup_response.html", "admin/popup_response.html", ], ) self.assertTemplateUsed(response, "admin/popup_response.html") def test_popup_template_escaping(self): popup_response_data = json.dumps( { "new_value": "new_value\\", "obj": "obj\\", "value": "value\\", } ) context = { "popup_response_data": popup_response_data, } output = render_to_string("admin/popup_response.html", context) self.assertIn(r"&quot;value\\&quot;", output) self.assertIn(r"&quot;new_value\\&quot;", output) self.assertIn(r"&quot;obj\\&quot;", output) @override_settings(ROOT_URLCONF="admin_views.urls") class AdminActionsPermissionTests(TestCase): @classmethod def setUpTestData(cls): cls.s1 = ExternalSubscriber.objects.create( name="John Doe", email="john@example.org" ) cls.s2 = Subscriber.objects.create( name="Max Mustermann", email="max@example.org" ) cls.user = User.objects.create_user( username="user", password="secret", email="user@example.com", is_staff=True, ) permission = Permission.objects.get(codename="change_subscriber") cls.user.user_permissions.add(permission) def setUp(self): self.client.force_login(self.user) def test_model_admin_no_delete_permission(self): """ Permission is denied if the user doesn't have delete permission for the model (Subscriber). """ action_data = { ACTION_CHECKBOX_NAME: [self.s1.pk], "action": "delete_selected", } url = reverse("admin:admin_views_subscriber_changelist") response = self.client.post(url, action_data) self.assertRedirects(response, url, fetch_redirect_response=False) response = self.client.get(response.url) self.assertContains(response, "No action selected.") def test_model_admin_no_delete_permission_externalsubscriber(self): """ Permission is denied if the user doesn't have delete permission for a related model (ExternalSubscriber). """ permission = Permission.objects.get(codename="delete_subscriber") self.user.user_permissions.add(permission) delete_confirmation_data = { ACTION_CHECKBOX_NAME: [self.s1.pk, self.s2.pk], "action": "delete_selected", "post": "yes", } response = self.client.post( reverse("admin:admin_views_subscriber_changelist"), delete_confirmation_data ) self.assertEqual(response.status_code, 403)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_related_object_lookups.py
tests/admin_views/test_related_object_lookups.py
from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import User from django.test import override_settings from django.urls import reverse from .models import CamelCaseModel @override_settings(ROOT_URLCONF="admin_views.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) def test_related_object_link_images_attributes(self): from selenium.webdriver.common.by import By album_add_url = reverse("admin:admin_views_album_add") self.selenium.get(self.live_server_url + album_add_url) tests = [ "add_id_owner", "change_id_owner", "delete_id_owner", "view_id_owner", ] for link_id in tests: with self.subTest(link_id): link_image = self.selenium.find_element( By.XPATH, f'//*[@id="{link_id}"]/img' ) self.assertEqual(link_image.get_attribute("alt"), "") self.assertEqual(link_image.get_attribute("width"), "24") self.assertEqual(link_image.get_attribute("height"), "24") def test_related_object_lookup_link_initial_state(self): from selenium.webdriver.common.by import By album_add_url = reverse("admin:admin_views_album_add") self.selenium.get(self.live_server_url + album_add_url) tests = [ "change_id_owner", "delete_id_owner", "view_id_owner", ] for link_id in tests: with self.subTest(link_id): link = self.selenium.find_element(By.XPATH, f'//*[@id="{link_id}"]') self.assertEqual(link.get_attribute("aria-disabled"), "true") def test_related_object_lookup_link_enabled(self): from selenium.webdriver.common.by import By from selenium.webdriver.support.select import Select album_add_url = reverse("admin:admin_views_album_add") self.selenium.get(self.live_server_url + album_add_url) select_element = self.selenium.find_element(By.XPATH, '//*[@id="id_owner"]') option = Select(select_element).options[-1] self.assertEqual(option.text, "super") select_element.click() option.click() tests = [ "add_id_owner", "change_id_owner", "delete_id_owner", "view_id_owner", ] for link_id in tests: with self.subTest(link_id): link = self.selenium.find_element(By.XPATH, f'//*[@id="{link_id}"]') self.assertIsNone(link.get_attribute("aria-disabled")) def test_related_object_update_with_camel_casing(self): from selenium.webdriver.common.by import By add_url = reverse("admin:admin_views_camelcaserelatedmodel_add") self.selenium.get(self.live_server_url + add_url) interesting_name = "A test name" # Add a new CamelCaseModel using the "+" icon next to the "fk" field. self.selenium.find_element(By.ID, "add_id_fk").click() # Switch to the add popup window. self.wait_for_and_switch_to_popup() # Find the "interesting_name" field and enter a value, then save it. self.selenium.find_element(By.ID, "id_interesting_name").send_keys( interesting_name ) self.selenium.find_element(By.NAME, "_save").click() # Return to the main window. self.wait_until(lambda d: len(d.window_handles) == 1, 1) self.selenium.switch_to.window(self.selenium.window_handles[0]) id_value = CamelCaseModel.objects.get(interesting_name=interesting_name).id # Check that both the "Available" m2m box and the "Fk" dropdown now # include the newly added CamelCaseModel instance. fk_dropdown = self.selenium.find_element(By.ID, "id_fk") self.assertHTMLEqual( fk_dropdown.get_attribute("innerHTML"), f""" <option value="" selected="">---------</option> <option value="{id_value}" selected>{interesting_name}</option> """, ) # Check the newly added instance is not also added in the "to" box. m2m_to = self.selenium.find_element(By.ID, "id_m2m_to") self.assertHTMLEqual(m2m_to.get_attribute("innerHTML"), "") m2m_box = self.selenium.find_element(By.ID, "id_m2m_from") self.assertHTMLEqual( m2m_box.get_attribute("innerHTML"), f""" <option title="{interesting_name}" value="{id_value}"> {interesting_name}</option> """, ) def test_related_object_add_js_actions(self): from selenium.webdriver.common.by import By add_url = reverse("admin:admin_views_camelcaserelatedmodel_add") self.selenium.get(self.live_server_url + add_url) m2m_to = self.selenium.find_element(By.ID, "id_m2m_to") m2m_box = self.selenium.find_element(By.ID, "id_m2m_from") fk_dropdown = self.selenium.find_element(By.ID, "id_fk") # Add new related entry using +. name = "Bergeron" self.selenium.find_element(By.ID, "add_id_m2m").click() self.wait_for_and_switch_to_popup() self.selenium.find_element(By.ID, "id_interesting_name").send_keys(name) self.selenium.find_element(By.NAME, "_save").click() self.wait_until(lambda d: len(d.window_handles) == 1, 1) self.selenium.switch_to.window(self.selenium.window_handles[0]) id_value = CamelCaseModel.objects.get(interesting_name=name).id # Check the new value correctly appears in the "to" box. self.assertHTMLEqual( m2m_to.get_attribute("innerHTML"), f"""<option title="{name}" value="{id_value}">{name}</option>""", ) self.assertHTMLEqual(m2m_box.get_attribute("innerHTML"), "") self.assertHTMLEqual( fk_dropdown.get_attribute("innerHTML"), f""" <option value="" selected>---------</option> <option value="{id_value}">{name}</option> """, ) # Move the new value to the from box. self.selenium.find_element(By.XPATH, "//*[@id='id_m2m_to']/option").click() self.selenium.find_element(By.XPATH, "//*[@id='id_m2m_remove']").click() self.assertHTMLEqual( m2m_box.get_attribute("innerHTML"), f"""<option title="{name}" value="{id_value}">{name}</option>""", ) self.assertHTMLEqual(m2m_to.get_attribute("innerHTML"), "") # Move the new value to the to box. self.selenium.find_element(By.XPATH, "//*[@id='id_m2m_from']/option").click() self.selenium.find_element(By.XPATH, "//*[@id='id_m2m_add']").click() self.assertHTMLEqual(m2m_box.get_attribute("innerHTML"), "") self.assertHTMLEqual( m2m_to.get_attribute("innerHTML"), f"""<option title="{name}" value="{id_value}">{name}</option>""", )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/views.py
tests/admin_views/views.py
from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse @staff_member_required def secure_view(request): return HttpResponse(str(request.POST)) @staff_member_required(redirect_field_name="myfield") def secure_view2(request): return HttpResponse(str(request.POST))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_nav_sidebar.py
tests/admin_views/test_nav_sidebar.py
from django.contrib import admin from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import User from django.test import TestCase, override_settings from django.urls import path, reverse from .models import Héllo class AdminSiteWithSidebar(admin.AdminSite): pass class AdminSiteWithoutSidebar(admin.AdminSite): enable_nav_sidebar = False site_with_sidebar = AdminSiteWithSidebar(name="test_with_sidebar") site_without_sidebar = AdminSiteWithoutSidebar(name="test_without_sidebar") site_with_sidebar.register(User) site_with_sidebar.register(Héllo) urlpatterns = [ path("test_sidebar/admin/", site_with_sidebar.urls), path("test_wihout_sidebar/admin/", site_without_sidebar.urls), ] @override_settings(ROOT_URLCONF="admin_views.test_nav_sidebar") class AdminSidebarTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) def setUp(self): self.client.force_login(self.superuser) def test_sidebar_not_on_index(self): response = self.client.get(reverse("test_with_sidebar:index")) self.assertContains(response, '<div class="main" id="main">') self.assertNotContains( response, '<nav class="sticky" id="nav-sidebar" aria-label="Sidebar">' ) def test_sidebar_disabled(self): response = self.client.get(reverse("test_without_sidebar:index")) self.assertNotContains( response, '<nav class="sticky" id="nav-sidebar" aria-label="Sidebar">' ) def test_sidebar_unauthenticated(self): self.client.logout() response = self.client.get(reverse("test_with_sidebar:login")) self.assertNotContains( response, '<nav class="sticky" id="nav-sidebar" aria-label="Sidebar">' ) def test_sidebar_aria_current_page(self): url = reverse("test_with_sidebar:auth_user_changelist") response = self.client.get(url) self.assertContains( response, '<nav class="sticky" id="nav-sidebar" aria-label="Sidebar">' ) self.assertContains( response, '<a href="%s" aria-current="page">Users</a>' % url ) @override_settings( 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", ], }, } ] ) def test_sidebar_aria_current_page_missing_without_request_context_processor(self): url = reverse("test_with_sidebar:auth_user_changelist") response = self.client.get(url) self.assertContains( response, '<nav class="sticky" id="nav-sidebar" aria-label="Sidebar">' ) # Does not include aria-current attribute. self.assertContains(response, '<a href="%s">Users</a>' % url) @override_settings(DEBUG=True) def test_included_app_list_template_context_fully_set(self): # All context variables should be set when rendering the sidebar. url = reverse("test_with_sidebar:auth_user_changelist") with self.assertNoLogs("django.template", "DEBUG"): self.client.get(url) def test_sidebar_model_name_non_ascii(self): url = reverse("test_with_sidebar:admin_views_héllo_changelist") response = self.client.get(url) self.assertContains( response, '<div class="app-admin_views module current-app">' ) self.assertContains(response, '<tr class="model-héllo current-model">') self.assertContains( response, '<th scope="row" id="admin_views-héllo">' '<a href="/test_sidebar/admin/admin_views/h%C3%A9llo/" aria-current="page">' "Héllos</a></th>", html=True, ) @override_settings(ROOT_URLCONF="admin_views.test_nav_sidebar") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) self.admin_login( username="super", password="secret", login_url=reverse("test_with_sidebar:index"), ) self.selenium.execute_script( "localStorage.removeItem('django.admin.navSidebarIsOpen')" ) def test_sidebar_starts_open(self): from selenium.webdriver.common.by import By self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) main_element = self.selenium.find_element(By.CSS_SELECTOR, "#main") self.assertIn("shifted", main_element.get_attribute("class").split()) def test_sidebar_can_be_closed(self): from selenium.webdriver.common.by import By self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) self.assertEqual(toggle_button.tag_name, "button") self.assertEqual(toggle_button.get_attribute("aria-label"), "Toggle navigation") nav_sidebar = self.selenium.find_element(By.ID, "nav-sidebar") self.assertEqual(nav_sidebar.get_attribute("aria-expanded"), "true") self.assertTrue(nav_sidebar.is_displayed()) toggle_button.click() # Hidden sidebar is not visible. nav_sidebar = self.selenium.find_element(By.ID, "nav-sidebar") self.assertEqual(nav_sidebar.get_attribute("aria-expanded"), "false") self.assertFalse(nav_sidebar.is_displayed()) main_element = self.selenium.find_element(By.CSS_SELECTOR, "#main") self.assertNotIn("shifted", main_element.get_attribute("class").split()) def test_sidebar_state_persists(self): from selenium.webdriver.common.by import By self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) self.assertIsNone( self.selenium.execute_script( "return localStorage.getItem('django.admin.navSidebarIsOpen')" ) ) toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) toggle_button.click() self.assertEqual( self.selenium.execute_script( "return localStorage.getItem('django.admin.navSidebarIsOpen')" ), "false", ) self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) main_element = self.selenium.find_element(By.CSS_SELECTOR, "#main") self.assertNotIn("shifted", main_element.get_attribute("class").split()) toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) # Hidden sidebar is not visible. nav_sidebar = self.selenium.find_element(By.ID, "nav-sidebar") self.assertEqual(nav_sidebar.get_attribute("aria-expanded"), "false") self.assertFalse(nav_sidebar.is_displayed()) toggle_button.click() nav_sidebar = self.selenium.find_element(By.ID, "nav-sidebar") self.assertEqual(nav_sidebar.get_attribute("aria-expanded"), "true") self.assertTrue(nav_sidebar.is_displayed()) self.assertEqual( self.selenium.execute_script( "return localStorage.getItem('django.admin.navSidebarIsOpen')" ), "true", ) self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) main_element = self.selenium.find_element(By.CSS_SELECTOR, "#main") self.assertIn("shifted", main_element.get_attribute("class").split()) def test_sidebar_filter_persists(self): from selenium.webdriver.common.by import By self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) filter_value_script = ( "return sessionStorage.getItem('django.admin.navSidebarFilterValue')" ) self.assertIsNone(self.selenium.execute_script(filter_value_script)) filter_input = self.selenium.find_element(By.CSS_SELECTOR, "#nav-filter") filter_input.send_keys("users") self.assertEqual(self.selenium.execute_script(filter_value_script), "users")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/admin.py
tests/admin_views/admin.py
import datetime from io import StringIO from wsgiref.util import FileWrapper from django import forms from django.contrib import admin from django.contrib.admin import BooleanFieldListFilter from django.contrib.admin.views.main import ChangeList from django.contrib.auth.admin import GroupAdmin, UserAdmin from django.contrib.auth.models import Group, User from django.core.exceptions import ValidationError from django.core.mail import EmailMessage from django.db import models from django.forms.models import BaseModelFormSet from django.http import HttpResponse, JsonResponse, StreamingHttpResponse from django.urls import path from django.utils.html import format_html from django.utils.safestring import mark_safe from django.views.decorators.common import no_append_slash from .forms import MediaActionForm from .models import ( Actor, AdminOrderedAdminMethod, AdminOrderedCallable, AdminOrderedField, AdminOrderedModelMethod, Album, Answer, Answer2, Article, BarAccount, Book, Bookmark, Box, CamelCaseModel, CamelCaseRelatedModel, Category, Chapter, ChapterXtra1, Child, ChildOfReferer, Choice, City, Collector, Color, Color2, ComplexSortedPerson, Country, Course, CoverLetter, CustomArticle, CyclicOne, CyclicTwo, DependentChild, DooHickey, EmptyModel, EmptyModelHidden, EmptyModelMixin, EmptyModelVisible, ExplicitlyProvidedPK, ExternalSubscriber, Fabric, FancyDoodad, FieldOverridePost, FilteredManager, FooAccount, FoodDelivery, FunkyTag, Gadget, Gallery, GenRelReference, Grommet, ImplicitlyGeneratedPK, Ingredient, InlineReference, InlineReferer, Inquisition, Language, Link, MainPrepopulated, ModelWithStringPrimaryKey, NotReferenced, OldSubscriber, OtherStory, Paper, Parent, ParentWithDependentChildren, ParentWithUUIDPK, Person, Persona, Picture, Pizza, Plot, PlotDetails, PlotProxy, PluggableSearchPerson, Podcast, Post, PrePopulatedPost, PrePopulatedPostLargeSlug, PrePopulatedSubPost, Promo, Question, ReadablePizza, ReadOnlyPizza, ReadOnlyRelatedField, Recipe, Recommendation, Recommender, ReferencedByGenRel, ReferencedByInline, ReferencedByParent, RelatedPrepopulated, RelatedWithUUIDPKModel, Report, Reservation, Restaurant, RowLevelChangePermissionModel, Section, ShortMessage, Simple, Sketch, Song, Square, State, Story, StumpJoke, Subscriber, SuperVillain, Telegram, Thing, Topping, Traveler, UnchangeableObject, UndeletableObject, UnorderedObject, UserMessenger, UserProxy, Villain, Vodcast, Whatsit, Widget, Worker, WorkHour, ) @admin.display(ordering="date") def callable_year(dt_value): try: return dt_value.year except AttributeError: return None class ArticleInline(admin.TabularInline): model = Article fk_name = "section" prepopulated_fields = {"title": ("content",)} fieldsets = ( ("Some fields", {"classes": ("collapse",), "fields": ("title", "content")}), ("Some other fields", {"classes": ("wide",), "fields": ("date", "section")}), ) class ChapterInline(admin.TabularInline): model = Chapter class ChapterXtra1Admin(admin.ModelAdmin): list_filter = ( "chap", "chap__title", "chap__book", "chap__book__name", "chap__book__promo", "chap__book__promo__name", "guest_author__promo__book", ) class ArticleForm(forms.ModelForm): extra_form_field = forms.BooleanField(required=False) class Meta: fields = "__all__" model = Article class ArticleAdminWithExtraUrl(admin.ModelAdmin): def get_urls(self): urlpatterns = super().get_urls() urlpatterns.append( path( "extra.json", self.admin_site.admin_view(self.extra_json), name="article_extra_json", ) ) return urlpatterns def extra_json(self, request): return JsonResponse({}) class ArticleAdmin(ArticleAdminWithExtraUrl): list_display = ( "content", "date", callable_year, "model_year", "modeladmin_year", "model_year_reversed", "section", lambda obj: obj.title, "order_by_expression", "model_property_year", "model_month", "order_by_f_expression", "order_by_orderby_expression", "model_property_is_from_past", ) list_editable = ("section",) list_filter = ("date", "section") autocomplete_fields = ("section",) view_on_site = False form = ArticleForm fieldsets = ( ( "Some fields", { "classes": ("collapse",), "fields": ("title", "content", "extra_form_field"), }, ), ( "Some other fields", {"classes": ("wide",), "fields": ("date", "section", "sub_section")}, ), ("이름", {"fields": ("another_section",)}), ) # These orderings aren't particularly useful but show that expressions can # be used for admin_order_field. @admin.display(ordering=models.F("date") + datetime.timedelta(days=3)) def order_by_expression(self, obj): return obj.model_year @admin.display(ordering=models.F("date")) def order_by_f_expression(self, obj): return obj.model_year @admin.display(ordering=models.F("date").asc(nulls_last=True)) def order_by_orderby_expression(self, obj): return obj.model_year def changelist_view(self, request): return super().changelist_view(request, extra_context={"extra_var": "Hello!"}) @admin.display(ordering="date", description=None) def modeladmin_year(self, obj): return obj.date.year def delete_model(self, request, obj): EmailMessage( "Greetings from a deleted object", "I hereby inform you that some user deleted me", "from@example.com", ["to@example.com"], ).send() return super().delete_model(request, obj) def save_model(self, request, obj, form, change=True): EmailMessage( "Greetings from a created object", "I hereby inform you that some user created me", "from@example.com", ["to@example.com"], ).send() return super().save_model(request, obj, form, change) class ArticleAdmin2(admin.ModelAdmin): def has_module_permission(self, request): return False class RowLevelChangePermissionModelAdmin(admin.ModelAdmin): def has_change_permission(self, request, obj=None): """Only allow changing objects with even id number""" return request.user.is_staff and (obj is not None) and (obj.id % 2 == 0) def has_view_permission(self, request, obj=None): """Only allow viewing objects if id is a multiple of 3.""" return request.user.is_staff and obj is not None and obj.id % 3 == 0 class CustomArticleAdmin(admin.ModelAdmin): """ Tests various hooks for using custom templates and contexts. """ change_list_template = "custom_admin/change_list.html" change_form_template = "custom_admin/change_form.html" add_form_template = "custom_admin/add_form.html" object_history_template = "custom_admin/object_history.html" delete_confirmation_template = "custom_admin/delete_confirmation.html" delete_selected_confirmation_template = ( "custom_admin/delete_selected_confirmation.html" ) popup_response_template = "custom_admin/popup_response.html" def changelist_view(self, request): return super().changelist_view(request, extra_context={"extra_var": "Hello!"}) class ThingAdmin(admin.ModelAdmin): list_filter = ("color", "color__warm", "color__value", "pub_date") class InquisitionAdmin(admin.ModelAdmin): list_display = ("leader", "country", "expected", "sketch") @admin.display def sketch(self, obj): # A method with the same name as a reverse accessor. return "list-display-sketch" class SketchAdmin(admin.ModelAdmin): raw_id_fields = ("inquisition", "defendant0", "defendant1") class FabricAdmin(admin.ModelAdmin): list_display = ("surface",) list_filter = ("surface",) class BasePersonModelFormSet(BaseModelFormSet): def clean(self): for person_dict in self.cleaned_data: person = person_dict.get("id") alive = person_dict.get("alive") if person and alive and person.name == "Grace Hopper": raise ValidationError("Grace is not a Zombie") class PersonAdmin(admin.ModelAdmin): list_display = ("name", "gender", "alive") list_editable = ("gender", "alive") list_filter = ("gender",) search_fields = ("^name",) save_as = True def get_changelist_formset(self, request, **kwargs): return super().get_changelist_formset( request, formset=BasePersonModelFormSet, **kwargs ) def get_queryset(self, request): # Order by a field that isn't in list display, to be able to test # whether ordering is preserved. return super().get_queryset(request).order_by("age") class FooAccountAdmin(admin.StackedInline): model = FooAccount extra = 1 class BarAccountAdmin(admin.StackedInline): model = BarAccount extra = 1 class PersonaAdmin(admin.ModelAdmin): inlines = (FooAccountAdmin, BarAccountAdmin) class SubscriberAdmin(admin.ModelAdmin): actions = ["mail_admin"] action_form = MediaActionForm def delete_queryset(self, request, queryset): SubscriberAdmin.overridden = True super().delete_queryset(request, queryset) @admin.action def mail_admin(self, request, selected): EmailMessage( "Greetings from a ModelAdmin action", "This is the test email from an admin action", "from@example.com", ["to@example.com"], ).send() @admin.action(description="External mail (Another awesome action)") def external_mail(modeladmin, request, selected): EmailMessage( "Greetings from a function action", "This is the test email from a function action", "from@example.com", ["to@example.com"], ).send() @admin.action(description="Redirect to (Awesome action)") def redirect_to(modeladmin, request, selected): from django.http import HttpResponseRedirect return HttpResponseRedirect("/some-where-else/") @admin.action(description="Download subscription") def download(modeladmin, request, selected): buf = StringIO("This is the content of the file") return StreamingHttpResponse(FileWrapper(buf)) @admin.action(description="No permission to run") def no_perm(modeladmin, request, selected): return HttpResponse(content="No permission to perform this action", status=403) class ExternalSubscriberAdmin(admin.ModelAdmin): actions = [redirect_to, external_mail, download, no_perm] class PodcastAdmin(admin.ModelAdmin): list_display = ("name", "release_date") list_editable = ("release_date",) date_hierarchy = "release_date" list_filter = ("name",) search_fields = ("name",) ordering = ("name",) class VodcastAdmin(admin.ModelAdmin): list_display = ("name", "released") list_editable = ("released",) ordering = ("name",) class ChildInline(admin.StackedInline): model = Child class ParentAdmin(admin.ModelAdmin): model = Parent inlines = [ChildInline] save_as = True list_display = ( "id", "name", ) list_display_links = ("id",) list_editable = ("name",) def save_related(self, request, form, formsets, change): super().save_related(request, form, formsets, change) first_name, last_name = form.instance.name.split() for child in form.instance.child_set.all(): if len(child.name.split()) < 2: child.name = child.name + " " + last_name child.save() class EmptyModelAdmin(admin.ModelAdmin): def get_queryset(self, request): return super().get_queryset(request).filter(pk__gt=1) class OldSubscriberAdmin(admin.ModelAdmin): actions = None class PictureInline(admin.TabularInline): model = Picture extra = 1 class GalleryAdmin(admin.ModelAdmin): inlines = [PictureInline] class PictureAdmin(admin.ModelAdmin): pass class LanguageAdmin(admin.ModelAdmin): list_display = ["iso", "shortlist", "english_name", "name"] list_editable = ["shortlist"] class RecommendationAdmin(admin.ModelAdmin): show_full_result_count = False search_fields = ( "=titletranslation__text", "=the_recommender__titletranslation__text", ) class WidgetInline(admin.StackedInline): model = Widget class DooHickeyInline(admin.StackedInline): model = DooHickey class GrommetInline(admin.StackedInline): model = Grommet class WhatsitInline(admin.StackedInline): model = Whatsit class FancyDoodadInline(admin.StackedInline): model = FancyDoodad class CategoryAdmin(admin.ModelAdmin): list_display = ("id", "collector", "order") list_editable = ("order",) class CategoryInline(admin.StackedInline): model = Category class CollectorAdmin(admin.ModelAdmin): inlines = [ WidgetInline, DooHickeyInline, GrommetInline, WhatsitInline, FancyDoodadInline, CategoryInline, ] class LinkInline(admin.TabularInline): model = Link extra = 1 readonly_fields = ("posted", "multiline", "readonly_link_content") @admin.display def multiline(self, instance): return "InlineMultiline\ntest\nstring" class SubPostInline(admin.TabularInline): model = PrePopulatedSubPost prepopulated_fields = {"subslug": ("subtitle",)} def get_readonly_fields(self, request, obj=None): if obj and obj.published: return ("subslug",) return self.readonly_fields def get_prepopulated_fields(self, request, obj=None): if obj and obj.published: return {} return self.prepopulated_fields class PrePopulatedPostAdmin(admin.ModelAdmin): list_display = ["title", "slug"] prepopulated_fields = {"slug": ("title",)} inlines = [SubPostInline] def get_readonly_fields(self, request, obj=None): if obj and obj.published: return ("slug",) return self.readonly_fields def get_prepopulated_fields(self, request, obj=None): if obj and obj.published: return {} return self.prepopulated_fields class PrePopulatedPostReadOnlyAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} def has_change_permission(self, *args, **kwargs): return False class PostAdmin(admin.ModelAdmin): list_display = ["title", "public"] readonly_fields = ( "posted", "awesomeness_level", "coolness", "value", "multiline", "multiline_html", lambda obj: "foo", "readonly_content", ) inlines = [LinkInline] @admin.display def coolness(self, instance): if instance.pk: return "%d amount of cool." % instance.pk else: return "Unknown coolness." @admin.display(description="Value in $US") def value(self, instance): return 1000 @admin.display def multiline(self, instance): return "Multiline\ntest\nstring" @admin.display def multiline_html(self, instance): return mark_safe("Multiline<br>\nhtml<br>\ncontent") class FieldOverridePostForm(forms.ModelForm): model = FieldOverridePost class Meta: help_texts = { "posted": "Overridden help text for the date", } labels = { "public": "Overridden public label", } class FieldOverridePostAdmin(PostAdmin): form = FieldOverridePostForm class CustomChangeList(ChangeList): def get_queryset(self, request): return self.root_queryset.order_by("pk").filter(pk=9999) # Doesn't exist class GadgetAdmin(admin.ModelAdmin): def get_changelist(self, request, **kwargs): return CustomChangeList class ToppingAdmin(admin.ModelAdmin): readonly_fields = ("pizzas",) class PizzaAdmin(admin.ModelAdmin): readonly_fields = ("toppings",) class ReadOnlyRelatedFieldAdmin(admin.ModelAdmin): readonly_fields = ("chapter", "language", "user") class StudentAdmin(admin.ModelAdmin): search_fields = ("name",) class ReadOnlyPizzaAdmin(admin.ModelAdmin): readonly_fields = ("name", "toppings") def has_add_permission(self, request): return False def has_change_permission(self, request, obj=None): return True def has_delete_permission(self, request, obj=None): return True class WorkHourAdmin(admin.ModelAdmin): list_display = ("datum", "employee") list_filter = ("employee",) show_facets = admin.ShowFacets.ALWAYS class FoodDeliveryAdmin(admin.ModelAdmin): list_display = ("reference", "driver", "restaurant") list_editable = ("driver", "restaurant") show_facets = admin.ShowFacets.NEVER class CoverLetterAdmin(admin.ModelAdmin): """ A ModelAdmin with a custom get_queryset() method that uses defer(), to test verbose_name display in messages shown after adding/editing CoverLetter instances. Note that the CoverLetter model defines a __str__ method. For testing fix for ticket #14529. """ def get_queryset(self, request): return super().get_queryset(request).defer("date_written") class PaperAdmin(admin.ModelAdmin): """ A ModelAdmin with a custom get_queryset() method that uses only(), to test verbose_name display in messages shown after adding/editing Paper instances. For testing fix for ticket #14529. """ def get_queryset(self, request): return super().get_queryset(request).only("title") class ShortMessageAdmin(admin.ModelAdmin): """ A ModelAdmin with a custom get_queryset() method that uses defer(), to test verbose_name display in messages shown after adding/editing ShortMessage instances. For testing fix for ticket #14529. """ def get_queryset(self, request): return super().get_queryset(request).defer("timestamp") class TelegramAdmin(admin.ModelAdmin): """ A ModelAdmin with a custom get_queryset() method that uses only(), to test verbose_name display in messages shown after adding/editing Telegram instances. Note that the Telegram model defines a __str__ method. For testing fix for ticket #14529. """ def get_queryset(self, request): return super().get_queryset(request).only("title") class StoryForm(forms.ModelForm): class Meta: widgets = {"title": forms.HiddenInput} class StoryAdmin(admin.ModelAdmin): list_display = ("id", "title", "content") list_display_links = ("title",) # 'id' not in list_display_links list_editable = ("content",) form = StoryForm ordering = ["-id"] class OtherStoryAdmin(admin.ModelAdmin): list_display = ("id", "title", "content") list_display_links = ("title", "id") # 'id' in list_display_links list_editable = ("content",) ordering = ["-id"] class ComplexSortedPersonAdmin(admin.ModelAdmin): list_display = ("name", "age", "is_employee", "colored_name") ordering = ("name",) @admin.display(ordering="name") def colored_name(self, obj): return format_html('<span style="color: #ff00ff;">{}</span>', obj.name) class PluggableSearchPersonAdmin(admin.ModelAdmin): list_display = ("name", "age") search_fields = ("name",) def get_search_results(self, request, queryset, search_term): queryset, may_have_duplicates = super().get_search_results( request, queryset, search_term, ) try: search_term_as_int = int(search_term) except ValueError: pass else: queryset |= self.model.objects.filter(age=search_term_as_int) return queryset, may_have_duplicates class AlbumAdmin(admin.ModelAdmin): list_filter = ["title"] class QuestionAdmin(admin.ModelAdmin): ordering = ["-posted"] search_fields = ["question"] autocomplete_fields = ["related_questions"] class AnswerAdmin(admin.ModelAdmin): autocomplete_fields = ["question"] class PrePopulatedPostLargeSlugAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} class AdminOrderedFieldAdmin(admin.ModelAdmin): ordering = ("order",) list_display = ("stuff", "order") class AdminOrderedModelMethodAdmin(admin.ModelAdmin): ordering = ("order",) list_display = ("stuff", "some_order") class AdminOrderedAdminMethodAdmin(admin.ModelAdmin): @admin.display(ordering="order") def some_admin_order(self, obj): return obj.order ordering = ("order",) list_display = ("stuff", "some_admin_order") @admin.display(ordering="order") def admin_ordered_callable(obj): return obj.order class AdminOrderedCallableAdmin(admin.ModelAdmin): ordering = ("order",) list_display = ("stuff", admin_ordered_callable) class ReportAdmin(admin.ModelAdmin): def extra(self, request): return HttpResponse() def get_urls(self): # Corner case: Don't call parent implementation return [path("extra/", self.extra, name="cable_extra")] class CustomTemplateBooleanFieldListFilter(BooleanFieldListFilter): template = "custom_filter_template.html" class CustomTemplateFilterColorAdmin(admin.ModelAdmin): list_filter = (("warm", CustomTemplateBooleanFieldListFilter),) # For Selenium Prepopulated tests ------------------------------------- class RelatedPrepopulatedInline1(admin.StackedInline): fieldsets = ( ( None, { "fields": ( ("fk", "m2m"), ("pubdate", "status"), ( "name", "slug1", "slug2", ), ), }, ), ) formfield_overrides = {models.CharField: {"strip": False}} model = RelatedPrepopulated extra = 1 autocomplete_fields = ["fk", "m2m"] prepopulated_fields = { "slug1": ["name", "pubdate"], "slug2": ["status", "name"], } class RelatedPrepopulatedInline2(admin.TabularInline): model = RelatedPrepopulated extra = 1 autocomplete_fields = ["fk", "m2m"] prepopulated_fields = { "slug1": ["name", "pubdate"], "slug2": ["status", "name"], } class RelatedPrepopulatedInline3(admin.TabularInline): model = RelatedPrepopulated extra = 0 autocomplete_fields = ["fk", "m2m"] class RelatedPrepopulatedStackedInlineNoFieldsets(admin.StackedInline): model = RelatedPrepopulated extra = 1 prepopulated_fields = { "slug1": ["name", "pubdate"], "slug2": ["status"], } class MainPrepopulatedAdmin(admin.ModelAdmin): inlines = [ RelatedPrepopulatedInline1, RelatedPrepopulatedInline2, RelatedPrepopulatedInline3, RelatedPrepopulatedStackedInlineNoFieldsets, ] fieldsets = ( ( None, {"fields": (("pubdate", "status"), ("name", "slug1", "slug2", "slug3"))}, ), ) formfield_overrides = {models.CharField: {"strip": False}} prepopulated_fields = { "slug1": ["name", "pubdate"], "slug2": ["status", "name"], "slug3": ["name"], } class UnorderedObjectAdmin(admin.ModelAdmin): list_display = ["id", "name"] list_display_links = ["id"] list_editable = ["name"] list_per_page = 2 class UndeletableObjectAdmin(admin.ModelAdmin): def change_view(self, *args, **kwargs): kwargs["extra_context"] = {"show_delete": False} return super().change_view(*args, **kwargs) class UnchangeableObjectAdmin(admin.ModelAdmin): def get_urls(self): # Disable change_view, but leave other urls untouched urlpatterns = super().get_urls() return [p for p in urlpatterns if p.name and not p.name.endswith("_change")] @admin.display def callable_on_unknown(obj): return obj.unknown class AttributeErrorRaisingAdmin(admin.ModelAdmin): list_display = [callable_on_unknown] class CustomManagerAdmin(admin.ModelAdmin): def get_queryset(self, request): return FilteredManager.objects class MessageTestingAdmin(admin.ModelAdmin): actions = [ "message_debug", "message_info", "message_success", "message_warning", "message_error", "message_extra_tags", ] @admin.action def message_debug(self, request, selected): self.message_user(request, "Test debug", level="debug") @admin.action def message_info(self, request, selected): self.message_user(request, "Test info", level="info") @admin.action def message_success(self, request, selected): self.message_user(request, "Test success", level="success") @admin.action def message_warning(self, request, selected): self.message_user(request, "Test warning", level="warning") @admin.action def message_error(self, request, selected): self.message_user(request, "Test error", level="error") @admin.action def message_extra_tags(self, request, selected): self.message_user(request, "Test tags", extra_tags="extra_tag") class ChoiceList(admin.ModelAdmin): list_display = ["choice"] readonly_fields = ["choice"] fields = ["choice"] class DependentChildAdminForm(forms.ModelForm): """ Issue #20522 Form to test child dependency on parent object's validation """ def clean(self): parent = self.cleaned_data.get("parent") if parent.family_name and parent.family_name != self.cleaned_data.get( "family_name" ): raise ValidationError( "Children must share a family name with their parents " + "in this contrived test case" ) return super().clean() class DependentChildInline(admin.TabularInline): model = DependentChild form = DependentChildAdminForm class ParentWithDependentChildrenAdmin(admin.ModelAdmin): inlines = [DependentChildInline] # Tests for ticket 11277 ---------------------------------- class FormWithoutHiddenField(forms.ModelForm): first = forms.CharField() second = forms.CharField() class FormWithoutVisibleField(forms.ModelForm): first = forms.CharField(widget=forms.HiddenInput) second = forms.CharField(widget=forms.HiddenInput) class FormWithVisibleAndHiddenField(forms.ModelForm): first = forms.CharField(widget=forms.HiddenInput) second = forms.CharField() class EmptyModelVisibleAdmin(admin.ModelAdmin): form = FormWithoutHiddenField fieldsets = ( ( None, { "fields": (("first", "second"),), }, ), ) class EmptyModelHiddenAdmin(admin.ModelAdmin): form = FormWithoutVisibleField fieldsets = EmptyModelVisibleAdmin.fieldsets class EmptyModelMixinAdmin(admin.ModelAdmin): form = FormWithVisibleAndHiddenField fieldsets = EmptyModelVisibleAdmin.fieldsets class CityInlineAdmin(admin.TabularInline): model = City view_on_site = False class StateAdminForm(forms.ModelForm): nolabel_form_field = forms.BooleanField(required=False) class Meta: model = State fields = "__all__" labels = {"name": "State name (from form’s Meta.labels)"} @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 StateAdmin(admin.ModelAdmin): inlines = [CityInlineAdmin] form = StateAdminForm class RestaurantInlineAdmin(admin.TabularInline): model = Restaurant view_on_site = True class CityAdmin(admin.ModelAdmin): inlines = [RestaurantInlineAdmin] view_on_site = True def get_formset_kwargs(self, request, obj, inline, prefix): return { **super().get_formset_kwargs(request, obj, inline, prefix), "form_kwargs": {"initial": {"name": "overridden_name"}}, } class WorkerAdmin(admin.ModelAdmin): def view_on_site(self, obj): return "/worker/%s/%s/" % (obj.surname, obj.name) class WorkerInlineAdmin(admin.TabularInline): model = Worker def view_on_site(self, obj): return "/worker_inline/%s/%s/" % (obj.surname, obj.name) class RestaurantAdmin(admin.ModelAdmin): inlines = [WorkerInlineAdmin] view_on_site = False def get_changeform_initial_data(self, request): return {"name": "overridden_value"} class FunkyTagAdmin(admin.ModelAdmin): list_display = ("name", "content_object") class InlineReferenceInline(admin.TabularInline): model = InlineReference class InlineRefererAdmin(admin.ModelAdmin): inlines = [InlineReferenceInline] class PlotReadonlyAdmin(admin.ModelAdmin): readonly_fields = ("plotdetails",) class GetFormsetsArgumentCheckingAdmin(admin.ModelAdmin): fields = ["name"] def add_view(self, request, *args, **kwargs): request.is_add_view = True return super().add_view(request, *args, **kwargs) def change_view(self, request, *args, **kwargs): request.is_add_view = False return super().change_view(request, *args, **kwargs) def get_formsets_with_inlines(self, request, obj=None): if request.is_add_view and obj is not None: raise Exception( "'obj' passed to get_formsets_with_inlines wasn't None during add_view" ) if not request.is_add_view and obj is None: raise Exception( "'obj' passed to get_formsets_with_inlines was None during change_view" ) return super().get_formsets_with_inlines(request, obj) class CountryAdmin(admin.ModelAdmin): search_fields = ["name"] class TravelerAdmin(admin.ModelAdmin): autocomplete_fields = ["living_country"] class SquareAdmin(admin.ModelAdmin): readonly_fields = ("area",) class CamelCaseAdmin(admin.ModelAdmin): filter_horizontal = ["m2m"] class CourseAdmin(admin.ModelAdmin): radio_fields = {"difficulty": admin.VERTICAL} site = admin.AdminSite(name="admin") site.site_url = "/my-site-url/" site.register(Article, ArticleAdmin) site.register(CustomArticle, CustomArticleAdmin) site.register( Section, save_as=True, inlines=[ArticleInline], readonly_fields=["name_property"], search_fields=["name"], ) site.register(ModelWithStringPrimaryKey) site.register(Color) site.register(Thing, ThingAdmin) site.register(Actor) site.register(Inquisition, InquisitionAdmin) site.register(Sketch, SketchAdmin) site.register(Person, PersonAdmin) site.register(Persona, PersonaAdmin) site.register(Subscriber, SubscriberAdmin) site.register(ExternalSubscriber, ExternalSubscriberAdmin) site.register(OldSubscriber, OldSubscriberAdmin) site.register(Podcast, PodcastAdmin) site.register(Vodcast, VodcastAdmin) site.register(Parent, ParentAdmin) site.register(EmptyModel, EmptyModelAdmin) site.register(Fabric, FabricAdmin) site.register(Gallery, GalleryAdmin) site.register(Picture, PictureAdmin) site.register(Language, LanguageAdmin) site.register(Recommendation, RecommendationAdmin) site.register(Recommender) site.register(Collector, CollectorAdmin) site.register(Category, CategoryAdmin) site.register(Post, PostAdmin) site.register(FieldOverridePost, FieldOverridePostAdmin) site.register(Gadget, GadgetAdmin) site.register(Villain) site.register(SuperVillain) site.register(Plot) site.register(PlotDetails) site.register(PlotProxy, PlotReadonlyAdmin) site.register(Bookmark) site.register(CyclicOne) site.register(CyclicTwo) site.register(WorkHour, WorkHourAdmin) site.register(Reservation) site.register(FoodDelivery, FoodDeliveryAdmin)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_multidb.py
tests/admin_views/test_multidb.py
from unittest import mock from django.contrib import admin from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.http import HttpResponse from django.test import TestCase, override_settings from django.urls import path, reverse from .models import Book class Router: target_db = None def db_for_read(self, model, **hints): return self.target_db db_for_write = db_for_read def allow_relation(self, obj1, obj2, **hints): return True site = admin.AdminSite(name="test_adminsite") site.register(Book) def book(request, book_id): b = Book.objects.get(id=book_id) return HttpResponse(b.title) urlpatterns = [ path("admin/", site.urls), path("books/<book_id>/", book), ] @override_settings(ROOT_URLCONF=__name__, DATABASE_ROUTERS=["%s.Router" % __name__]) class MultiDatabaseTests(TestCase): databases = {"default", "other"} READ_ONLY_METHODS = {"get", "options", "head", "trace"} @classmethod def setUpTestData(cls): cls.superusers = {} cls.test_book_ids = {} for db in cls.databases: Router.target_db = db cls.superusers[db] = User.objects.create_superuser( username="admin", password="something", email="test@test.org", ) b = Book(name="Test Book") b.save(using=db) cls.test_book_ids[db] = b.id def tearDown(self): # Reset the routers' state between each test. Router.target_db = None @mock.patch("django.contrib.admin.options.transaction") def test_add_view(self, mock): for db in self.databases: with self.subTest(db=db): mock.mock_reset() Router.target_db = db self.client.force_login(self.superusers[db]) response = self.client.post( reverse("test_adminsite:admin_views_book_add"), {"name": "Foobar: 5th edition"}, ) self.assertEqual(response.status_code, 302) self.assertEqual( response.url, reverse("test_adminsite:admin_views_book_changelist") ) mock.atomic.assert_called_with(using=db) @mock.patch("django.contrib.admin.options.transaction") def test_read_only_methods_add_view(self, mock): for db in self.databases: for method in self.READ_ONLY_METHODS: with self.subTest(db=db, method=method): mock.mock_reset() Router.target_db = db self.client.force_login(self.superusers[db]) response = getattr(self.client, method)( reverse("test_adminsite:admin_views_book_add"), ) self.assertEqual(response.status_code, 200) mock.atomic.assert_not_called() @mock.patch("django.contrib.admin.options.transaction") def test_change_view(self, mock): for db in self.databases: with self.subTest(db=db): mock.mock_reset() Router.target_db = db self.client.force_login(self.superusers[db]) response = self.client.post( reverse( "test_adminsite:admin_views_book_change", args=[self.test_book_ids[db]], ), {"name": "Test Book 2: Test more"}, ) self.assertEqual(response.status_code, 302) self.assertEqual( response.url, reverse("test_adminsite:admin_views_book_changelist") ) mock.atomic.assert_called_with(using=db) @mock.patch("django.contrib.admin.options.transaction") def test_read_only_methods_change_view(self, mock): for db in self.databases: for method in self.READ_ONLY_METHODS: with self.subTest(db=db, method=method): mock.mock_reset() Router.target_db = db self.client.force_login(self.superusers[db]) response = getattr(self.client, method)( reverse( "test_adminsite:admin_views_book_change", args=[self.test_book_ids[db]], ), data={"name": "Test Book 2: Test more"}, ) self.assertEqual(response.status_code, 200) mock.atomic.assert_not_called() @mock.patch("django.contrib.admin.options.transaction") def test_delete_view(self, mock): for db in self.databases: with self.subTest(db=db): mock.mock_reset() Router.target_db = db self.client.force_login(self.superusers[db]) response = self.client.post( reverse( "test_adminsite:admin_views_book_delete", args=[self.test_book_ids[db]], ), {"post": "yes"}, ) self.assertEqual(response.status_code, 302) self.assertEqual( response.url, reverse("test_adminsite:admin_views_book_changelist") ) mock.atomic.assert_called_with(using=db) @mock.patch("django.contrib.admin.options.transaction") def test_read_only_methods_delete_view(self, mock): for db in self.databases: for method in self.READ_ONLY_METHODS: with self.subTest(db=db, method=method): mock.mock_reset() Router.target_db = db self.client.force_login(self.superusers[db]) response = getattr(self.client, method)( reverse( "test_adminsite:admin_views_book_delete", args=[self.test_book_ids[db]], ) ) self.assertEqual(response.status_code, 200) mock.atomic.assert_not_called() class ViewOnSiteRouter: def db_for_read(self, model, instance=None, **hints): if model._meta.app_label in {"auth", "sessions", "contenttypes"}: return "default" return "other" def db_for_write(self, model, **hints): if model._meta.app_label in {"auth", "sessions", "contenttypes"}: return "default" return "other" def allow_relation(self, obj1, obj2, **hints): return obj1._state.db in {"default", "other"} and obj2._state.db in { "default", "other", } def allow_migrate(self, db, app_label, **hints): return True @override_settings(ROOT_URLCONF=__name__, DATABASE_ROUTERS=[ViewOnSiteRouter()]) class ViewOnSiteTests(TestCase): databases = {"default", "other"} def test_contenttype_in_separate_db(self): ContentType.objects.using("other").all().delete() book = Book.objects.using("other").create(name="other book") user = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) book_type = ContentType.objects.get(app_label="admin_views", model="book") self.client.force_login(user) shortcut_url = reverse("admin:view_on_site", args=(book_type.pk, book.id)) response = self.client.get(shortcut_url, follow=False) self.assertEqual(response.status_code, 302) self.assertRegex( response.url, f"http://(testserver|example.com)/books/{book.id}/" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_forms.py
tests/admin_views/test_forms.py
from django.contrib.admin.forms import AdminAuthenticationForm from django.contrib.admin.helpers import AdminForm from django.contrib.auth.models import User from django.test import SimpleTestCase, TestCase, override_settings from .admin import ArticleForm # To verify that the login form rejects inactive users, use an authentication # backend that allows them. @override_settings( AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.AllowAllUsersModelBackend"] ) class AdminAuthenticationFormTests(TestCase): @classmethod def setUpTestData(cls): User.objects.create_user( username="inactive", password="password", is_active=False ) def test_inactive_user(self): data = { "username": "inactive", "password": "password", } form = AdminAuthenticationForm(None, data) self.assertEqual(form.non_field_errors(), ["This account is inactive."]) class AdminFormTests(SimpleTestCase): def test_repr(self): fieldsets = ( ( "My fields", { "classes": ["collapse"], "fields": ("url", "title", "content", "sites"), }, ), ) form = ArticleForm() admin_form = AdminForm(form, fieldsets, {}) self.assertEqual( repr(admin_form), "<AdminForm: form=ArticleForm fieldsets=(('My fields', " "{'classes': ['collapse'], " "'fields': ('url', 'title', 'content', 'sites')}),)>", )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/models.py
tests/admin_views/models.py
import datetime import tempfile import uuid from django.contrib import admin from django.contrib.auth.models import User from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ValidationError from django.core.files.storage import FileSystemStorage from django.db import models from django.utils import timezone class Section(models.Model): """ A simple section that links to articles, to test linking to related items in admin views. """ name = models.CharField(max_length=100) def __str__(self): return self.name @property def name_property(self): """ A property that simply returns the name. Used to test #24461 """ return self.name class Article(models.Model): """ A simple article to test admin views. Test backwards compatibility. """ title = models.CharField(max_length=100) content = models.TextField() date = models.DateTimeField() section = models.ForeignKey(Section, models.CASCADE, null=True, blank=True) another_section = models.ForeignKey( Section, models.CASCADE, null=True, blank=True, related_name="+" ) sub_section = models.ForeignKey( Section, models.SET_NULL, null=True, blank=True, related_name="+" ) def __str__(self): return self.title @admin.display(ordering="date", description="") def model_year(self): return self.date.year @admin.display(ordering="-date", description="") def model_year_reversed(self): return self.date.year @property @admin.display(ordering="date") def model_property_year(self): return self.date.year @property def model_month(self): return self.date.month @property @admin.display(description="Is from past?", boolean=True) def model_property_is_from_past(self): return self.date < timezone.now() class Book(models.Model): """ A simple book that has chapters. """ name = models.CharField(max_length=100, verbose_name="¿Name?") def __str__(self): return self.name def get_absolute_url(self): return f"/books/{self.id}/" class Promo(models.Model): name = models.CharField(max_length=100, verbose_name="¿Name?") book = models.ForeignKey(Book, models.CASCADE) author = models.ForeignKey(User, models.SET_NULL, blank=True, null=True) def __str__(self): return self.name class Chapter(models.Model): title = models.CharField(max_length=100, verbose_name="¿Title?") content = models.TextField() book = models.ForeignKey(Book, models.CASCADE) class Meta: # Use a utf-8 bytestring to ensure it works (see #11710) verbose_name = "¿Chapter?" def __str__(self): return self.title class ChapterXtra1(models.Model): chap = models.OneToOneField(Chapter, models.CASCADE, verbose_name="¿Chap?") xtra = models.CharField(max_length=100, verbose_name="¿Xtra?") guest_author = models.ForeignKey(User, models.SET_NULL, blank=True, null=True) def __str__(self): return "¿Xtra1: %s" % self.xtra class ChapterXtra2(models.Model): chap = models.OneToOneField(Chapter, models.CASCADE, verbose_name="¿Chap?") xtra = models.CharField(max_length=100, verbose_name="¿Xtra?") def __str__(self): return "¿Xtra2: %s" % self.xtra class RowLevelChangePermissionModel(models.Model): name = models.CharField(max_length=100, blank=True) class CustomArticle(models.Model): content = models.TextField() date = models.DateTimeField() class ModelWithStringPrimaryKey(models.Model): string_pk = models.CharField(max_length=255, primary_key=True) def __str__(self): return self.string_pk def get_absolute_url(self): return "/dummy/%s/" % self.string_pk class Color(models.Model): value = models.CharField(max_length=10) warm = models.BooleanField(default=False) def __str__(self): return self.value # we replicate Color to register with another ModelAdmin class Color2(Color): class Meta: proxy = True class Thing(models.Model): title = models.CharField(max_length=20) color = models.ForeignKey(Color, models.CASCADE, limit_choices_to={"warm": True}) pub_date = models.DateField(blank=True, null=True) def __str__(self): return self.title class Actor(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() title = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.name class Inquisition(models.Model): expected = models.BooleanField(default=False) leader = models.ForeignKey(Actor, models.CASCADE) country = models.CharField(max_length=20) def __str__(self): return "by %s from %s" % (self.leader, self.country) class Sketch(models.Model): title = models.CharField(max_length=100) inquisition = models.ForeignKey( Inquisition, models.CASCADE, limit_choices_to={ "leader__name": "Palin", "leader__age": 27, "expected": False, }, ) defendant0 = models.ForeignKey( Actor, models.CASCADE, limit_choices_to={"title__isnull": False}, related_name="as_defendant0", ) defendant1 = models.ForeignKey( Actor, models.CASCADE, limit_choices_to={"title__isnull": True}, related_name="as_defendant1", ) def __str__(self): return self.title 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() def __str__(self): return self.username class StumpJoke(models.Model): variation = models.CharField(max_length=100) 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="+" ) def __str__(self): return self.variation class Fabric(models.Model): NG_CHOICES = ( ( "Textured", ( ("x", "Horizontal"), ("y", "Vertical"), ), ), ("plain", "Smooth"), ) surface = models.CharField(max_length=20, choices=NG_CHOICES) class Person(models.Model): GENDER_CHOICES = ( (1, "Male"), (2, "Female"), ) name = models.CharField(max_length=100) gender = models.IntegerField(choices=GENDER_CHOICES) age = models.IntegerField(default=21) alive = models.BooleanField(default=True) def __str__(self): return self.name class Persona(models.Model): """ A simple persona associated with accounts, to test inlining of related accounts which inherit from a common accounts class. """ name = models.CharField(blank=False, max_length=80) def __str__(self): return self.name class Account(models.Model): """ A simple, generic account encapsulating the information shared by all types of accounts. """ username = models.CharField(blank=False, max_length=80) persona = models.ForeignKey(Persona, models.CASCADE, related_name="accounts") servicename = "generic service" def __str__(self): return "%s: %s" % (self.servicename, self.username) class FooAccount(Account): """A service-specific account of type Foo.""" servicename = "foo" class BarAccount(Account): """A service-specific account of type Bar.""" servicename = "bar" class Subscriber(models.Model): name = models.CharField(blank=False, max_length=80) email = models.EmailField(blank=False, max_length=175) def __str__(self): return "%s (%s)" % (self.name, self.email) class ExternalSubscriber(Subscriber): pass class OldSubscriber(Subscriber): pass class Media(models.Model): name = models.CharField(max_length=60) class Podcast(Media): release_date = models.DateField() class Meta: ordering = ("release_date",) # overridden in PodcastAdmin class Vodcast(Media): media = models.OneToOneField( Media, models.CASCADE, primary_key=True, parent_link=True ) released = models.BooleanField(default=False) class Parent(models.Model): name = models.CharField(max_length=128) def clean(self): if self.name == "_invalid": raise ValidationError("invalid") class Child(models.Model): parent = models.ForeignKey(Parent, models.CASCADE, editable=False) name = models.CharField(max_length=30, blank=True) def clean(self): if self.name == "_invalid": raise ValidationError("invalid") class PKChild(models.Model): """ Used to check autocomplete to_field resolution when ForeignKey is PK. """ parent = models.ForeignKey(Parent, models.CASCADE, primary_key=True) name = models.CharField(max_length=128) class Meta: ordering = ["parent"] def __str__(self): return self.name class Toy(models.Model): child = models.ForeignKey(PKChild, models.CASCADE) class EmptyModel(models.Model): def __str__(self): return "Primary key = %s" % self.id temp_storage = FileSystemStorage(tempfile.mkdtemp()) class Gallery(models.Model): name = models.CharField(max_length=100) class Picture(models.Model): name = models.CharField(max_length=100) image = models.FileField(storage=temp_storage, upload_to="test_upload") gallery = models.ForeignKey(Gallery, models.CASCADE, related_name="pictures") class Language(models.Model): iso = models.CharField(max_length=5, primary_key=True) name = models.CharField(max_length=50) english_name = models.CharField(max_length=50) shortlist = models.BooleanField(default=False) def __str__(self): return self.iso class Meta: ordering = ("iso",) # a base class for Recommender and Recommendation class Title(models.Model): pass class TitleTranslation(models.Model): title = models.ForeignKey(Title, models.CASCADE) text = models.CharField(max_length=100) class Recommender(Title): pass class Recommendation(Title): the_recommender = models.ForeignKey(Recommender, models.CASCADE) class Collector(models.Model): name = models.CharField(max_length=100) class Widget(models.Model): owner = models.ForeignKey(Collector, models.CASCADE) name = models.CharField(max_length=100) class DooHickey(models.Model): code = models.CharField(max_length=10, primary_key=True) owner = models.ForeignKey(Collector, models.CASCADE) name = models.CharField(max_length=100) class Grommet(models.Model): code = models.AutoField(primary_key=True) owner = models.ForeignKey(Collector, models.CASCADE) name = models.CharField(max_length=100) class Whatsit(models.Model): index = models.IntegerField(primary_key=True) owner = models.ForeignKey(Collector, models.CASCADE) name = models.CharField(max_length=100) class Doodad(models.Model): name = models.CharField(max_length=100) class FancyDoodad(Doodad): owner = models.ForeignKey(Collector, models.CASCADE) expensive = models.BooleanField(default=True) class Category(models.Model): collector = models.ForeignKey(Collector, models.CASCADE) order = models.PositiveIntegerField() class Meta: ordering = ("order",) def __str__(self): return "%s:o%s" % (self.id, self.order) def link_posted_default(): return datetime.date.today() - datetime.timedelta(days=7) class Link(models.Model): posted = models.DateField(default=link_posted_default) url = models.URLField() post = models.ForeignKey("Post", models.CASCADE) readonly_link_content = models.TextField() class PrePopulatedPost(models.Model): title = models.CharField(max_length=100) published = models.BooleanField(default=False) slug = models.SlugField() class PrePopulatedSubPost(models.Model): post = models.ForeignKey(PrePopulatedPost, models.CASCADE) subtitle = models.CharField(max_length=100) subslug = models.SlugField() class Post(models.Model): title = models.CharField( max_length=100, help_text="Some help text for the title (with Unicode ŠĐĆŽćžšđ)" ) content = models.TextField( help_text="Some help text for the content (with Unicode ŠĐĆŽćžšđ)" ) readonly_content = models.TextField() posted = models.DateField( default=datetime.date.today, help_text="Some help text for the date (with Unicode ŠĐĆŽćžšđ)", ) public = models.BooleanField(null=True, blank=True) def awesomeness_level(self): return "Very awesome." # Proxy model to test overridden fields attrs on Post model so as not to # interfere with other tests. class FieldOverridePost(Post): class Meta: proxy = True class Gadget(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Villain(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class SuperVillain(Villain): pass class FunkyTag(models.Model): "Because we all know there's only one real use case for GFKs." name = models.CharField(max_length=25) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") def __str__(self): return self.name class Plot(models.Model): name = models.CharField(max_length=100) team_leader = models.ForeignKey(Villain, models.CASCADE, related_name="lead_plots") contact = models.ForeignKey(Villain, models.CASCADE, related_name="contact_plots") tags = GenericRelation(FunkyTag) def __str__(self): return self.name class PlotDetails(models.Model): details = models.CharField(max_length=100) plot = models.OneToOneField(Plot, models.CASCADE, null=True, blank=True) def __str__(self): return self.details class PlotProxy(Plot): class Meta: proxy = True class SecretHideout(models.Model): """Secret! Not registered with the admin!""" location = models.CharField(max_length=100) villain = models.ForeignKey(Villain, models.CASCADE) def __str__(self): return self.location class SuperSecretHideout(models.Model): """Secret! Not registered with the admin!""" location = models.CharField(max_length=100) supervillain = models.ForeignKey(SuperVillain, models.CASCADE) def __str__(self): return self.location class Bookmark(models.Model): name = models.CharField(max_length=60) tag = GenericRelation(FunkyTag, related_query_name="bookmark") def __str__(self): return self.name class CyclicOne(models.Model): name = models.CharField(max_length=25) two = models.ForeignKey("CyclicTwo", models.CASCADE) def __str__(self): return self.name class CyclicTwo(models.Model): name = models.CharField(max_length=25) one = models.ForeignKey(CyclicOne, models.CASCADE) def __str__(self): return self.name class Course(models.Model): DIFFICULTY_CHOICES = [ ("beginner", "Beginner Class"), ("intermediate", "Intermediate Class"), ("advanced", "Advanced Class"), ] title = models.CharField(max_length=100) materials = models.FileField(upload_to="test_upload") difficulty = models.CharField( max_length=20, choices=DIFFICULTY_CHOICES, null=True, blank=True ) categories = models.ManyToManyField(Category, blank=True) start_datetime = models.DateTimeField(null=True, blank=True) class Topping(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Pizza(models.Model): name = models.CharField(max_length=20) toppings = models.ManyToManyField("Topping", related_name="pizzas") # Pizza's ModelAdmin has readonly_fields = ['toppings']. # toppings is editable for this model's admin. class ReadablePizza(Pizza): class Meta: proxy = True # No default permissions are created for this model and both name and toppings # are readonly for this model's admin. class ReadOnlyPizza(Pizza): class Meta: proxy = True default_permissions = () class Album(models.Model): owner = models.ForeignKey(User, models.SET_NULL, null=True, blank=True) title = models.CharField(max_length=30) class Song(models.Model): name = models.CharField(max_length=20) album = models.ForeignKey(Album, on_delete=models.RESTRICT) def __str__(self): return self.name class Employee(Person): code = models.CharField(max_length=20) class Meta: ordering = ["name"] class WorkHour(models.Model): datum = models.DateField() employee = models.ForeignKey(Employee, models.CASCADE) class Manager(Employee): """ A multi-layer MTI child. """ pass class Bonus(models.Model): recipient = models.ForeignKey(Manager, on_delete=models.CASCADE) class Question(models.Model): big_id = models.BigAutoField(primary_key=True) question = models.CharField(max_length=20) posted = models.DateField(default=datetime.date.today) expires = models.DateTimeField(null=True, blank=True) related_questions = models.ManyToManyField("self") uuid = models.UUIDField(default=uuid.uuid4, unique=True) def __str__(self): return self.question class Answer(models.Model): question = models.ForeignKey(Question, models.PROTECT) question_with_to_field = models.ForeignKey( Question, models.SET_NULL, blank=True, null=True, to_field="uuid", related_name="uuid_answers", limit_choices_to=~models.Q(question__istartswith="not"), ) related_answers = models.ManyToManyField("self") answer = models.CharField(max_length=20) def __str__(self): return self.answer class Answer2(Answer): class Meta: proxy = True class Reservation(models.Model): start_date = models.DateTimeField() price = models.IntegerField() class FoodDelivery(models.Model): DRIVER_CHOICES = ( ("bill", "Bill G"), ("steve", "Steve J"), ) RESTAURANT_CHOICES = ( ("indian", "A Taste of India"), ("thai", "Thai Pography"), ("pizza", "Pizza Mama"), ) reference = models.CharField(max_length=100) driver = models.CharField(max_length=100, choices=DRIVER_CHOICES, blank=True) restaurant = models.CharField( max_length=100, choices=RESTAURANT_CHOICES, blank=True ) class Meta: unique_together = (("driver", "restaurant"),) class CoverLetter(models.Model): author = models.CharField(max_length=30) date_written = models.DateField(null=True, blank=True) def __str__(self): return self.author class Paper(models.Model): title = models.CharField(max_length=30) author = models.CharField(max_length=30, blank=True, null=True) class ShortMessage(models.Model): content = models.CharField(max_length=140) timestamp = models.DateTimeField(null=True, blank=True) class Telegram(models.Model): title = models.CharField(max_length=30) date_sent = models.DateField(null=True, blank=True) def __str__(self): return self.title class Story(models.Model): title = models.CharField(max_length=100) content = models.TextField() class OtherStory(models.Model): title = models.CharField(max_length=100) content = models.TextField() class ComplexSortedPerson(models.Model): name = models.CharField(max_length=100) age = models.PositiveIntegerField() is_employee = models.BooleanField(null=True) class PluggableSearchPerson(models.Model): name = models.CharField(max_length=100) age = models.PositiveIntegerField() class PrePopulatedPostLargeSlug(models.Model): """ Regression test for #15938: a large max_length for the slugfield must not be localized in prepopulated_fields_js.html or it might end up breaking the JavaScript (ie, using THOUSAND_SEPARATOR ends up with maxLength=1,000) """ title = models.CharField(max_length=100) published = models.BooleanField(default=False) # `db_index=False` because MySQL cannot index large CharField (#21196). slug = models.SlugField(max_length=1000, db_index=False) class AdminOrderedField(models.Model): order = models.IntegerField() stuff = models.CharField(max_length=200) class AdminOrderedModelMethod(models.Model): order = models.IntegerField() stuff = models.CharField(max_length=200) @admin.display(ordering="order") def some_order(self): return self.order class AdminOrderedAdminMethod(models.Model): order = models.IntegerField() stuff = models.CharField(max_length=200) class AdminOrderedCallable(models.Model): order = models.IntegerField() stuff = models.CharField(max_length=200) class Report(models.Model): title = models.CharField(max_length=100) def __str__(self): return self.title class MainPrepopulated(models.Model): name = models.CharField(max_length=100) pubdate = models.DateField() status = models.CharField( max_length=20, choices=(("option one", "Option One"), ("option two", "Option Two")), ) slug1 = models.SlugField(blank=True) slug2 = models.SlugField(blank=True) slug3 = models.SlugField(blank=True, allow_unicode=True) class RelatedPrepopulated(models.Model): parent = models.ForeignKey(MainPrepopulated, models.CASCADE) name = models.CharField(max_length=75) fk = models.ForeignKey("self", models.CASCADE, blank=True, null=True) m2m = models.ManyToManyField("self", blank=True) pubdate = models.DateField() status = models.CharField( max_length=20, choices=(("option one", "Option One"), ("option two", "Option Two")), ) slug1 = models.SlugField(max_length=50) slug2 = models.SlugField(max_length=60) class UnorderedObject(models.Model): """ Model without any defined `Meta.ordering`. Refs #16819. """ name = models.CharField(max_length=255) bool = models.BooleanField(default=True) class UndeletableObject(models.Model): """ Model whose show_delete in admin change_view has been disabled Refs #10057. """ name = models.CharField(max_length=255) class UnchangeableObject(models.Model): """ Model whose change_view is disabled in admin Refs #20640. """ class UserMessenger(models.Model): """ Dummy class for testing message_user functions on ModelAdmin """ class Simple(models.Model): """ Simple model with nothing on it for use in testing """ class Choice(models.Model): choice = models.IntegerField( blank=True, null=True, choices=((1, "Yes"), (0, "No"), (None, "No opinion")), ) class ParentWithDependentChildren(models.Model): """ Issue #20522 Model where the validation of child foreign-key relationships depends on validation of the parent """ some_required_info = models.PositiveIntegerField() family_name = models.CharField(max_length=255, blank=False) class DependentChild(models.Model): """ Issue #20522 Model that depends on validation of the parent class for one of its fields to validate during clean """ parent = models.ForeignKey(ParentWithDependentChildren, models.CASCADE) family_name = models.CharField(max_length=255) class _Manager(models.Manager): def get_queryset(self): return super().get_queryset().filter(pk__gt=1) class FilteredManager(models.Model): def __str__(self): return "PK=%d" % self.pk pk_gt_1 = _Manager() objects = models.Manager() class EmptyModelVisible(models.Model): """See ticket #11277.""" class EmptyModelHidden(models.Model): """See ticket #11277.""" class EmptyModelMixin(models.Model): """See ticket #11277.""" class State(models.Model): name = models.CharField(max_length=100, verbose_name="State verbose_name") class City(models.Model): state = models.ForeignKey(State, models.CASCADE) name = models.CharField(max_length=100, verbose_name="City verbose_name") def get_absolute_url(self): return "/dummy/%s/" % self.pk class Restaurant(models.Model): city = models.ForeignKey(City, models.CASCADE) name = models.CharField(max_length=100) class Meta: verbose_name = ( "very very very very very very very very very " "loooooooooooooooooooooooooooooooooooooooooong name" ) def get_absolute_url(self): return "/dummy/%s/" % self.pk class Worker(models.Model): work_at = models.ForeignKey(Restaurant, models.CASCADE) name = models.CharField(max_length=50) surname = models.CharField(max_length=50) # Models for #23329 class ReferencedByParent(models.Model): name = models.CharField(max_length=20, unique=True) class ParentWithFK(models.Model): fk = models.ForeignKey( ReferencedByParent, models.CASCADE, to_field="name", related_name="hidden+", ) class ChildOfReferer(ParentWithFK): pass # Models for #23431 class InlineReferer(models.Model): pass class ReferencedByInline(models.Model): name = models.CharField(max_length=20, unique=True) class InlineReference(models.Model): referer = models.ForeignKey(InlineReferer, models.CASCADE) fk = models.ForeignKey( ReferencedByInline, models.CASCADE, to_field="name", related_name="hidden+", ) class Recipe(models.Model): rname = models.CharField(max_length=20, unique=True) class Ingredient(models.Model): iname = models.CharField(max_length=20, unique=True) recipes = models.ManyToManyField(Recipe, through="RecipeIngredient") class RecipeIngredient(models.Model): ingredient = models.ForeignKey(Ingredient, models.CASCADE, to_field="iname") recipe = models.ForeignKey(Recipe, models.CASCADE, to_field="rname") # Model for #23839 class NotReferenced(models.Model): # Don't point any FK at this model. pass # Models for #23934 class ExplicitlyProvidedPK(models.Model): name = models.IntegerField(primary_key=True) class ImplicitlyGeneratedPK(models.Model): name = models.IntegerField(unique=True) # Models for #25622 class ReferencedByGenRel(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") class GenRelReference(models.Model): references = GenericRelation(ReferencedByGenRel) class ParentWithUUIDPK(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=100) def __str__(self): return str(self.id) class RelatedWithUUIDPKModel(models.Model): parent = models.ForeignKey( ParentWithUUIDPK, on_delete=models.SET_NULL, null=True, blank=True ) class Author(models.Model): pass class Authorship(models.Model): book = models.ForeignKey(Book, models.CASCADE) author = models.ForeignKey(Author, models.CASCADE) class UserProxy(User): """Proxy a model with a different app_label.""" class Meta: proxy = True class ReadOnlyRelatedField(models.Model): chapter = models.ForeignKey(Chapter, models.CASCADE) language = models.ForeignKey(Language, models.CASCADE) user = models.ForeignKey(User, models.CASCADE) class Héllo(models.Model): pass class Box(models.Model): title = models.CharField(max_length=100) next_box = models.ForeignKey( "self", null=True, on_delete=models.SET_NULL, blank=True ) next_box = models.ForeignKey( "self", null=True, on_delete=models.SET_NULL, blank=True ) class Country(models.Model): NORTH_AMERICA = "North America" SOUTH_AMERICA = "South America" EUROPE = "Europe" ASIA = "Asia" OCEANIA = "Oceania" ANTARCTICA = "Antarctica" CONTINENT_CHOICES = [ (NORTH_AMERICA, NORTH_AMERICA), (SOUTH_AMERICA, SOUTH_AMERICA), (EUROPE, EUROPE), (ASIA, ASIA), (OCEANIA, OCEANIA), (ANTARCTICA, ANTARCTICA), ] name = models.CharField(max_length=80) continent = models.CharField(max_length=13, choices=CONTINENT_CHOICES) def __str__(self): return self.name class Traveler(models.Model): born_country = models.ForeignKey(Country, models.CASCADE) living_country = models.ForeignKey( Country, models.CASCADE, related_name="living_country_set" ) favorite_country_to_vacation = models.ForeignKey( Country, models.CASCADE, related_name="favorite_country_to_vacation_set", limit_choices_to={"continent": Country.ASIA}, ) class Square(models.Model): side = models.IntegerField() area = models.GeneratedField( db_persist=True, expression=models.F("side") * models.F("side"), output_field=models.BigIntegerField(), ) class Meta: required_db_features = {"supports_stored_generated_columns"} class CamelCaseModel(models.Model): interesting_name = models.CharField(max_length=100) def __str__(self): return self.interesting_name class CamelCaseRelatedModel(models.Model): m2m = models.ManyToManyField(CamelCaseModel, related_name="m2m") fk = models.ForeignKey(CamelCaseModel, on_delete=models.CASCADE, related_name="fk")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_history_view.py
tests/admin_views/test_history_view.py
from django.contrib.admin.models import CHANGE, LogEntry from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import User from django.core.paginator import Paginator from django.test import TestCase, override_settings from django.urls import reverse from .models import City, State @override_settings(ROOT_URLCONF="admin_views.urls") class AdminHistoryViewTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) def setUp(self): self.client.force_login(self.superuser) def test_changed_message_uses_form_labels(self): """ Admin's model history change messages use form labels instead of field names. """ state = State.objects.create(name="My State Name") city = City.objects.create(name="My City Name", state=state) change_dict = { "name": "My State Name 2", "nolabel_form_field": True, "city_set-0-name": "My City name 2", "city_set-0-id": city.pk, "city_set-TOTAL_FORMS": "3", "city_set-INITIAL_FORMS": "1", "city_set-MAX_NUM_FORMS": "0", } state_change_url = reverse("admin:admin_views_state_change", args=(state.pk,)) self.client.post(state_change_url, change_dict) logentry = LogEntry.objects.filter(content_type__model__iexact="state").latest( "id" ) self.assertEqual( logentry.get_change_message(), "Changed State name (from form’s Meta.labels), " "nolabel_form_field and not_a_form_field. " "Changed City verbose_name for city “%s”." % city, ) @override_settings(ROOT_URLCONF="admin_views.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) for i in range(1, 1101): LogEntry.objects.log_actions( self.superuser.pk, [self.superuser], CHANGE, change_message=f"Changed something {i}", ) self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), ) def test_pagination(self): from selenium.webdriver.common.by import By user_history_url = reverse("admin:auth_user_history", args=(self.superuser.pk,)) self.selenium.get(self.live_server_url + user_history_url) paginator = self.selenium.find_element(By.CSS_SELECTOR, ".paginator") self.assertEqual(paginator.tag_name, "nav") labelledby = paginator.get_attribute("aria-labelledby") description = self.selenium.find_element(By.CSS_SELECTOR, "#%s" % labelledby) self.assertHTMLEqual( description.get_attribute("outerHTML"), '<h2 id="pagination" class="visually-hidden">Pagination user entries</h2>', ) self.assertTrue(paginator.is_displayed()) aria_current_link = paginator.find_elements(By.CSS_SELECTOR, "[aria-current]") self.assertEqual(len(aria_current_link), 1) # The current page. current_page_link = aria_current_link[0] self.assertEqual(current_page_link.get_attribute("aria-current"), "page") self.assertEqual(current_page_link.get_attribute("href"), "") self.assertIn("%s entries" % LogEntry.objects.count(), paginator.text) self.assertIn(str(Paginator.ELLIPSIS), paginator.text) self.assertEqual(current_page_link.text, "1") # The last page. last_page_link = self.selenium.find_element(By.XPATH, "//ul/li[last()]/a") self.assertTrue(last_page_link.text, "20") # Select the second page. pages = paginator.find_elements(By.TAG_NAME, "a") second_page_link = pages[1] self.assertEqual(second_page_link.text, "2") second_page_link.click() self.assertIn("?p=2", self.selenium.current_url) rows = self.selenium.find_elements(By.CSS_SELECTOR, "#change-history tbody tr") self.assertIn("Changed something 101", rows[0].text) self.assertIn("Changed something 200", rows[-1].text)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_skip_link_to_content.py
tests/admin_views/test_skip_link_to_content.py
from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import User from django.test import override_settings from django.urls import reverse from .models import Podcast @override_settings(ROOT_URLCONF="admin_views.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) def test_use_skip_link_to_content(self): from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), ) # `Skip link` is not present. skip_link = self.selenium.find_element(By.CLASS_NAME, "skip-to-content-link") self.assertFalse(skip_link.is_displayed()) # 1st TAB is pressed, `skip link` is shown. body = self.selenium.find_element(By.TAG_NAME, "body") body.send_keys(Keys.TAB) self.assertTrue(skip_link.is_displayed()) # Press RETURN to skip the navbar links (view site / documentation / # change password / log out) and focus first model in the admin_views # list. skip_link.send_keys(Keys.RETURN) self.assertFalse(skip_link.is_displayed()) # `skip link` disappear. keys = [Keys.TAB, Keys.TAB] # The 1st TAB is the section title. if self.browser == "firefox": # For some reason Firefox doesn't focus the section title # ('ADMIN_VIEWS'). keys.remove(Keys.TAB) body.send_keys(keys) actors_a_tag = self.selenium.find_element(By.LINK_TEXT, "Actors") self.assertEqual(self.selenium.switch_to.active_element, actors_a_tag) # Go to Actors changelist, skip sidebar and focus "Add actor +". with self.wait_page_loaded(): actors_a_tag.send_keys(Keys.RETURN) body = self.selenium.find_element(By.TAG_NAME, "body") body.send_keys(Keys.TAB) skip_link = self.selenium.find_element(By.CLASS_NAME, "skip-to-content-link") self.assertTrue(skip_link.is_displayed()) ActionChains(self.selenium).send_keys(Keys.RETURN, Keys.TAB).perform() actors_add_url = reverse("admin:admin_views_actor_add") actors_a_tag = self.selenium.find_element( By.CSS_SELECTOR, f"#content [href='{actors_add_url}']" ) self.assertEqual(self.selenium.switch_to.active_element, actors_a_tag) # Go to the Actor form and the first input will be focused # automatically. with self.wait_page_loaded(): actors_a_tag.send_keys(Keys.RETURN) first_input = self.selenium.find_element(By.ID, "id_name") self.assertEqual(self.selenium.switch_to.active_element, first_input) def test_dont_use_skip_link_to_content(self): from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), ) # `Skip link` is not present. skip_link = self.selenium.find_element(By.CLASS_NAME, "skip-to-content-link") self.assertFalse(skip_link.is_displayed()) # 1st TAB is pressed, `skip link` is shown. body = self.selenium.find_element(By.TAG_NAME, "body") body.send_keys(Keys.TAB) self.assertTrue(skip_link.is_displayed()) # The 2nd TAB will focus the page title. body.send_keys(Keys.TAB) django_administration_title = self.selenium.find_element( By.LINK_TEXT, "Django administration" ) self.assertFalse(skip_link.is_displayed()) # `skip link` disappear. self.assertEqual( self.selenium.switch_to.active_element, django_administration_title ) def test_skip_link_with_RTL_language_doesnt_create_horizontal_scrolling(self): from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys with override_settings(LANGUAGE_CODE="ar"): self.admin_login( username="super", password="secret", login_url=reverse("admin:index"), ) skip_link = self.selenium.find_element( By.CLASS_NAME, "skip-to-content-link" ) body = self.selenium.find_element(By.TAG_NAME, "body") body.send_keys(Keys.TAB) self.assertTrue(skip_link.is_displayed()) is_vertical_scrolleable = self.selenium.execute_script( "return arguments[0].scrollHeight > arguments[0].offsetHeight;", body ) is_horizontal_scrolleable = self.selenium.execute_script( "return arguments[0].scrollWeight > arguments[0].offsetWeight;", body ) self.assertTrue(is_vertical_scrolleable) self.assertFalse(is_horizontal_scrolleable) def test_skip_link_keyboard_navigation_in_changelist(self): from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys Podcast.objects.create(name="apple", release_date="2000-09-19") self.admin_login( username="super", password="secret", login_url=reverse("admin:index") ) self.selenium.get( self.live_server_url + reverse("admin:admin_views_podcast_changelist") ) selectors = [ "ul.object-tools", # object_tools. "search#changelist-filter", # list_filter. "form#changelist-search", # search_fields. "nav.toplinks", # date_hierarchy. "form#changelist-form div.actions", # action. "table#result_list", # table. "div.changelist-footer", # footer. ] content = self.selenium.find_element(By.ID, "content-start") content.send_keys(Keys.TAB) for selector in selectors: with self.subTest(selector=selector): # Currently focused element. focused_element = self.selenium.switch_to.active_element expected_element = self.selenium.find_element(By.CSS_SELECTOR, selector) element_points = self.selenium.find_elements( By.CSS_SELECTOR, f"{selector} a, {selector} input, {selector} button", ) self.assertIn( focused_element.get_attribute("outerHTML"), expected_element.get_attribute("innerHTML"), ) # Move to the next container element via TAB. for point in element_points[::-1]: if point.is_displayed(): point.send_keys(Keys.TAB) break
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_templatetags.py
tests/admin_views/test_templatetags.py
import datetime import unittest from django.contrib.admin import ModelAdmin from django.contrib.admin.templatetags.admin_list import date_hierarchy from django.contrib.admin.templatetags.admin_modify import submit_row from django.contrib.admin.templatetags.base import InclusionAdminNode from django.contrib.auth import get_permission_codename from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.template.base import Token, TokenType from django.test import RequestFactory, TestCase from django.urls import reverse from django.utils.version import PY314 from .admin import ArticleAdmin, site from .models import Article, Question from .tests import AdminViewBasicTestCase, get_perm class AdminTemplateTagsTest(AdminViewBasicTestCase): request_factory = RequestFactory() def test_submit_row(self): """ submit_row template tag should pass whole context. """ request = self.request_factory.get( reverse("admin:auth_user_change", args=[self.superuser.pk]) ) request.user = self.superuser admin = UserAdmin(User, site) extra_context = {"extra": True} response = admin.change_view( request, str(self.superuser.pk), extra_context=extra_context ) template_context = submit_row(response.context_data) self.assertIs(template_context["extra"], True) self.assertIs(template_context["show_save"], True) def test_submit_row_save_as_new_add_permission_required(self): change_user = User.objects.create_user( username="change_user", password="secret", is_staff=True ) change_user.user_permissions.add( get_perm(User, get_permission_codename("change", User._meta)), ) request = self.request_factory.get( reverse("admin:auth_user_change", args=[self.superuser.pk]) ) request.user = change_user admin = UserAdmin(User, site) admin.save_as = True response = admin.change_view(request, str(self.superuser.pk)) template_context = submit_row(response.context_data) self.assertIs(template_context["show_save_as_new"], False) add_user = User.objects.create_user( username="add_user", password="secret", is_staff=True ) add_user.user_permissions.add( get_perm(User, get_permission_codename("add", User._meta)), get_perm(User, get_permission_codename("change", User._meta)), ) request = self.request_factory.get( reverse("admin:auth_user_change", args=[self.superuser.pk]) ) request.user = add_user response = admin.change_view(request, str(self.superuser.pk)) template_context = submit_row(response.context_data) self.assertIs(template_context["show_save_as_new"], True) def test_override_show_save_and_add_another(self): request = self.request_factory.get( reverse("admin:auth_user_change", args=[self.superuser.pk]), ) request.user = self.superuser admin = UserAdmin(User, site) for extra_context, expected_flag in ( ({}, True), # Default. ({"show_save_and_add_another": False}, False), ): with self.subTest(show_save_and_add_another=expected_flag): response = admin.change_view( request, str(self.superuser.pk), extra_context=extra_context, ) template_context = submit_row(response.context_data) self.assertIs( template_context["show_save_and_add_another"], expected_flag ) def test_override_change_form_template_tags(self): """ admin_modify template tags follow the standard search pattern admin/app_label/model/template.html. """ article = Article.objects.all()[0] request = self.request_factory.get( reverse("admin:admin_views_article_change", args=[article.pk]) ) request.user = self.superuser admin = ArticleAdmin(Article, site) extra_context = {"show_publish": True, "extra": True} response = admin.change_view( request, str(article.pk), extra_context=extra_context ) response.render() self.assertIs(response.context_data["show_publish"], True) self.assertIs(response.context_data["extra"], True) self.assertContains(response, 'name="_save"') self.assertContains(response, 'name="_publish"') self.assertContains(response, "override-change_form_object_tools") self.assertContains(response, "override-prepopulated_fields_js") def test_override_change_list_template_tags(self): """ admin_list template tags follow the standard search pattern admin/app_label/model/template.html. """ request = self.request_factory.get( reverse("admin:admin_views_article_changelist") ) request.user = self.superuser admin = ArticleAdmin(Article, site) admin.date_hierarchy = "date" admin.search_fields = ("title", "content") response = admin.changelist_view(request) response.render() self.assertContains(response, "override-actions") self.assertContains(response, "override-change_list_object_tools") self.assertContains(response, "override-change_list_results") self.assertContains(response, "override-date_hierarchy") self.assertContains(response, "override-pagination") self.assertContains(response, "override-search_form") @unittest.skipUnless(PY314, "Deferred annotations are Python 3.14+ only") def test_inclusion_admin_node_deferred_annotation(self): def action(arg: SomeType = None): # NOQA: F821 pass # This used to raise TypeError via the underlying call to # inspect.getfullargspec(), which is not ready for deferred # evaluation of annotations. InclusionAdminNode( "test", parser=object(), token=Token(token_type=TokenType.TEXT, contents="a"), func=action, template_name="test.html", takes_context=False, ) class DateHierarchyTests(TestCase): factory = RequestFactory() @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) def test_choice_links(self): modeladmin = ModelAdmin(Question, site) modeladmin.date_hierarchy = "posted" posted_dates = ( datetime.date(2017, 10, 1), datetime.date(2017, 10, 1), datetime.date(2017, 12, 15), datetime.date(2017, 12, 15), datetime.date(2017, 12, 31), datetime.date(2018, 2, 1), ) Question.objects.bulk_create( Question(question="q", posted=posted) for posted in posted_dates ) tests = ( ({}, [["year=2017"], ["year=2018"]]), ({"year": 2016}, []), ({"year": 2017}, [["month=10", "year=2017"], ["month=12", "year=2017"]]), ({"year": 2017, "month": 9}, []), ( {"year": 2017, "month": 12}, [ ["day=15", "month=12", "year=2017"], ["day=31", "month=12", "year=2017"], ], ), ) for query, expected_choices in tests: with self.subTest(query=query): query = {"posted__%s" % q: val for q, val in query.items()} request = self.factory.get("/", query) request.user = self.superuser changelist = modeladmin.get_changelist_instance(request) spec = date_hierarchy(changelist) choices = [choice["link"] for choice in spec["choices"]] expected_choices = [ "&".join("posted__%s" % c for c in choice) for choice in expected_choices ] expected_choices = [ ("?" + choice) if choice else "" for choice in expected_choices ] self.assertEqual(choices, expected_choices) def test_choice_links_datetime(self): modeladmin = ModelAdmin(Question, site) modeladmin.date_hierarchy = "expires" Question.objects.bulk_create( [ Question(question="q1", expires=datetime.datetime(2017, 10, 1)), Question(question="q2", expires=datetime.datetime(2017, 10, 1)), Question(question="q3", expires=datetime.datetime(2017, 12, 15)), Question(question="q4", expires=datetime.datetime(2017, 12, 15)), Question(question="q5", expires=datetime.datetime(2017, 12, 31)), Question(question="q6", expires=datetime.datetime(2018, 2, 1)), ] ) tests = [ ({}, [["year=2017"], ["year=2018"]]), ({"year": 2016}, []), ( {"year": 2017}, [ ["month=10", "year=2017"], ["month=12", "year=2017"], ], ), ({"year": 2017, "month": 9}, []), ( {"year": 2017, "month": 12}, [ ["day=15", "month=12", "year=2017"], ["day=31", "month=12", "year=2017"], ], ), ] for query, expected_choices in tests: with self.subTest(query=query): query = {"expires__%s" % q: val for q, val in query.items()} request = self.factory.get("/", query) request.user = self.superuser changelist = modeladmin.get_changelist_instance(request) spec = date_hierarchy(changelist) choices = [choice["link"] for choice in spec["choices"]] expected_choices = [ "?" + "&".join("expires__%s" % c for c in choice) for choice in expected_choices ] self.assertEqual(choices, expected_choices)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_autocomplete_view.py
tests/admin_views/test_autocomplete_view.py
import datetime import json from contextlib import contextmanager from django.contrib import admin from django.contrib.admin.exceptions import NotRegistered from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.admin.views.autocomplete import AutocompleteJsonView from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.core.exceptions import PermissionDenied from django.http import Http404 from django.test import RequestFactory, override_settings from django.urls import reverse, reverse_lazy from .admin import AnswerAdmin, QuestionAdmin from .models import ( Answer, Author, Authorship, Bonus, Book, Employee, Manager, Parent, PKChild, Question, Toy, WorkHour, ) from .tests import AdminViewBasicTestCase PAGINATOR_SIZE = AutocompleteJsonView.paginate_by class AuthorAdmin(admin.ModelAdmin): ordering = ["id"] search_fields = ["id"] class AuthorshipInline(admin.TabularInline): model = Authorship autocomplete_fields = ["author"] class BookAdmin(admin.ModelAdmin): inlines = [AuthorshipInline] site = admin.AdminSite(name="autocomplete_admin") site.register(Question, QuestionAdmin) site.register(Answer, AnswerAdmin) site.register(Author, AuthorAdmin) site.register(Book, BookAdmin) site.register(Employee, search_fields=["name"]) site.register(WorkHour, autocomplete_fields=["employee"]) site.register(Manager, search_fields=["name"]) site.register(Bonus, autocomplete_fields=["recipient"]) site.register(PKChild, search_fields=["name"]) site.register(Toy, autocomplete_fields=["child"]) @contextmanager def model_admin(model, model_admin, admin_site=site): try: org_admin = admin_site.get_model_admin(model) except NotRegistered: org_admin = None else: admin_site.unregister(model) admin_site.register(model, model_admin) try: yield finally: if org_admin: admin_site._registry[model] = org_admin class AutocompleteJsonViewTests(AdminViewBasicTestCase): as_view_args = {"admin_site": site} opts = { "app_label": Answer._meta.app_label, "model_name": Answer._meta.model_name, "field_name": "question", } factory = RequestFactory() url = reverse_lazy("autocomplete_admin:autocomplete") @classmethod def setUpTestData(cls): cls.user = User.objects.create_user( username="user", password="secret", email="user@example.com", is_staff=True, ) super().setUpTestData() def test_success(self): q = Question.objects.create(question="Is this a question?") request = self.factory.get(self.url, {"term": "is", **self.opts}) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.text) self.assertEqual( data, { "results": [{"id": str(q.pk), "text": q.question}], "pagination": {"more": False}, }, ) def test_custom_to_field(self): q = Question.objects.create(question="Is this a question?") request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "question_with_to_field"}, ) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.text) self.assertEqual( data, { "results": [{"id": str(q.uuid), "text": q.question}], "pagination": {"more": False}, }, ) def test_custom_to_field_permission_denied(self): Question.objects.create(question="Is this a question?") request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "question_with_to_field"}, ) request.user = self.user with self.assertRaises(PermissionDenied): AutocompleteJsonView.as_view(**self.as_view_args)(request) def test_custom_to_field_custom_pk(self): q = Question.objects.create(question="Is this a question?") opts = { "app_label": Question._meta.app_label, "model_name": Question._meta.model_name, "field_name": "related_questions", } request = self.factory.get(self.url, {"term": "is", **opts}) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.text) self.assertEqual( data, { "results": [{"id": str(q.big_id), "text": q.question}], "pagination": {"more": False}, }, ) def test_to_field_resolution_with_mti(self): """ to_field resolution should correctly resolve for target models using MTI. Tests for single and multi-level cases. """ tests = [ (Employee, WorkHour, "employee"), (Manager, Bonus, "recipient"), ] for Target, Remote, related_name in tests: with self.subTest( target_model=Target, remote_model=Remote, related_name=related_name ): o = Target.objects.create( name="Frida Kahlo", gender=2, code="painter", alive=False ) opts = { "app_label": Remote._meta.app_label, "model_name": Remote._meta.model_name, "field_name": related_name, } request = self.factory.get(self.url, {"term": "frida", **opts}) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.text) self.assertEqual( data, { "results": [{"id": str(o.pk), "text": o.name}], "pagination": {"more": False}, }, ) def test_to_field_resolution_with_fk_pk(self): p = Parent.objects.create(name="Bertie") c = PKChild.objects.create(parent=p, name="Anna") opts = { "app_label": Toy._meta.app_label, "model_name": Toy._meta.model_name, "field_name": "child", } request = self.factory.get(self.url, {"term": "anna", **opts}) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.text) self.assertEqual( data, { "results": [{"id": str(c.pk), "text": c.name}], "pagination": {"more": False}, }, ) def test_field_does_not_exist(self): request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "does_not_exist"} ) request.user = self.superuser with self.assertRaises(PermissionDenied): AutocompleteJsonView.as_view(**self.as_view_args)(request) def test_field_no_related_field(self): request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "answer"} ) request.user = self.superuser with self.assertRaises(PermissionDenied): AutocompleteJsonView.as_view(**self.as_view_args)(request) def test_field_does_not_allowed(self): request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "related_questions"} ) request.user = self.superuser with self.assertRaises(PermissionDenied): AutocompleteJsonView.as_view(**self.as_view_args)(request) def test_limit_choices_to(self): # Answer.question_with_to_field defines limit_choices_to to "those not # starting with 'not'". q = Question.objects.create(question="Is this a question?") Question.objects.create(question="Not a question.") request = self.factory.get( self.url, {"term": "is", **self.opts, "field_name": "question_with_to_field"}, ) request.user = self.superuser response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.text) self.assertEqual( data, { "results": [{"id": str(q.uuid), "text": q.question}], "pagination": {"more": False}, }, ) def test_must_be_logged_in(self): response = self.client.get(self.url, {"term": "", **self.opts}) self.assertEqual(response.status_code, 200) self.client.logout() response = self.client.get(self.url, {"term": "", **self.opts}) self.assertEqual(response.status_code, 302) def test_has_view_or_change_permission_required(self): """ Users require the change permission for the related model to the autocomplete view for it. """ request = self.factory.get(self.url, {"term": "is", **self.opts}) request.user = self.user with self.assertRaises(PermissionDenied): AutocompleteJsonView.as_view(**self.as_view_args)(request) for permission in ("view", "change"): with self.subTest(permission=permission): self.user.user_permissions.clear() p = Permission.objects.get( content_type=ContentType.objects.get_for_model(Question), codename="%s_question" % permission, ) self.user.user_permissions.add(p) request.user = User.objects.get(pk=self.user.pk) response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) def test_search_use_distinct(self): """ Searching across model relations use QuerySet.distinct() to avoid duplicates. """ q1 = Question.objects.create(question="question 1") q2 = Question.objects.create(question="question 2") q2.related_questions.add(q1) q3 = Question.objects.create(question="question 3") q3.related_questions.add(q1) request = self.factory.get(self.url, {"term": "question", **self.opts}) request.user = self.superuser class DistinctQuestionAdmin(QuestionAdmin): search_fields = ["related_questions__question", "question"] with model_admin(Question, DistinctQuestionAdmin): response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.text) self.assertEqual(len(data["results"]), 3) def test_missing_search_fields(self): class EmptySearchAdmin(QuestionAdmin): search_fields = [] with model_admin(Question, EmptySearchAdmin): msg = "EmptySearchAdmin must have search_fields for the autocomplete_view." with self.assertRaisesMessage(Http404, msg): site.autocomplete_view( self.factory.get(self.url, {"term": "", **self.opts}) ) def test_get_paginator(self): """Search results are paginated.""" class PKOrderingQuestionAdmin(QuestionAdmin): ordering = ["pk"] Question.objects.bulk_create( Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10) ) # The first page of results. request = self.factory.get(self.url, {"term": "", **self.opts}) request.user = self.superuser with model_admin(Question, PKOrderingQuestionAdmin): response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.text) self.assertEqual( data, { "results": [ {"id": str(q.pk), "text": q.question} for q in Question.objects.all()[:PAGINATOR_SIZE] ], "pagination": {"more": True}, }, ) # The second page of results. request = self.factory.get(self.url, {"term": "", "page": "2", **self.opts}) request.user = self.superuser with model_admin(Question, PKOrderingQuestionAdmin): response = AutocompleteJsonView.as_view(**self.as_view_args)(request) self.assertEqual(response.status_code, 200) data = json.loads(response.text) self.assertEqual( data, { "results": [ {"id": str(q.pk), "text": q.question} for q in Question.objects.all()[PAGINATOR_SIZE:] ], "pagination": {"more": False}, }, ) def test_serialize_result(self): class AutocompleteJsonSerializeResultView(AutocompleteJsonView): def serialize_result(self, obj, to_field_name): return { **super().serialize_result(obj, to_field_name), "posted": str(obj.posted), } Question.objects.create(question="Question 1", posted=datetime.date(2021, 8, 9)) Question.objects.create(question="Question 2", posted=datetime.date(2021, 8, 7)) request = self.factory.get(self.url, {"term": "question", **self.opts}) request.user = self.superuser response = AutocompleteJsonSerializeResultView.as_view(**self.as_view_args)( request ) self.assertEqual(response.status_code, 200) data = json.loads(response.text) self.assertEqual( data, { "results": [ {"id": str(q.pk), "text": q.question, "posted": str(q.posted)} for q in Question.objects.order_by("-posted") ], "pagination": {"more": False}, }, ) @override_settings(ROOT_URLCONF="admin_views.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) self.admin_login( username="super", password="secret", login_url=reverse("autocomplete_admin:index"), ) @contextmanager def select2_ajax_wait(self, timeout=10): from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as ec yield with self.disable_implicit_wait(): try: loading_element = self.selenium.find_element( By.CSS_SELECTOR, "li.select2-results__option.loading-results" ) except NoSuchElementException: pass else: self.wait_until(ec.staleness_of(loading_element), timeout=timeout) def test_select(self): from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select self.selenium.get( self.live_server_url + reverse("autocomplete_admin:admin_views_answer_add") ) elem = self.selenium.find_element(By.CSS_SELECTOR, ".select2-selection") with self.select2_ajax_wait(): elem.click() # Open the autocomplete dropdown. results = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results") self.assertTrue(results.is_displayed()) option = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results__option") self.assertEqual(option.text, "No results found") with self.select2_ajax_wait(): elem.click() # Close the autocomplete dropdown. q1 = Question.objects.create(question="Who am I?") Question.objects.bulk_create( Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10) ) with self.select2_ajax_wait(): elem.click() # Reopen the dropdown now that some objects exist. result_container = self.selenium.find_element( By.CSS_SELECTOR, ".select2-results" ) self.assertTrue(result_container.is_displayed()) # PAGINATOR_SIZE results and "Loading more results". self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 1, root_element=result_container, ) search = self.selenium.find_element(By.CSS_SELECTOR, ".select2-search__field") # Load next page of results by scrolling to the bottom of the list. for _ in range(PAGINATOR_SIZE + 1): with self.select2_ajax_wait(): search.send_keys(Keys.ARROW_DOWN) # All objects are now loaded. self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 11, root_element=result_container, ) # Limit the results with the search field. with self.select2_ajax_wait(): search.send_keys("Who") # Ajax request is delayed. self.assertTrue(result_container.is_displayed()) self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 12, root_element=result_container, ) self.assertTrue(result_container.is_displayed()) self.assertCountSeleniumElements( ".select2-results__option", 1, root_element=result_container ) # Select the result. with self.select2_ajax_wait(): search.send_keys(Keys.RETURN) select = Select(self.selenium.find_element(By.ID, "id_question")) self.assertEqual( select.first_selected_option.get_attribute("value"), str(q1.pk) ) def test_select_multiple(self): from selenium.common import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select self.selenium.get( self.live_server_url + reverse("autocomplete_admin:admin_views_question_add") ) elem = self.selenium.find_element(By.CSS_SELECTOR, ".select2-selection") with self.select2_ajax_wait(): elem.click() # Open the autocomplete dropdown. results = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results") self.assertTrue(results.is_displayed()) option = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results__option") self.assertEqual(option.text, "No results found") with self.select2_ajax_wait(): elem.click() # Close the autocomplete dropdown. Question.objects.create(question="Who am I?") Question.objects.bulk_create( Question(question=str(i)) for i in range(PAGINATOR_SIZE + 10) ) with self.select2_ajax_wait(): elem.click() # Reopen the dropdown now that some objects exist. result_container = self.selenium.find_element( By.CSS_SELECTOR, ".select2-results" ) self.assertIs(result_container.is_displayed(), True) self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 1, root_element=result_container, ) search = self.selenium.find_element(By.CSS_SELECTOR, ".select2-search__field") # Load next page of results by scrolling to the bottom of the list. for _ in range(PAGINATOR_SIZE + 1): with self.select2_ajax_wait(): search.send_keys(Keys.ARROW_DOWN) self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 11, root_element=result_container, ) # Limit the results with the search field. with self.select2_ajax_wait(): search.send_keys("Who") # Ajax request is delayed. self.assertIs(result_container.is_displayed(), True) self.assertCountSeleniumElements( ".select2-results__option", PAGINATOR_SIZE + 12, root_element=result_container, ) self.assertIs(result_container.is_displayed(), True) self.assertCountSeleniumElements( ".select2-results__option", 1, root_element=result_container ) with self.select2_ajax_wait(): # Select the result. search.send_keys(Keys.RETURN) with self.disable_implicit_wait(): with self.assertRaises(NoSuchElementException): self.selenium.find_element(By.CSS_SELECTOR, ".select2-results") with self.select2_ajax_wait(): # Reopen the dropdown. elem.click() result_container = self.selenium.find_element( By.CSS_SELECTOR, ".select2-results" ) self.assertIs(result_container.is_displayed(), True) with self.select2_ajax_wait(): # Add the first result to the selection. search.send_keys(Keys.ARROW_DOWN) search.send_keys(Keys.RETURN) select = Select(self.selenium.find_element(By.ID, "id_related_questions")) self.assertEqual(len(select.all_selected_options), 2) def test_inline_add_another_widgets(self): from selenium.webdriver.common.by import By def assertNoResults(row): elem = row.find_element(By.CSS_SELECTOR, ".select2-selection") with self.select2_ajax_wait(): elem.click() # Open the autocomplete dropdown. results = self.selenium.find_element(By.CSS_SELECTOR, ".select2-results") self.assertTrue(results.is_displayed()) option = self.selenium.find_element( By.CSS_SELECTOR, ".select2-results__option" ) self.assertEqual(option.text, "No results found") # Autocomplete works in rows present when the page loads. self.selenium.get( self.live_server_url + reverse("autocomplete_admin:admin_views_book_add") ) rows = self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-authorship_set") self.assertEqual(len(rows), 3) assertNoResults(rows[0]) # Autocomplete works in rows added using the "Add another" button. self.selenium.find_element(By.LINK_TEXT, "Add another Authorship").click() rows = self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-authorship_set") self.assertEqual(len(rows), 4) assertNoResults(rows[-1])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/__init__.py
tests/admin_views/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/tests.py
tests/admin_views/tests.py
import datetime import os import re import unittest import zoneinfo from unittest import mock from urllib.parse import parse_qsl, urljoin, urlsplit from django import forms from django.contrib import admin from django.contrib.admin import AdminSite, ModelAdmin from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.models import ADDITION, DELETION, LogEntry from django.contrib.admin.options import TO_FIELD_VAR from django.contrib.admin.templatetags.admin_urls import add_preserved_filters from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.admin.utils import quote from django.contrib.admin.views.main import IS_POPUP_VAR from django.contrib.auth import REDIRECT_FIELD_NAME, get_permission_codename from django.contrib.auth.admin import UserAdmin from django.contrib.auth.forms import AdminPasswordChangeForm from django.contrib.auth.models import Group, Permission, User from django.contrib.contenttypes.models import ContentType from django.core import mail from django.core.checks import Error from django.core.files import temp as tempfile from django.forms.utils import ErrorList from django.template.response import TemplateResponse from django.test import ( RequestFactory, TestCase, modify_settings, override_settings, skipUnlessDBFeature, ) from django.test.selenium import screenshot_cases from django.test.utils import override_script_prefix from django.urls import NoReverseMatch, resolve, reverse from django.utils import formats, translation from django.utils.cache import get_max_age from django.utils.encoding import iri_to_uri from django.utils.html import escape from django.utils.http import urlencode from . import customadmin from .admin import CityAdmin, site, site2 from .models import ( Actor, AdminOrderedAdminMethod, AdminOrderedCallable, AdminOrderedField, AdminOrderedModelMethod, Album, Answer, Answer2, Article, BarAccount, Book, Bookmark, Box, Category, Chapter, ChapterXtra1, ChapterXtra2, Character, Child, Choice, City, Collector, Color, ComplexSortedPerson, Country, Course, CoverLetter, CustomArticle, CyclicOne, CyclicTwo, DooHickey, Employee, EmptyModel, Fabric, FancyDoodad, FieldOverridePost, FilteredManager, FooAccount, FoodDelivery, FunkyTag, Gallery, Grommet, Inquisition, Language, Link, MainPrepopulated, Media, ModelWithStringPrimaryKey, OtherStory, Paper, Parent, ParentWithDependentChildren, ParentWithUUIDPK, Person, Persona, Picture, Pizza, Plot, PlotDetails, PluggableSearchPerson, Podcast, Post, PrePopulatedPost, Promo, Question, ReadablePizza, ReadOnlyPizza, ReadOnlyRelatedField, Recommendation, Recommender, RelatedPrepopulated, RelatedWithUUIDPKModel, Report, Restaurant, RowLevelChangePermissionModel, SecretHideout, Section, ShortMessage, Simple, Song, State, Story, Subscriber, SuperSecretHideout, SuperVillain, Telegram, TitleTranslation, Topping, Traveler, UnchangeableObject, UndeletableObject, UnorderedObject, UserMessenger, UserProxy, Villain, Vodcast, Whatsit, Widget, Worker, WorkHour, ) ERROR_MESSAGE = "Please enter the correct username and password \ for a staff account. Note that both fields may be case-sensitive." MULTIPART_ENCTYPE = 'enctype="multipart/form-data"' def make_aware_datetimes(dt, iana_key): """Makes one aware datetime for each supported time zone provider.""" yield dt.replace(tzinfo=zoneinfo.ZoneInfo(iana_key)) class AdminFieldExtractionMixin: """ Helper methods for extracting data from AdminForm. """ def get_admin_form_fields(self, response): """ Return a list of AdminFields for the AdminForm in the response. """ fields = [] for fieldset in response.context["adminform"]: for field_line in fieldset: fields.extend(field_line) return fields def get_admin_readonly_fields(self, response): """ Return the readonly fields for the response's AdminForm. """ return [f for f in self.get_admin_form_fields(response) if f.is_readonly] def get_admin_readonly_field(self, response, field_name): """ Return the readonly field for the given field_name. """ admin_readonly_fields = self.get_admin_readonly_fields(response) for field in admin_readonly_fields: if field.field["name"] == field_name: return field @override_settings(ROOT_URLCONF="admin_views.urls", USE_I18N=True, LANGUAGE_CODE="en") class AdminViewBasicTestCase(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com" ) cls.s1 = Section.objects.create(name="Test section") cls.a1 = Article.objects.create( content="<p>Middle content</p>", date=datetime.datetime(2008, 3, 18, 11, 54, 58), section=cls.s1, title="Article 1", ) cls.a2 = Article.objects.create( content="<p>Oldest content</p>", date=datetime.datetime(2000, 3, 18, 11, 54, 58), section=cls.s1, title="Article 2", ) cls.a3 = Article.objects.create( content="<p>Newest content</p>", date=datetime.datetime(2009, 3, 18, 11, 54, 58), section=cls.s1, ) cls.p1 = PrePopulatedPost.objects.create( title="A Long Title", published=True, slug="a-long-title" ) cls.color1 = Color.objects.create(value="Red", warm=True) cls.color2 = Color.objects.create(value="Orange", warm=True) cls.color3 = Color.objects.create(value="Blue", warm=False) cls.color4 = Color.objects.create(value="Green", warm=False) cls.fab1 = Fabric.objects.create(surface="x") cls.fab2 = Fabric.objects.create(surface="y") cls.fab3 = Fabric.objects.create(surface="plain") cls.b1 = Book.objects.create(name="Book 1") cls.b2 = Book.objects.create(name="Book 2") cls.pro1 = Promo.objects.create(name="Promo 1", book=cls.b1) cls.pro1 = Promo.objects.create(name="Promo 2", book=cls.b2) cls.chap1 = Chapter.objects.create( title="Chapter 1", content="[ insert contents here ]", book=cls.b1 ) cls.chap2 = Chapter.objects.create( title="Chapter 2", content="[ insert contents here ]", book=cls.b1 ) cls.chap3 = Chapter.objects.create( title="Chapter 1", content="[ insert contents here ]", book=cls.b2 ) cls.chap4 = Chapter.objects.create( title="Chapter 2", content="[ insert contents here ]", book=cls.b2 ) cls.cx1 = ChapterXtra1.objects.create(chap=cls.chap1, xtra="ChapterXtra1 1") cls.cx2 = ChapterXtra1.objects.create(chap=cls.chap3, xtra="ChapterXtra1 2") Actor.objects.create(name="Palin", age=27) # Post data for edit inline cls.inline_post_data = { "name": "Test section", # inline data "article_set-TOTAL_FORMS": "6", "article_set-INITIAL_FORMS": "3", "article_set-MAX_NUM_FORMS": "0", "article_set-0-id": cls.a1.pk, # there is no title in database, give one here or formset will # fail. "article_set-0-title": "Norske bostaver æøå skaper problemer", "article_set-0-content": "&lt;p&gt;Middle content&lt;/p&gt;", "article_set-0-date_0": "2008-03-18", "article_set-0-date_1": "11:54:58", "article_set-0-section": cls.s1.pk, "article_set-1-id": cls.a2.pk, "article_set-1-title": "Need a title.", "article_set-1-content": "&lt;p&gt;Oldest content&lt;/p&gt;", "article_set-1-date_0": "2000-03-18", "article_set-1-date_1": "11:54:58", "article_set-2-id": cls.a3.pk, "article_set-2-title": "Need a title.", "article_set-2-content": "&lt;p&gt;Newest content&lt;/p&gt;", "article_set-2-date_0": "2009-03-18", "article_set-2-date_1": "11:54:58", "article_set-3-id": "", "article_set-3-title": "", "article_set-3-content": "", "article_set-3-date_0": "", "article_set-3-date_1": "", "article_set-4-id": "", "article_set-4-title": "", "article_set-4-content": "", "article_set-4-date_0": "", "article_set-4-date_1": "", "article_set-5-id": "", "article_set-5-title": "", "article_set-5-content": "", "article_set-5-date_0": "", "article_set-5-date_1": "", } def setUp(self): self.client.force_login(self.superuser) def assertContentBefore(self, response, text1, text2, failing_msg=None): """ Testing utility asserting that text1 appears before text2 in response content. """ self.assertEqual(response.status_code, 200) self.assertLess( response.content.index(text1.encode()), response.content.index(text2.encode()), (failing_msg or "") + "\nResponse:\n" + response.text, ) class AdminViewBasicTest(AdminViewBasicTestCase): def test_trailing_slash_required(self): """ If you leave off the trailing slash, app should redirect and add it. """ add_url = reverse("admin:admin_views_article_add") response = self.client.get(add_url[:-1]) self.assertRedirects(response, add_url, status_code=301) def test_basic_add_GET(self): """ A smoke test to ensure GET on the add_view works. """ response = self.client.get(reverse("admin:admin_views_section_add")) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_add_with_GET_args(self): response = self.client.get( reverse("admin:admin_views_section_add"), {"name": "My Section"} ) self.assertContains( response, 'value="My Section"', msg_prefix="Couldn't find an input with the right value in the response", ) def test_add_query_string_persists(self): save_options = [ {"_addanother": "1"}, # "Save and add another". {"_continue": "1"}, # "Save and continue editing". {"_saveasnew": "1"}, # "Save as new". ] other_options = [ "", "_changelist_filters=is_staff__exact%3D0", f"{IS_POPUP_VAR}=1", f"{TO_FIELD_VAR}=id", ] url = reverse("admin:auth_user_add") for i, save_option in enumerate(save_options): for j, other_option in enumerate(other_options): with self.subTest(save_option=save_option, other_option=other_option): qsl = "username=newuser" if other_option: qsl = f"{qsl}&{other_option}" response = self.client.post( f"{url}?{qsl}", { "username": f"newuser{i}{j}", "password1": "newpassword", "password2": "newpassword", **save_option, }, ) parsed_url = urlsplit(response.url) self.assertEqual(parsed_url.query, qsl) def test_change_query_string_persists(self): save_options = [ {"_addanother": "1"}, # "Save and add another". {"_continue": "1"}, # "Save and continue editing". ] other_options = [ "", "_changelist_filters=warm%3D1", f"{IS_POPUP_VAR}=1", f"{TO_FIELD_VAR}=id", ] url = reverse("admin:admin_views_color_change", args=(self.color1.pk,)) for save_option in save_options: for other_option in other_options: with self.subTest(save_option=save_option, other_option=other_option): qsl = "value=blue" if other_option: qsl = f"{qsl}&{other_option}" response = self.client.post( f"{url}?{qsl}", { "value": "gold", "warm": True, **save_option, }, ) parsed_url = urlsplit(response.url) self.assertEqual(parsed_url.query, qsl) def test_basic_edit_GET(self): """ A smoke test to ensure GET on the change_view works. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_basic_edit_GET_string_PK(self): """ GET on the change_view (when passing a string as the PK argument for a model with an integer PK field) redirects to the index page with a message saying the object doesn't exist. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(quote("abc/<b>"),)), follow=True, ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["section with ID “abc/<b>” doesn’t exist. Perhaps it was deleted?"], ) def test_basic_edit_GET_old_url_redirect(self): """ The change URL changed in Django 1.9, but the old one still redirects. """ response = self.client.get( reverse("admin:admin_views_section_change", args=(self.s1.pk,)).replace( "change/", "" ) ) self.assertRedirects( response, reverse("admin:admin_views_section_change", args=(self.s1.pk,)) ) def test_basic_inheritance_GET_string_PK(self): """ GET on the change_view (for inherited models) redirects to the index page with a message saying the object doesn't exist. """ response = self.client.get( reverse("admin:admin_views_supervillain_change", args=("abc",)), follow=True ) self.assertRedirects(response, reverse("admin:index")) self.assertEqual( [m.message for m in response.context["messages"]], ["super villain with ID “abc” doesn’t exist. Perhaps it was deleted?"], ) def test_basic_add_POST(self): """ A smoke test to ensure POST on add_view works. """ post_data = { "name": "Another Section", # inline data "article_set-TOTAL_FORMS": "3", "article_set-INITIAL_FORMS": "0", "article_set-MAX_NUM_FORMS": "0", } response = self.client.post(reverse("admin:admin_views_section_add"), post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def test_popup_add_POST(self): """HTTP response from a popup is properly escaped.""" post_data = { IS_POPUP_VAR: "1", "title": "title with a new\nline", "content": "some content", "date_0": "2010-09-10", "date_1": "14:55:39", } response = self.client.post(reverse("admin:admin_views_article_add"), post_data) self.assertContains(response, "title with a new\\nline") def test_basic_edit_POST(self): """ A smoke test to ensure POST on edit_view works. """ url = reverse("admin:admin_views_section_change", args=(self.s1.pk,)) response = self.client.post(url, self.inline_post_data) self.assertEqual(response.status_code, 302) # redirect somewhere def test_edit_save_as(self): """ Test "save as". """ post_data = self.inline_post_data.copy() post_data.update( { "_saveasnew": "Save+as+new", "article_set-1-section": "1", "article_set-2-section": "1", "article_set-3-section": "1", "article_set-4-section": "1", "article_set-5-section": "1", } ) response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # redirect somewhere def test_edit_save_as_delete_inline(self): """ Should be able to "Save as new" while also deleting an inline. """ post_data = self.inline_post_data.copy() post_data.update( { "_saveasnew": "Save+as+new", "article_set-1-section": "1", "article_set-2-section": "1", "article_set-2-DELETE": "1", "article_set-3-section": "1", } ) response = self.client.post( reverse("admin:admin_views_section_change", args=(self.s1.pk,)), post_data ) self.assertEqual(response.status_code, 302) # started with 3 articles, one was deleted. self.assertEqual(Section.objects.latest("id").article_set.count(), 2) def test_change_list_column_field_classes(self): response = self.client.get(reverse("admin:admin_views_article_changelist")) # callables display the callable name. self.assertContains(response, "column-callable_year") self.assertContains(response, "field-callable_year") # lambdas display as "lambda" + index that they appear in list_display. self.assertContains(response, "column-lambda8") self.assertContains(response, "field-lambda8") def test_change_list_sorting_callable(self): """ Ensure we can sort on a list_display field that is a callable (column 2 is callable_year in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": 2} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on callable are out of order.", ) def test_change_list_boolean_display_property(self): response = self.client.get(reverse("admin:admin_views_article_changelist")) self.assertContains( response, '<td class="field-model_property_is_from_past">' '<img src="/static/admin/img/icon-yes.svg" alt="True"></td>', ) def test_change_list_sorting_property(self): """ Sort on a list_display field that is a property (column 10 is a property in Article model). """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": 10} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on property are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on property are out of order.", ) def test_change_list_sorting_callable_query_expression(self): """Query expressions may be used for admin_order_field.""" tests = [ ("order_by_expression", 9), ("order_by_f_expression", 12), ("order_by_orderby_expression", 13), ] for admin_order_field, index in tests: with self.subTest(admin_order_field): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": index}, ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on callable are out of order.", ) def test_change_list_sorting_callable_query_expression_reverse(self): tests = [ ("order_by_expression", -9), ("order_by_f_expression", -12), ("order_by_orderby_expression", -13), ] for admin_order_field, index in tests: with self.subTest(admin_order_field): response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": index}, ) self.assertContentBefore( response, "Middle content", "Oldest content", "Results of sorting on callable are out of order.", ) self.assertContentBefore( response, "Newest content", "Middle content", "Results of sorting on callable are out of order.", ) def test_change_list_sorting_model(self): """ Ensure we can sort on a list_display field that is a Model method (column 3 is 'model_year' in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "-3"} ) self.assertContentBefore( response, "Newest content", "Middle content", "Results of sorting on Model method are out of order.", ) self.assertContentBefore( response, "Middle content", "Oldest content", "Results of sorting on Model method are out of order.", ) def test_change_list_sorting_model_admin(self): """ Ensure we can sort on a list_display field that is a ModelAdmin method (column 4 is 'modeladmin_year' in ArticleAdmin) """ response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "4"} ) self.assertContentBefore( response, "Oldest content", "Middle content", "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, "Middle content", "Newest content", "Results of sorting on ModelAdmin method are out of order.", ) def test_change_list_sorting_model_admin_reverse(self): """ Ensure we can sort on a list_display field that is a ModelAdmin method in reverse order (i.e. admin_order_field uses the '-' prefix) (column 6 is 'model_year_reverse' in ArticleAdmin) """ td = '<td class="field-model_property_year">%s</td>' td_2000, td_2008, td_2009 = td % 2000, td % 2008, td % 2009 response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "6"} ) self.assertContentBefore( response, td_2009, td_2008, "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, td_2008, td_2000, "Results of sorting on ModelAdmin method are out of order.", ) # Let's make sure the ordering is right and that we don't get a # FieldError when we change to descending order response = self.client.get( reverse("admin:admin_views_article_changelist"), {"o": "-6"} ) self.assertContentBefore( response, td_2000, td_2008, "Results of sorting on ModelAdmin method are out of order.", ) self.assertContentBefore( response, td_2008, td_2009, "Results of sorting on ModelAdmin method are out of order.", ) def test_change_list_sorting_multiple(self): p1 = Person.objects.create(name="Chris", gender=1, alive=True) p2 = Person.objects.create(name="Chris", gender=2, alive=True) p3 = Person.objects.create(name="Bob", gender=1, alive=True) link1 = reverse("admin:admin_views_person_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_person_change", args=(p2.pk,)) link3 = reverse("admin:admin_views_person_change", args=(p3.pk,)) # Sort by name, gender response = self.client.get( reverse("admin:admin_views_person_changelist"), {"o": "1.2"} ) self.assertContentBefore(response, link3, link1) self.assertContentBefore(response, link1, link2) # Sort by gender descending, name response = self.client.get( reverse("admin:admin_views_person_changelist"), {"o": "-2.1"} ) self.assertContentBefore(response, link2, link3) self.assertContentBefore(response, link3, link1) def test_change_list_sorting_preserve_queryset_ordering(self): """ If no ordering is defined in `ModelAdmin.ordering` or in the query string, then the underlying order of the queryset should not be changed, even if it is defined in `Modeladmin.get_queryset()`. Refs #11868, #7309. """ p1 = Person.objects.create(name="Amy", gender=1, alive=True, age=80) p2 = Person.objects.create(name="Bob", gender=1, alive=True, age=70) p3 = Person.objects.create(name="Chris", gender=2, alive=False, age=60) link1 = reverse("admin:admin_views_person_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_person_change", args=(p2.pk,)) link3 = reverse("admin:admin_views_person_change", args=(p3.pk,)) response = self.client.get(reverse("admin:admin_views_person_changelist"), {}) self.assertContentBefore(response, link3, link2) self.assertContentBefore(response, link2, link1) def test_change_list_sorting_model_meta(self): # Test ordering on Model Meta is respected l1 = Language.objects.create(iso="ur", name="Urdu") l2 = Language.objects.create(iso="ar", name="Arabic") link1 = reverse("admin:admin_views_language_change", args=(quote(l1.pk),)) link2 = reverse("admin:admin_views_language_change", args=(quote(l2.pk),)) response = self.client.get(reverse("admin:admin_views_language_changelist"), {}) self.assertContentBefore(response, link2, link1) # Test we can override with query string response = self.client.get( reverse("admin:admin_views_language_changelist"), {"o": "-1"} ) self.assertContentBefore(response, link1, link2) def test_change_list_sorting_override_model_admin(self): # Test ordering on Model Admin is respected, and overrides Model Meta dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse("admin:admin_views_podcast_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_podcast_change", args=(p2.pk,)) response = self.client.get(reverse("admin:admin_views_podcast_changelist"), {}) self.assertContentBefore(response, link1, link2) def test_multiple_sort_same_field(self): # The changelist displays the correct columns if two columns correspond # to the same ordering field. dt = datetime.datetime.now() p1 = Podcast.objects.create(name="A", release_date=dt) p2 = Podcast.objects.create(name="B", release_date=dt - datetime.timedelta(10)) link1 = reverse("admin:admin_views_podcast_change", args=(quote(p1.pk),)) link2 = reverse("admin:admin_views_podcast_change", args=(quote(p2.pk),)) response = self.client.get(reverse("admin:admin_views_podcast_changelist"), {}) self.assertContentBefore(response, link1, link2) p1 = ComplexSortedPerson.objects.create(name="Bob", age=10) p2 = ComplexSortedPerson.objects.create(name="Amy", age=20) link1 = reverse("admin:admin_views_complexsortedperson_change", args=(p1.pk,)) link2 = reverse("admin:admin_views_complexsortedperson_change", args=(p2.pk,)) response = self.client.get( reverse("admin:admin_views_complexsortedperson_changelist"), {} ) # Should have 5 columns (including action checkbox col) result_list_table_re = re.compile('<table id="result_list">(.*?)</thead>') result_list_table_head = result_list_table_re.search(str(response.content))[0] self.assertEqual(result_list_table_head.count('<th scope="col"'), 5) self.assertContains(response, "Name") self.assertContains(response, "Colored name") # Check order self.assertContentBefore(response, "Name", "Colored name") # Check sorting - should be by name self.assertContentBefore(response, link2, link1) def test_sort_indicators_admin_order(self): """ The admin shows default sort indicators for all kinds of 'ordering' fields: field names, method on the model admin and model itself, and other callables. See #17252. """ models = [ (AdminOrderedField, "adminorderedfield"), (AdminOrderedModelMethod, "adminorderedmodelmethod"), (AdminOrderedAdminMethod, "adminorderedadminmethod"), (AdminOrderedCallable, "adminorderedcallable"), ] for model, url in models: model.objects.create(stuff="The Last Item", order=3) model.objects.create(stuff="The First Item", order=1) model.objects.create(stuff="The Middle Item", order=2) response = self.client.get( reverse("admin:admin_views_%s_changelist" % url), {} ) # Should have 3 columns including action checkbox col. result_list_table_re = re.compile('<table id="result_list">(.*?)</thead>') result_list_table_head = result_list_table_re.search(str(response.content))[ 0 ] self.assertEqual(result_list_table_head.count('<th scope="col"'), 3) # Check if the correct column was selected. 2 is the index of the # 'order' column in the model admin's 'list_display' with 0 being # the implicit 'action_checkbox' and 1 being the column 'stuff'. self.assertEqual( response.context["cl"].get_ordering_field_columns(), {2: "asc"} ) # Check order of records. self.assertContentBefore(response, "The First Item", "The Middle Item") self.assertContentBefore(response, "The Middle Item", "The Last Item") def test_has_related_field_in_list_display_fk(self): """Joins shouldn't be performed for <FK>_id fields in list display.""" state = State.objects.create(name="Karnataka") City.objects.create(state=state, name="Bangalore") response = self.client.get(reverse("admin:admin_views_city_changelist"), {}) response.context["cl"].list_display = ["id", "name", "state"] self.assertIs(response.context["cl"].has_related_field_in_list_display(), True) response.context["cl"].list_display = ["id", "name", "state_id"]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_breadcrumbs.py
tests/admin_views/test_breadcrumbs.py
from django.contrib.auth.models import User from django.test import TestCase, override_settings from django.urls import reverse @override_settings(ROOT_URLCONF="admin_views.urls") class AdminBreadcrumbsTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) def setUp(self): self.client.force_login(self.superuser) def test_breadcrumbs_absent(self): response = self.client.get(reverse("admin:index")) self.assertNotContains(response, '<nav aria-label="Breadcrumbs">') def test_breadcrumbs_present(self): response = self.client.get(reverse("admin:auth_user_add")) self.assertContains(response, '<nav aria-label="Breadcrumbs">') response = self.client.get( reverse("admin:app_list", kwargs={"app_label": "auth"}) ) self.assertContains(response, '<nav aria-label="Breadcrumbs">')
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/test_password_form.py
tests/admin_views/test_password_form.py
from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import User from django.test import override_settings from django.urls import reverse @override_settings(ROOT_URLCONF="auth_tests.urls_admin") class SeleniumAuthTests(AdminSeleniumTestCase): available_apps = AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="super@example.com", ) def test_add_new_user(self): """A user with no password can be added. Enabling/disabling the usable password field shows/hides the password fields when adding a user. """ from selenium.common import NoSuchElementException from selenium.webdriver.common.by import By user_add_url = reverse("auth_test_admin:auth_user_add") self.admin_login(username="super", password="secret") self.selenium.get(self.live_server_url + user_add_url) pw_switch_on = self.selenium.find_element( By.CSS_SELECTOR, 'input[name="usable_password"][value="true"]' ) pw_switch_off = self.selenium.find_element( By.CSS_SELECTOR, 'input[name="usable_password"][value="false"]' ) password1 = self.selenium.find_element( By.CSS_SELECTOR, 'input[name="password1"]' ) password2 = self.selenium.find_element( By.CSS_SELECTOR, 'input[name="password2"]' ) # Default is to set a password on user creation. self.assertIs(pw_switch_on.is_selected(), True) self.assertIs(pw_switch_off.is_selected(), False) # The password fields are visible. self.assertIs(password1.is_displayed(), True) self.assertIs(password2.is_displayed(), True) # Click to disable password-based authentication. pw_switch_off.click() # Radio buttons are updated accordingly. self.assertIs(pw_switch_on.is_selected(), False) self.assertIs(pw_switch_off.is_selected(), True) # The password fields are hidden. self.assertIs(password1.is_displayed(), False) self.assertIs(password2.is_displayed(), False) # The warning message should not be shown. with self.assertRaises(NoSuchElementException): self.selenium.find_element(By.ID, "id_unusable_warning") def test_change_password_for_existing_user(self): """A user can have their password changed or unset. Enabling/disabling the usable password field shows/hides the password fields and the warning about password lost. """ from selenium.webdriver.common.by import By user = User.objects.create_user( username="ada", password="charles", email="ada@example.com" ) user_url = reverse("auth_test_admin:auth_user_password_change", args=(user.pk,)) self.admin_login(username="super", password="secret") self.selenium.get(self.live_server_url + user_url) pw_switch_on = self.selenium.find_element( By.CSS_SELECTOR, 'input[name="usable_password"][value="true"]' ) pw_switch_off = self.selenium.find_element( By.CSS_SELECTOR, 'input[name="usable_password"][value="false"]' ) password1 = self.selenium.find_element( By.CSS_SELECTOR, 'input[name="password1"]' ) password2 = self.selenium.find_element( By.CSS_SELECTOR, 'input[name="password2"]' ) submit_set = self.selenium.find_element( By.CSS_SELECTOR, 'input[type="submit"].set-password' ) submit_unset = self.selenium.find_element( By.CSS_SELECTOR, 'input[type="submit"].unset-password' ) # By default password-based authentication is enabled. self.assertIs(pw_switch_on.is_selected(), True) self.assertIs(pw_switch_off.is_selected(), False) # The password fields are visible. self.assertIs(password1.is_displayed(), True) self.assertIs(password2.is_displayed(), True) # Only the set password submit button is visible. self.assertIs(submit_set.is_displayed(), True) self.assertIs(submit_unset.is_displayed(), False) # Click to disable password-based authentication. pw_switch_off.click() # Radio buttons are updated accordingly. self.assertIs(pw_switch_on.is_selected(), False) self.assertIs(pw_switch_off.is_selected(), True) # The password fields are hidden. self.assertIs(password1.is_displayed(), False) self.assertIs(password2.is_displayed(), False) # Only the unset password submit button is visible. self.assertIs(submit_unset.is_displayed(), True) self.assertIs(submit_set.is_displayed(), False) # The warning about password being lost is shown. warning = self.selenium.find_element(By.ID, "id_unusable_warning") self.assertIs(warning.is_displayed(), True) # Click to enable password-based authentication. pw_switch_on.click() # The warning disappears. self.assertIs(warning.is_displayed(), False) # The password fields are shown. self.assertIs(password1.is_displayed(), True) self.assertIs(password2.is_displayed(), True) # Only the set password submit button is visible. self.assertIs(submit_set.is_displayed(), True) self.assertIs(submit_unset.is_displayed(), False)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/forms.py
tests/admin_views/forms.py
from django.contrib.admin.forms import AdminAuthenticationForm, AdminPasswordChangeForm from django.contrib.admin.helpers import ActionForm from django.core.exceptions import ValidationError class CustomAdminAuthenticationForm(AdminAuthenticationForm): class Media: css = {"all": ("path/to/media.css",)} def clean_username(self): username = self.cleaned_data.get("username") if username == "customform": raise ValidationError("custom form error") return username class CustomAdminPasswordChangeForm(AdminPasswordChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["old_password"].label = "Custom old password label" class MediaActionForm(ActionForm): class Media: js = ["path/to/media.js"]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/urls.py
tests/admin_views/urls.py
from django.http import HttpResponse from django.urls import include, path from . import admin, custom_has_permission_admin, customadmin, views from .test_autocomplete_view import site as autocomplete_site def non_admin_view(request): return HttpResponse() urlpatterns = [ path("test_admin/admin/doc/", include("django.contrib.admindocs.urls")), path("test_admin/admin/secure-view/", views.secure_view, name="secure_view"), path("test_admin/admin/secure-view2/", views.secure_view2, name="secure_view2"), path("test_admin/admin/", admin.site.urls), path("test_admin/admin2/", customadmin.site.urls), path( "test_admin/admin3/", (admin.site.get_urls(), "admin", "admin3"), {"form_url": "pony"}, ), path("test_admin/admin4/", customadmin.simple_site.urls), path("test_admin/admin5/", admin.site2.urls), path("test_admin/admin6/", admin.site6.urls), path("test_admin/admin7/", admin.site7.urls), # All admin views accept `extra_context` to allow adding it like this: path( "test_admin/admin8/", (admin.site.get_urls(), "admin", "admin-extra-context"), {"extra_context": {}}, ), path("test_admin/admin9/", admin.site9.urls), path("test_admin/admin10/", admin.site10.urls), path("test_admin/has_permission_admin/", custom_has_permission_admin.site.urls), path("test_admin/autocomplete_admin/", autocomplete_site.urls), # Shares the admin URL prefix. path("test_admin/admin/non_admin_view/", non_admin_view, name="non_admin"), path("test_admin/admin10/non_admin_view/", non_admin_view, name="non_admin10"), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/admin_views/customadmin.py
tests/admin_views/customadmin.py
""" A second, custom AdminSite -- see tests.CustomAdminSiteTests. """ from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from django.http import HttpResponse from django.urls import path from . import admin as base_admin from . import forms, models class Admin2(admin.AdminSite): app_index_template = "custom_admin/app_index.html" login_form = forms.CustomAdminAuthenticationForm login_template = "custom_admin/login.html" logout_template = "custom_admin/logout.html" index_template = ["custom_admin/index.html"] # a list, to test fix for #18697 password_change_form = forms.CustomAdminPasswordChangeForm password_change_template = "custom_admin/password_change_form.html" password_change_done_template = "custom_admin/password_change_done.html" # A custom index view. def index(self, request, extra_context=None): return super().index(request, {"foo": "*bar*"}) def get_urls(self): return [ path("my_view/", self.admin_view(self.my_view), name="my_view"), ] + super().get_urls() def my_view(self, request): return HttpResponse("Django is a magical pony!") def password_change(self, request, extra_context=None): return super().password_change(request, {"spam": "eggs"}) def get_app_list(self, request, app_label=None): app_list = super().get_app_list(request, app_label=app_label) # Reverse order of apps and models. app_list = list(reversed(app_list)) for app in app_list: app["models"].sort(key=lambda x: x["name"], reverse=True) return app_list class UserLimitedAdmin(UserAdmin): # used for testing password change on a user not in queryset def get_queryset(self, request): qs = super().get_queryset(request) return qs.filter(is_superuser=False) class CustomPwdTemplateUserAdmin(UserAdmin): change_user_password_template = [ "admin/auth/user/change_password.html" ] # a list, to test fix for #18697 class BookAdmin(admin.ModelAdmin): def get_deleted_objects(self, objs, request): return ["a deletable object"], {"books": 1}, set(), [] site = Admin2(name="admin2") site.register(models.Article, base_admin.ArticleAdmin) site.register(models.Book, BookAdmin) site.register( models.Section, inlines=[base_admin.ArticleInline], search_fields=["name"] ) site.register(models.Thing, base_admin.ThingAdmin) site.register(models.Fabric, base_admin.FabricAdmin) site.register(models.ChapterXtra1, base_admin.ChapterXtra1Admin) site.register(User, UserLimitedAdmin) site.register(models.UndeletableObject, base_admin.UndeletableObjectAdmin) site.register(models.Simple, base_admin.AttributeErrorRaisingAdmin) simple_site = Admin2(name="admin4") simple_site.register(User, CustomPwdTemplateUserAdmin)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/one_to_one/models.py
tests/one_to_one/models.py
""" One-to-one relationships To define a one-to-one relationship, use ``OneToOneField()``. In this example, a ``Place`` optionally can be a ``Restaurant``. """ from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) def __str__(self): return "%s the place" % self.name class Restaurant(models.Model): place = models.OneToOneField(Place, models.CASCADE, primary_key=True) serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) def __str__(self): return "%s the restaurant" % self.place.name class Bar(models.Model): place = models.OneToOneField(Place, models.CASCADE) serves_cocktails = models.BooleanField(default=True) class UndergroundBar(models.Model): place = models.OneToOneField(Place, models.SET_NULL, null=True) serves_cocktails = models.BooleanField(default=True) class Waiter(models.Model): restaurant = models.ForeignKey(Restaurant, models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return "%s the waiter at %s" % (self.name, self.restaurant) class Favorites(models.Model): name = models.CharField(max_length=50) restaurants = models.ManyToManyField(Restaurant) class ManualPrimaryKey(models.Model): primary_key = models.CharField(max_length=10, primary_key=True) name = models.CharField(max_length=50) class RelatedModel(models.Model): link = models.OneToOneField(ManualPrimaryKey, models.CASCADE) name = models.CharField(max_length=50) class MultiModel(models.Model): link1 = models.OneToOneField(Place, models.CASCADE) link2 = models.OneToOneField(ManualPrimaryKey, models.CASCADE) name = models.CharField(max_length=50) def __str__(self): return "Multimodel %s" % self.name class Target(models.Model): name = models.CharField(max_length=50, unique=True) class Pointer(models.Model): other = models.OneToOneField(Target, models.CASCADE, primary_key=True) class Pointer2(models.Model): other = models.OneToOneField(Target, models.CASCADE, related_name="second_pointer") class HiddenPointer(models.Model): target = models.OneToOneField(Target, models.CASCADE, related_name="hidden+") class ToFieldPointer(models.Model): target = models.OneToOneField( Target, models.CASCADE, to_field="name", primary_key=True ) # 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 DirectorManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_temp=False) class Director(models.Model): is_temp = models.BooleanField(default=False) school = models.OneToOneField(School, models.CASCADE) objects = DirectorManager()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/one_to_one/__init__.py
tests/one_to_one/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/one_to_one/tests.py
tests/one_to_one/tests.py
from django.core.exceptions import FieldFetchBlocked from django.db import IntegrityError, connection, transaction from django.db.models import FETCH_PEERS, RAISE from django.test import TestCase from .models import ( Bar, Director, Favorites, HiddenPointer, ManualPrimaryKey, MultiModel, Place, Pointer, RelatedModel, Restaurant, School, Target, ToFieldPointer, UndergroundBar, Waiter, ) class OneToOneTests(TestCase): @classmethod def setUpTestData(cls): cls.p1 = Place.objects.create(name="Demon Dogs", address="944 W. Fullerton") cls.p2 = Place.objects.create(name="Ace Hardware", address="1013 N. Ashland") cls.r1 = Restaurant.objects.create( place=cls.p1, serves_hot_dogs=True, serves_pizza=False ) cls.b1 = Bar.objects.create(place=cls.p1, serves_cocktails=False) def test_getter(self): # A Restaurant can access its place. self.assertEqual(repr(self.r1.place), "<Place: Demon Dogs the place>") # A Place can access its restaurant, if available. self.assertEqual( repr(self.p1.restaurant), "<Restaurant: Demon Dogs the restaurant>" ) # p2 doesn't have an associated restaurant. with self.assertRaisesMessage( Restaurant.DoesNotExist, "Place has no restaurant" ): self.p2.restaurant # 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(self.p2, "restaurant")) def test_setter(self): # Set the place using assignment notation. Because place is the primary # key on Restaurant, the save will create a new restaurant self.r1.place = self.p2 self.r1.save() self.assertEqual( repr(self.p2.restaurant), "<Restaurant: Ace Hardware the restaurant>" ) self.assertEqual(repr(self.r1.place), "<Place: Ace Hardware the place>") self.assertEqual(self.p2.pk, self.r1.pk) # Set the place back again, using assignment in the reverse direction. self.p1.restaurant = self.r1 self.assertEqual( repr(self.p1.restaurant), "<Restaurant: Demon Dogs the restaurant>" ) r = Restaurant.objects.get(pk=self.p1.id) self.assertEqual(repr(r.place), "<Place: Demon Dogs the place>") def test_manager_all(self): # Restaurant.objects.all() just returns the Restaurants, not the # Places. self.assertSequenceEqual(Restaurant.objects.all(), [self.r1]) # Place.objects.all() returns all Places, regardless of whether they # have Restaurants. self.assertSequenceEqual(Place.objects.order_by("name"), [self.p2, self.p1]) def test_manager_get(self): def assert_get_restaurant(**params): self.assertEqual( repr(Restaurant.objects.get(**params)), "<Restaurant: Demon Dogs the restaurant>", ) assert_get_restaurant(place__id__exact=self.p1.pk) assert_get_restaurant(place__id=self.p1.pk) assert_get_restaurant(place__exact=self.p1.pk) assert_get_restaurant(place__exact=self.p1) assert_get_restaurant(place=self.p1.pk) assert_get_restaurant(place=self.p1) assert_get_restaurant(pk=self.p1.pk) assert_get_restaurant(place__pk__exact=self.p1.pk) assert_get_restaurant(place__pk=self.p1.pk) assert_get_restaurant(place__name__startswith="Demon") def assert_get_place(**params): self.assertEqual( repr(Place.objects.get(**params)), "<Place: Demon Dogs the place>" ) assert_get_place(restaurant__place__exact=self.p1.pk) assert_get_place(restaurant__place__exact=self.p1) assert_get_place(restaurant__place__pk=self.p1.pk) assert_get_place(restaurant__exact=self.p1.pk) assert_get_place(restaurant__exact=self.r1) assert_get_place(restaurant__pk=self.p1.pk) assert_get_place(restaurant=self.p1.pk) assert_get_place(restaurant=self.r1) assert_get_place(id__exact=self.p1.pk) assert_get_place(pk=self.p1.pk) def test_foreign_key(self): # Add a Waiter to the Restaurant. w = self.r1.waiter_set.create(name="Joe") self.assertEqual( repr(w), "<Waiter: Joe the waiter at Demon Dogs the restaurant>" ) # Query the waiters def assert_filter_waiters(**params): self.assertSequenceEqual(Waiter.objects.filter(**params), [w]) assert_filter_waiters(restaurant__place__exact=self.p1.pk) assert_filter_waiters(restaurant__place__exact=self.p1) assert_filter_waiters(restaurant__place__pk=self.p1.pk) assert_filter_waiters(restaurant__exact=self.r1.pk) assert_filter_waiters(restaurant__exact=self.r1) assert_filter_waiters(restaurant__pk=self.r1.pk) assert_filter_waiters(restaurant=self.r1.pk) assert_filter_waiters(restaurant=self.r1) assert_filter_waiters(id__exact=w.pk) assert_filter_waiters(pk=w.pk) # Delete the restaurant; the waiter should also be removed r = Restaurant.objects.get(pk=self.r1.pk) r.delete() self.assertEqual(Waiter.objects.count(), 0) def test_multiple_o2o(self): # One-to-one fields still work if you create your own primary key o1 = ManualPrimaryKey(primary_key="abc123", name="primary") o1.save() o2 = RelatedModel(link=o1, name="secondary") o2.save() # You can have multiple one-to-one fields on a model, too. x1 = MultiModel(link1=self.p1, link2=o1, name="x1") x1.save() self.assertEqual(repr(o1.multimodel), "<MultiModel: Multimodel x1>") # This will fail because each one-to-one field must be unique (and # link2=o1 was used for x1, above). mm = MultiModel(link1=self.p2, link2=o1, name="x1") with self.assertRaises(IntegrityError): with transaction.atomic(): mm.save() def test_unsaved_object(self): """ #10811 -- Assigning an unsaved object to a OneToOneField should raise an exception. """ place = Place(name="User", address="London") with self.assertRaises(Restaurant.DoesNotExist): place.restaurant msg = ( "save() prohibited to prevent data loss due to unsaved related object " "'place'." ) with self.assertRaisesMessage(ValueError, msg): Restaurant.objects.create( place=place, serves_hot_dogs=True, serves_pizza=False ) # place should not cache restaurant with self.assertRaises(Restaurant.DoesNotExist): place.restaurant def test_reverse_relationship_cache_cascade(self): """ Regression test for #9023: accessing the reverse relationship shouldn't result in a cascading delete(). """ bar = UndergroundBar.objects.create(place=self.p1, serves_cocktails=False) # The bug in #9023: if you access the one-to-one relation *before* # setting to None and deleting, the cascade happens anyway. self.p1.undergroundbar bar.place.name = "foo" bar.place = None bar.save() self.p1.delete() self.assertEqual(Place.objects.count(), 1) self.assertEqual(UndergroundBar.objects.count(), 1) def test_create_models_m2m(self): """ Models are created via the m2m relation if the remote model has a OneToOneField (#1064, #1506). """ f = Favorites(name="Fred") f.save() f.restaurants.set([self.r1]) self.assertSequenceEqual(f.restaurants.all(), [self.r1]) def test_reverse_object_cache(self): """ The name of the cache for the reverse object is correct (#7173). """ self.assertEqual(self.p1.restaurant, self.r1) self.assertEqual(self.p1.bar, self.b1) def test_assign_none_reverse_relation(self): p = Place.objects.get(name="Demon Dogs") # Assigning None succeeds if field is null=True. ug_bar = UndergroundBar.objects.create(place=p, serves_cocktails=False) p.undergroundbar = None self.assertIsNone(ug_bar.place) ug_bar.save() ug_bar.refresh_from_db() self.assertIsNone(ug_bar.place) def test_assign_none_null_reverse_relation(self): p = Place.objects.get(name="Demon Dogs") # Assigning None doesn't throw AttributeError if there isn't a related # UndergroundBar. p.undergroundbar = None def test_assign_none_to_null_cached_reverse_relation(self): p = Place.objects.get(name="Demon Dogs") # Prime the relation's cache with a value of None. with self.assertRaises(Place.undergroundbar.RelatedObjectDoesNotExist): getattr(p, "undergroundbar") # Assigning None works if there isn't a related UndergroundBar and the # reverse cache has a value of None. p.undergroundbar = None def test_assign_o2o_id_value(self): b = UndergroundBar.objects.create(place=self.p1) b.place_id = self.p2.pk b.save() self.assertEqual(b.place_id, self.p2.pk) self.assertFalse(UndergroundBar.place.is_cached(b)) self.assertEqual(b.place, self.p2) self.assertTrue(UndergroundBar.place.is_cached(b)) # Reassigning the same value doesn't clear a cached instance. b.place_id = self.p2.pk self.assertTrue(UndergroundBar.place.is_cached(b)) def test_assign_o2o_id_none(self): b = UndergroundBar.objects.create(place=self.p1) b.place_id = None b.save() self.assertIsNone(b.place_id) self.assertFalse(UndergroundBar.place.is_cached(b)) self.assertIsNone(b.place) self.assertTrue(UndergroundBar.place.is_cached(b)) def test_related_object_cache(self): """Regression test for #6886 (the related-object cache)""" # Look up the objects again so that we get "fresh" objects p = Place.objects.get(name="Demon Dogs") r = p.restaurant # Accessing the related object again returns the exactly same object self.assertIs(p.restaurant, r) # But if we kill the cache, we get a new object del p._state.fields_cache["restaurant"] self.assertIsNot(p.restaurant, r) # Reassigning the Restaurant object results in an immediate cache # update We can't use a new Restaurant because that'll violate # one-to-one, but with a new *instance* the is test below will fail if # #6886 regresses. r2 = Restaurant.objects.get(pk=r.pk) p.restaurant = r2 self.assertIs(p.restaurant, r2) # Assigning None succeeds if field is null=True. ug_bar = UndergroundBar.objects.create(place=p, serves_cocktails=False) ug_bar.place = None self.assertIsNone(ug_bar.place) # Assigning None will not fail: Place.restaurant is null=False setattr(p, "restaurant", None) # You also can't assign an object of the wrong type here msg = ( 'Cannot assign "<Place: Demon Dogs the place>": ' '"Place.restaurant" must be a "Restaurant" instance.' ) with self.assertRaisesMessage(ValueError, msg): setattr(p, "restaurant", p) # Creation using keyword argument should cache the related object. p = Place.objects.get(name="Demon Dogs") r = Restaurant(place=p) self.assertIs(r.place, p) # Creation using keyword argument and unsaved related instance (#8070). p = Place() r = Restaurant(place=p) self.assertIs(r.place, p) # Creation using attname keyword argument and an id will cause the # related object to be fetched. p = Place.objects.get(name="Demon Dogs") r = Restaurant(place_id=p.id) self.assertIsNot(r.place, p) self.assertEqual(r.place, p) def test_filter_one_to_one_relations(self): """ Regression test for #9968 filtering reverse one-to-one relations with primary_key=True was misbehaving. We test both (primary_key=True & False) cases here to prevent any reappearance of the problem. """ target = Target.objects.create() self.assertSequenceEqual(Target.objects.filter(pointer=None), [target]) self.assertSequenceEqual(Target.objects.exclude(pointer=None), []) self.assertSequenceEqual(Target.objects.filter(second_pointer=None), [target]) self.assertSequenceEqual(Target.objects.exclude(second_pointer=None), []) def test_o2o_primary_key_delete(self): t = Target.objects.create(name="name") Pointer.objects.create(other=t) num_deleted, objs = Pointer.objects.filter(other__name="name").delete() self.assertEqual(num_deleted, 1) self.assertEqual(objs, {"one_to_one.Pointer": 1}) def test_save_nullable_o2o_after_parent(self): place = Place(name="Rose tattoo") bar = UndergroundBar(place=place) place.save() bar.save() bar.refresh_from_db() self.assertEqual(bar.place, place) def test_reverse_object_does_not_exist_cache(self): """ Regression for #13839 and #17439. DoesNotExist on a reverse one-to-one relation is cached. """ p = Place(name="Zombie Cats", address="Not sure") p.save() with self.assertNumQueries(1): with self.assertRaises(Restaurant.DoesNotExist): p.restaurant with self.assertNumQueries(0): with self.assertRaises(Restaurant.DoesNotExist): p.restaurant def test_reverse_object_cached_when_related_is_accessed(self): """ Regression for #13839 and #17439. The target of a one-to-one relation is cached when the origin is accessed through the reverse relation. """ # Use a fresh object without caches r = Restaurant.objects.get(pk=self.r1.pk) p = r.place with self.assertNumQueries(0): self.assertEqual(p.restaurant, r) def test_related_object_cached_when_reverse_is_accessed(self): """ Regression for #13839 and #17439. The origin of a one-to-one relation is cached when the target is accessed through the reverse relation. """ # Use a fresh object without caches p = Place.objects.get(pk=self.p1.pk) r = p.restaurant with self.assertNumQueries(0): self.assertEqual(r.place, p) def test_reverse_object_cached_when_related_is_set(self): """ Regression for #13839 and #17439. The target of a one-to-one relation is always cached. """ p = Place(name="Zombie Cats", address="Not sure") p.save() self.r1.place = p self.r1.save() with self.assertNumQueries(0): self.assertEqual(p.restaurant, self.r1) def test_reverse_object_cached_when_related_is_unset(self): """ Regression for #13839 and #17439. The target of a one-to-one relation is always cached. """ b = UndergroundBar(place=self.p1, serves_cocktails=True) b.save() with self.assertNumQueries(0): self.assertEqual(self.p1.undergroundbar, b) b.place = None b.save() with self.assertNumQueries(0): with self.assertRaises(UndergroundBar.DoesNotExist): self.p1.undergroundbar def test_get_reverse_on_unsaved_object(self): """ Regression for #18153 and #19089. Accessing the reverse relation on an unsaved object always raises an exception. """ p = Place() # When there's no instance of the origin of the one-to-one with self.assertNumQueries(0): with self.assertRaises(UndergroundBar.DoesNotExist): p.undergroundbar UndergroundBar.objects.create() # When there's one instance of the origin # (p.undergroundbar used to return that instance) with self.assertNumQueries(0): with self.assertRaises(UndergroundBar.DoesNotExist): p.undergroundbar # Several instances of the origin are only possible if database allows # inserting multiple NULL rows for a unique constraint if connection.features.supports_nullable_unique_constraints: UndergroundBar.objects.create() # When there are several instances of the origin with self.assertNumQueries(0): with self.assertRaises(UndergroundBar.DoesNotExist): p.undergroundbar def test_set_reverse_on_unsaved_object(self): """ Writing to the reverse relation on an unsaved object is impossible too. """ p = Place() b = UndergroundBar.objects.create() # Assigning a reverse relation on an unsaved object is allowed. p.undergroundbar = b # However saving the object is not allowed. msg = ( "save() prohibited to prevent data loss due to unsaved related object " "'place'." ) with self.assertNumQueries(0): with self.assertRaisesMessage(ValueError, msg): b.save() def test_nullable_o2o_delete(self): u = UndergroundBar.objects.create(place=self.p1) u.place_id = None u.save() self.p1.delete() self.assertTrue(UndergroundBar.objects.filter(pk=u.pk).exists()) self.assertIsNone(UndergroundBar.objects.get(pk=u.pk).place) def test_hidden_accessor(self): """ When a '+' ending related name is specified no reverse accessor should be added to the related model. """ self.assertFalse( hasattr( Target, HiddenPointer._meta.get_field("target").remote_field.accessor_name, ) ) def test_related_object(self): public_school = School.objects.create(is_public=True) public_director = Director.objects.create(school=public_school, is_temp=False) private_school = School.objects.create(is_public=False) private_director = Director.objects.create(school=private_school, is_temp=True) # Only one school is available via all() due to the custom default # manager. self.assertSequenceEqual(School.objects.all(), [public_school]) # Only one director is available via all() due to the custom default # manager. self.assertSequenceEqual(Director.objects.all(), [public_director]) self.assertEqual(public_director.school, public_school) self.assertEqual(public_school.director, public_director) # Make sure the base manager is used so that the related objects # is still accessible even if the default manager doesn't normally # allow it. self.assertEqual(private_director.school, private_school) # Make sure the base manager is used so that an student can still # access its related school even if the default manager doesn't # normally allow it. self.assertEqual(private_school.director, private_director) School._meta.base_manager_name = "objects" School._meta._expire_cache() try: private_director = Director._base_manager.get(pk=private_director.pk) with self.assertRaises(School.DoesNotExist): private_director.school finally: School._meta.base_manager_name = None School._meta._expire_cache() Director._meta.base_manager_name = "objects" Director._meta._expire_cache() try: private_school = School._base_manager.get(pk=private_school.pk) with self.assertRaises(Director.DoesNotExist): private_school.director finally: Director._meta.base_manager_name = None Director._meta._expire_cache() def test_create_reverse_o2o_error(self): msg = "The following fields do not exist in this model: restaurant" with self.assertRaisesMessage(ValueError, msg): Place.objects.create(restaurant=self.r1) def test_get_or_create_reverse_o2o_error(self): msg = "The following fields do not exist in this model: restaurant" r2 = Restaurant.objects.create( place=self.p2, serves_hot_dogs=True, serves_pizza=False ) with self.assertRaisesMessage(ValueError, msg): Place.objects.get_or_create(name="nonexistent", defaults={"restaurant": r2}) def test_update_or_create_reverse_o2o_error(self): msg = "The following fields do not exist in this model: restaurant" r2 = Restaurant.objects.create( place=self.p2, serves_hot_dogs=True, serves_pizza=False ) with self.assertRaisesMessage(ValueError, msg): Place.objects.update_or_create( name="nonexistent", defaults={"restaurant": r2} ) 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(Director(), "director")) self.assertFalse(hasattr(School(), "school")) def test_update_one_to_one_pk(self): p1 = Place.objects.create() p2 = Place.objects.create() r1 = Restaurant.objects.create(place=p1) r2 = Restaurant.objects.create(place=p2) w = Waiter.objects.create(restaurant=r1) Waiter.objects.update(restaurant=r2) w.refresh_from_db() self.assertEqual(w.restaurant, r2) def test_rel_pk_subquery(self): r = Restaurant.objects.first() q1 = Restaurant.objects.filter(place_id=r.pk) # Subquery using primary key and a query against the # same model works correctly. q2 = Restaurant.objects.filter(place_id__in=q1) self.assertSequenceEqual(q2, [r]) # Subquery using 'pk__in' instead of 'place_id__in' work, too. q2 = Restaurant.objects.filter( pk__in=Restaurant.objects.filter(place__id=r.place.pk) ) self.assertSequenceEqual(q2, [r]) q3 = Restaurant.objects.filter(place__in=Place.objects.all()) self.assertSequenceEqual(q3, [r]) q4 = Restaurant.objects.filter(place__in=Place.objects.filter(id=r.pk)) self.assertSequenceEqual(q4, [r]) def test_rel_pk_exact(self): r = Restaurant.objects.first() r2 = Restaurant.objects.filter(pk__exact=r).first() self.assertEqual(r, r2) def test_primary_key_to_field_filter(self): target = Target.objects.create(name="foo") pointer = ToFieldPointer.objects.create(target=target) self.assertSequenceEqual( ToFieldPointer.objects.filter(target=target), [pointer] ) self.assertSequenceEqual( ToFieldPointer.objects.filter(pk__exact=pointer), [pointer] ) def test_cached_relation_invalidated_on_save(self): """ Model.save() invalidates stale OneToOneField relations after a primary key assignment. """ self.assertEqual(self.b1.place, self.p1) # caches b1.place self.b1.place_id = self.p2.pk self.b1.save() self.assertEqual(self.b1.place, self.p2) def test_get_prefetch_querysets_invalid_querysets_length(self): places = Place.objects.all() msg = ( "querysets argument of get_prefetch_querysets() should have a length of 1." ) with self.assertRaisesMessage(ValueError, msg): Place.bar.get_prefetch_querysets( instances=places, querysets=[Bar.objects.all(), Bar.objects.all()], ) def test_fetch_mode_fetch_peers_forward(self): Restaurant.objects.create( place=self.p2, serves_hot_dogs=True, serves_pizza=False ) r1, r2 = Restaurant.objects.fetch_mode(FETCH_PEERS) with self.assertNumQueries(1): r1.place with self.assertNumQueries(0): r2.place def test_fetch_mode_fetch_peers_reverse(self): Restaurant.objects.create( place=self.p2, serves_hot_dogs=True, serves_pizza=False ) p1, p2 = Place.objects.fetch_mode(FETCH_PEERS) with self.assertNumQueries(1): p1.restaurant with self.assertNumQueries(0): p2.restaurant def test_fetch_mode_raise_forward(self): r = Restaurant.objects.fetch_mode(RAISE).get(pk=self.r1.pk) msg = "Fetching of Restaurant.place blocked." with self.assertRaisesMessage(FieldFetchBlocked, msg) as cm: r.place self.assertIsNone(cm.exception.__cause__) self.assertTrue(cm.exception.__suppress_context__) def test_fetch_mode_raise_reverse(self): p = Place.objects.fetch_mode(RAISE).get(pk=self.p1.pk) msg = "Fetching of Place.restaurant blocked." with self.assertRaisesMessage(FieldFetchBlocked, msg) as cm: p.restaurant self.assertIsNone(cm.exception.__cause__) self.assertTrue(cm.exception.__suppress_context__) def test_fetch_mode_copied_forward_fetching_one(self): r1 = Restaurant.objects.fetch_mode(FETCH_PEERS).get(pk=self.r1.pk) self.assertEqual(r1._state.fetch_mode, FETCH_PEERS) self.assertEqual( r1.place._state.fetch_mode, FETCH_PEERS, ) def test_fetch_mode_copied_forward_fetching_many(self): Restaurant.objects.create( place=self.p2, serves_hot_dogs=True, serves_pizza=False ) r1, r2 = Restaurant.objects.fetch_mode(FETCH_PEERS) self.assertEqual(r1._state.fetch_mode, FETCH_PEERS) self.assertEqual( r1.place._state.fetch_mode, FETCH_PEERS, ) def test_fetch_mode_copied_reverse_fetching_one(self): p1 = Place.objects.fetch_mode(FETCH_PEERS).get(pk=self.p1.pk) self.assertEqual(p1._state.fetch_mode, FETCH_PEERS) self.assertEqual( p1.restaurant._state.fetch_mode, FETCH_PEERS, ) def test_fetch_mode_copied_reverse_fetching_many(self): Restaurant.objects.create( place=self.p2, serves_hot_dogs=True, serves_pizza=False ) p1, p2 = Place.objects.fetch_mode(FETCH_PEERS) self.assertEqual(p1._state.fetch_mode, FETCH_PEERS) self.assertEqual( p1.restaurant._state.fetch_mode, FETCH_PEERS, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/defer_regress/models.py
tests/defer_regress/models.py
""" Regression tests for defer() / only() behavior. """ from django.db import models class Item(models.Model): name = models.CharField(max_length=15) text = models.TextField(default="xyzzy") value = models.IntegerField() other_value = models.IntegerField(default=0) source = models.OneToOneField( "self", related_name="destination", on_delete=models.CASCADE, null=True, ) class RelatedItem(models.Model): item = models.ForeignKey(Item, models.CASCADE) class ProxyRelated(RelatedItem): class Meta: proxy = True class Child(models.Model): name = models.CharField(max_length=10) value = models.IntegerField() class Leaf(models.Model): name = models.CharField(max_length=10) child = models.ForeignKey(Child, models.CASCADE) second_child = models.ForeignKey( Child, models.SET_NULL, related_name="other", null=True ) value = models.IntegerField(default=42) class ResolveThis(models.Model): num = models.FloatField() name = models.CharField(max_length=16) class Proxy(Item): class Meta: proxy = True class SimpleItem(models.Model): name = models.CharField(max_length=15) value = models.IntegerField() class Feature(models.Model): item = models.ForeignKey(SimpleItem, models.CASCADE) class SpecialFeature(models.Model): feature = models.ForeignKey(Feature, models.CASCADE) class OneToOneItem(models.Model): item = models.OneToOneField(Item, models.CASCADE, related_name="one_to_one_item") name = models.CharField(max_length=15) class ItemAndSimpleItem(models.Model): item = models.ForeignKey(Item, models.CASCADE) simple = models.ForeignKey(SimpleItem, models.CASCADE) class Profile(models.Model): profile1 = models.CharField(max_length=255, default="profile1") class Location(models.Model): location1 = models.CharField(max_length=255, default="location1") class Request(models.Model): profile = models.ForeignKey(Profile, models.SET_NULL, null=True, blank=True) location = models.ForeignKey(Location, models.CASCADE) items = models.ManyToManyField(Item) request1 = models.CharField(default="request1", max_length=255) request2 = models.CharField(default="request2", max_length=255) request3 = models.CharField(default="request3", max_length=255) request4 = models.CharField(default="request4", max_length=255) class Base(models.Model): text = models.TextField() class Derived(Base): other_text = models.TextField()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/defer_regress/__init__.py
tests/defer_regress/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/defer_regress/tests.py
tests/defer_regress/tests.py
from operator import attrgetter from django.contrib.contenttypes.models import ContentType from django.db import models from django.db.models import Count from django.test import TestCase from .models import ( Base, Child, Derived, Feature, Item, ItemAndSimpleItem, Leaf, Location, OneToOneItem, Proxy, ProxyRelated, RelatedItem, Request, ResolveThis, SimpleItem, SpecialFeature, ) class DeferRegressionTest(TestCase): def test_basic(self): # Deferred fields should really be deferred and not accidentally use # the field's default value just because they aren't passed to __init__ Item.objects.create(name="first", value=42) obj = Item.objects.only("name", "other_value").get(name="first") # Accessing "name" doesn't trigger a new database query. Accessing # "value" or "text" should. with self.assertNumQueries(0): self.assertEqual(obj.name, "first") self.assertEqual(obj.other_value, 0) with self.assertNumQueries(1): self.assertEqual(obj.value, 42) with self.assertNumQueries(1): self.assertEqual(obj.text, "xyzzy") with self.assertNumQueries(0): self.assertEqual(obj.text, "xyzzy") # Regression test for #10695. Make sure different instances don't # inadvertently share data in the deferred descriptor objects. i = Item.objects.create(name="no I'm first", value=37) items = Item.objects.only("value").order_by("-value") self.assertEqual(items[0].name, "first") self.assertEqual(items[1].name, "no I'm first") RelatedItem.objects.create(item=i) r = RelatedItem.objects.defer("item").get() self.assertEqual(r.item_id, i.id) self.assertEqual(r.item, i) # Some further checks for select_related() and inherited model # behavior (regression for #10710). c1 = Child.objects.create(name="c1", value=42) c2 = Child.objects.create(name="c2", value=37) Leaf.objects.create(name="l1", child=c1, second_child=c2) obj = Leaf.objects.only("name", "child").select_related()[0] self.assertEqual(obj.child.name, "c1") self.assertQuerySetEqual( Leaf.objects.select_related().only("child__name", "second_child__name"), [ "l1", ], attrgetter("name"), ) # Models instances with deferred fields should still return the same # content types as their non-deferred versions (bug #10738). ctype = ContentType.objects.get_for_model c1 = ctype(Item.objects.all()[0]) c2 = ctype(Item.objects.defer("name")[0]) c3 = ctype(Item.objects.only("name")[0]) self.assertTrue(c1 is c2 is c3) # Regression for #10733 - only() can be used on a model with two # foreign keys. results = Leaf.objects.only("name", "child", "second_child").select_related() self.assertEqual(results[0].child.name, "c1") self.assertEqual(results[0].second_child.name, "c2") results = Leaf.objects.only( "name", "child", "second_child", "child__name", "second_child__name" ).select_related() self.assertEqual(results[0].child.name, "c1") self.assertEqual(results[0].second_child.name, "c2") # Regression for #16409 - make sure defer() and only() work with # annotate() self.assertIsInstance( list(SimpleItem.objects.annotate(Count("feature")).defer("name")), list ) self.assertIsInstance( list(SimpleItem.objects.annotate(Count("feature")).only("name")), list ) def test_ticket_16409(self): # Regression for #16409 - make sure defer() and only() work with # annotate() self.assertIsInstance( list(SimpleItem.objects.annotate(Count("feature")).defer("name")), list ) self.assertIsInstance( list(SimpleItem.objects.annotate(Count("feature")).only("name")), list ) def test_ticket_23270(self): d = Derived.objects.create(text="foo", other_text="bar") with self.assertNumQueries(1): obj = Base.objects.select_related("derived").defer("text")[0] self.assertIsInstance(obj.derived, Derived) self.assertEqual("bar", obj.derived.other_text) self.assertNotIn("text", obj.__dict__) self.assertEqual(d.pk, obj.derived.base_ptr_id) def test_only_and_defer_usage_on_proxy_models(self): # Regression for #15790 - only() broken for proxy models proxy = Proxy.objects.create(name="proxy", value=42) msg = "QuerySet.only() return bogus results with proxy models" dp = Proxy.objects.only("other_value").get(pk=proxy.pk) self.assertEqual(dp.name, proxy.name, msg=msg) self.assertEqual(dp.value, proxy.value, msg=msg) # also test things with .defer() msg = "QuerySet.defer() return bogus results with proxy models" dp = Proxy.objects.defer("name", "text", "value").get(pk=proxy.pk) self.assertEqual(dp.name, proxy.name, msg=msg) self.assertEqual(dp.value, proxy.value, msg=msg) def test_resolve_columns(self): ResolveThis.objects.create(num=5.0, name="Foobar") qs = ResolveThis.objects.defer("num") self.assertEqual(1, qs.count()) self.assertEqual("Foobar", qs[0].name) def test_reverse_one_to_one_relations(self): # Refs #14694. Test reverse relations which are known unique (reverse # side has o2ofield or unique FK) - the o2o case item = Item.objects.create(name="first", value=42) o2o = OneToOneItem.objects.create(item=item, name="second") self.assertEqual(len(Item.objects.defer("one_to_one_item__name")), 1) self.assertEqual(len(Item.objects.select_related("one_to_one_item")), 1) self.assertEqual( len( Item.objects.select_related("one_to_one_item").defer( "one_to_one_item__name" ) ), 1, ) self.assertEqual( len(Item.objects.select_related("one_to_one_item").defer("value")), 1 ) # Make sure that `only()` doesn't break when we pass in a unique # relation, rather than a field on the relation. self.assertEqual(len(Item.objects.only("one_to_one_item")), 1) with self.assertNumQueries(1): i = Item.objects.select_related("one_to_one_item")[0] self.assertEqual(i.one_to_one_item.pk, o2o.pk) self.assertEqual(i.one_to_one_item.name, "second") with self.assertNumQueries(1): i = Item.objects.select_related("one_to_one_item").defer( "value", "one_to_one_item__name" )[0] self.assertEqual(i.one_to_one_item.pk, o2o.pk) self.assertEqual(i.name, "first") with self.assertNumQueries(1): self.assertEqual(i.one_to_one_item.name, "second") with self.assertNumQueries(1): self.assertEqual(i.value, 42) with self.assertNumQueries(1): i = Item.objects.select_related("one_to_one_item").only( "name", "one_to_one_item__item" )[0] self.assertEqual(i.one_to_one_item.pk, o2o.pk) self.assertEqual(i.name, "first") with self.assertNumQueries(1): self.assertEqual(i.one_to_one_item.name, "second") with self.assertNumQueries(1): self.assertEqual(i.value, 42) def test_defer_with_select_related(self): item1 = Item.objects.create(name="first", value=47) item2 = Item.objects.create(name="second", value=42) simple = SimpleItem.objects.create(name="simple", value="23") ItemAndSimpleItem.objects.create(item=item1, simple=simple) obj = ItemAndSimpleItem.objects.defer("item").select_related("simple").get() self.assertEqual(obj.item, item1) self.assertEqual(obj.item_id, item1.id) obj.item = item2 obj.save() obj = ItemAndSimpleItem.objects.defer("item").select_related("simple").get() self.assertEqual(obj.item, item2) self.assertEqual(obj.item_id, item2.id) def test_proxy_model_defer_with_select_related(self): # Regression for #22050 item = Item.objects.create(name="first", value=47) RelatedItem.objects.create(item=item) # Defer fields with only() obj = ProxyRelated.objects.select_related().only("item__name")[0] with self.assertNumQueries(0): self.assertEqual(obj.item.name, "first") with self.assertNumQueries(1): self.assertEqual(obj.item.value, 47) def test_only_with_select_related(self): # Test for #17485. item = SimpleItem.objects.create(name="first", value=47) feature = Feature.objects.create(item=item) SpecialFeature.objects.create(feature=feature) qs = Feature.objects.only("item__name").select_related("item") self.assertEqual(len(qs), 1) qs = SpecialFeature.objects.only("feature__item__name").select_related( "feature__item" ) self.assertEqual(len(qs), 1) def test_defer_annotate_select_related(self): location = Location.objects.create() Request.objects.create(location=location) self.assertIsInstance( list( Request.objects.annotate(Count("items")) .select_related("profile", "location") .only("profile", "location") ), list, ) self.assertIsInstance( list( Request.objects.annotate(Count("items")) .select_related("profile", "location") .only("profile__profile1", "location__location1") ), list, ) self.assertIsInstance( list( Request.objects.annotate(Count("items")) .select_related("profile", "location") .defer("request1", "request2", "request3", "request4") ), list, ) def test_common_model_different_mask(self): child = Child.objects.create(name="Child", value=42) second_child = Child.objects.create(name="Second", value=64) Leaf.objects.create(child=child, second_child=second_child) with self.assertNumQueries(1): leaf = ( Leaf.objects.select_related("child", "second_child") .defer("child__name", "second_child__value") .get() ) self.assertEqual(leaf.child, child) self.assertEqual(leaf.second_child, second_child) self.assertEqual(leaf.child.get_deferred_fields(), {"name"}) self.assertEqual(leaf.second_child.get_deferred_fields(), {"value"}) with self.assertNumQueries(0): self.assertEqual(leaf.child.value, 42) self.assertEqual(leaf.second_child.name, "Second") with self.assertNumQueries(1): self.assertEqual(leaf.child.name, "Child") with self.assertNumQueries(1): self.assertEqual(leaf.second_child.value, 64) def test_defer_many_to_many_ignored(self): location = Location.objects.create() request = Request.objects.create(location=location) with self.assertNumQueries(1): self.assertEqual(Request.objects.defer("items").get(), request) def test_only_many_to_many_ignored(self): location = Location.objects.create() request = Request.objects.create(location=location) with self.assertNumQueries(1): self.assertEqual(Request.objects.only("items").get(), request) def test_defer_reverse_many_to_many_ignored(self): location = Location.objects.create() request = Request.objects.create(location=location) item = Item.objects.create(value=1) request.items.add(item) with self.assertNumQueries(1): self.assertEqual(Item.objects.defer("request").get(), item) def test_only_reverse_many_to_many_ignored(self): location = Location.objects.create() request = Request.objects.create(location=location) item = Item.objects.create(value=1) request.items.add(item) with self.assertNumQueries(1): self.assertEqual(Item.objects.only("request").get(), item) def test_self_referential_one_to_one(self): first = Item.objects.create(name="first", value=1) second = Item.objects.create(name="second", value=2, source=first) with self.assertNumQueries(1): deferred_first, deferred_second = ( Item.objects.select_related("source", "destination") .only("name", "source__name", "destination__value") .order_by("pk") ) with self.assertNumQueries(0): self.assertEqual(deferred_first.name, first.name) self.assertEqual(deferred_second.name, second.name) self.assertEqual(deferred_second.source.name, first.name) self.assertEqual(deferred_first.destination.value, second.value) with self.assertNumQueries(1): self.assertEqual(deferred_first.value, first.value) with self.assertNumQueries(1): self.assertEqual(deferred_second.source.value, first.value) with self.assertNumQueries(1): self.assertEqual(deferred_first.destination.name, second.name) class DeferDeletionSignalsTests(TestCase): senders = [Item, Proxy] @classmethod def setUpTestData(cls): cls.item_pk = Item.objects.create(value=1).pk def setUp(self): self.pre_delete_senders = [] self.post_delete_senders = [] for sender in self.senders: models.signals.pre_delete.connect(self.pre_delete_receiver, sender) self.addCleanup( models.signals.pre_delete.disconnect, self.pre_delete_receiver, sender ) models.signals.post_delete.connect(self.post_delete_receiver, sender) self.addCleanup( models.signals.post_delete.disconnect, self.post_delete_receiver, sender ) def pre_delete_receiver(self, sender, **kwargs): self.pre_delete_senders.append(sender) def post_delete_receiver(self, sender, **kwargs): self.post_delete_senders.append(sender) def test_delete_defered_model(self): Item.objects.only("value").get(pk=self.item_pk).delete() self.assertEqual(self.pre_delete_senders, [Item]) self.assertEqual(self.post_delete_senders, [Item]) def test_delete_defered_proxy_model(self): Proxy.objects.only("value").get(pk=self.item_pk).delete() self.assertEqual(self.pre_delete_senders, [Proxy]) self.assertEqual(self.post_delete_senders, [Proxy]) class DeferCopyInstanceTests(TestCase): @classmethod def setUpTestData(cls): SimpleItem.objects.create(name="test", value=42) cls.deferred_item = SimpleItem.objects.defer("value").first() cls.deferred_item.pk = None cls.deferred_item._state.adding = True cls.expected_msg = ( "Cannot retrieve deferred field 'value' from an unsaved model." ) def test_save(self): with self.assertRaisesMessage(AttributeError, self.expected_msg): self.deferred_item.save(force_insert=True) with self.assertRaisesMessage(AttributeError, self.expected_msg): self.deferred_item.save() def test_bulk_create(self): with self.assertRaisesMessage(AttributeError, self.expected_msg): SimpleItem.objects.bulk_create([self.deferred_item])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_formsets/test_uuid.py
tests/model_formsets/test_uuid.py
from django.forms.models import inlineformset_factory from django.test import TestCase from .models import ( AutoPKChildOfUUIDPKParent, AutoPKParent, ChildRelatedViaAK, ChildWithEditablePK, ParentWithUUIDAlternateKey, UUIDPKChild, UUIDPKChildOfAutoPKParent, UUIDPKParent, ) class InlineFormsetTests(TestCase): def test_inlineformset_factory_nulls_default_pks(self): """ #24377 - If we're adding a new object, a parent's auto-generated pk from the model field default should be ignored as it's regenerated on the save request. Tests the case where both the parent and child have a UUID primary key. """ FormSet = inlineformset_factory(UUIDPKParent, UUIDPKChild, fields="__all__") formset = FormSet() self.assertIsNone(formset.forms[0].fields["parent"].initial) def test_inlineformset_factory_ignores_default_pks_on_submit(self): """ #24377 - Inlines with a model field default should ignore that default value to avoid triggering validation on empty forms. """ FormSet = inlineformset_factory(UUIDPKParent, UUIDPKChild, fields="__all__") formset = FormSet( { "uuidpkchild_set-TOTAL_FORMS": 3, "uuidpkchild_set-INITIAL_FORMS": 0, "uuidpkchild_set-MAX_NUM_FORMS": "", "uuidpkchild_set-0-name": "Foo", "uuidpkchild_set-1-name": "", "uuidpkchild_set-2-name": "", } ) self.assertTrue(formset.is_valid()) self.assertIsNone(formset.instance.uuid) self.assertIsNone(formset.forms[0].instance.parent_id) def test_inlineformset_factory_nulls_default_pks_uuid_parent_auto_child(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with a UUID primary key and a child object with an AutoField primary key. """ FormSet = inlineformset_factory( UUIDPKParent, AutoPKChildOfUUIDPKParent, fields="__all__" ) formset = FormSet() self.assertIsNone(formset.forms[0].fields["parent"].initial) def test_inlineformset_factory_nulls_default_pks_auto_parent_uuid_child(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with an AutoField primary key and a child object with a UUID primary key. """ FormSet = inlineformset_factory( AutoPKParent, UUIDPKChildOfAutoPKParent, fields="__all__" ) formset = FormSet() self.assertIsNone(formset.forms[0].fields["parent"].initial) def test_inlineformset_factory_nulls_default_pks_child_editable_pk(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with a UUID primary key and a child object with an editable natural key for a primary key. """ FormSet = inlineformset_factory( UUIDPKParent, ChildWithEditablePK, fields="__all__" ) formset = FormSet() self.assertIsNone(formset.forms[0].fields["parent"].initial) def test_inlineformset_factory_nulls_default_pks_alternate_key_relation(self): """ #24958 - Variant of test_inlineformset_factory_nulls_default_pks for the case of a parent object with a UUID alternate key and a child object that relates to that alternate key. """ FormSet = inlineformset_factory( ParentWithUUIDAlternateKey, ChildRelatedViaAK, fields="__all__" ) formset = FormSet() self.assertIsNone(formset.forms[0].fields["parent"].initial) def test_inlineformset_factory_nulls_default_pks_alternate_key_relation_data(self): """ If form data is provided, a parent's auto-generated alternate key is set. """ FormSet = inlineformset_factory( ParentWithUUIDAlternateKey, ChildRelatedViaAK, fields="__all__" ) formset = FormSet( { "childrelatedviaak_set-TOTAL_FORMS": 3, "childrelatedviaak_set-INITIAL_FORMS": 0, "childrelatedviaak_set-MAX_NUM_FORMS": "", "childrelatedviaak_set-0-name": "Test", "childrelatedviaak_set-1-name": "", "childrelatedviaak_set-2-name": "", } ) self.assertIs(formset.is_valid(), True) self.assertIsNotNone(formset.instance.uuid) self.assertEqual(formset.forms[0].instance.parent_id, formset.instance.uuid)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_formsets/models.py
tests/model_formsets/models.py
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" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_formsets/__init__.py
tests/model_formsets/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/model_formsets/tests.py
tests/model_formsets/tests.py
import datetime import re from datetime import date from decimal import Decimal from django import forms from django.core.exceptions import ImproperlyConfigured from django.db import models from django.forms.formsets import formset_factory from django.forms.models import ( BaseModelFormSet, ModelForm, _get_foreign_key, inlineformset_factory, modelformset_factory, ) from django.forms.renderers import DjangoTemplates 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.assertSequenceEqual( instances[0].authors.all(), [author1, author4, author2, author3], ) 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. a1 = Author.objects.create(name="Charles Baudelaire") a2 = Author.objects.create(name="Paul Verlaine") a3 = 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.assertSequenceEqual(formset.get_queryset(), [a1, a2, a3]) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=0) formset = AuthorFormSet(queryset=qs) self.assertSequenceEqual(formset.get_queryset(), [a1, a2, a3]) AuthorFormSet = modelformset_factory(Author, fields="__all__", max_num=4) formset = AuthorFormSet(queryset=qs) self.assertSequenceEqual(formset.get_queryset(), [a1, a2, a3]) 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.assertSequenceEqual(author.book_set.all(), [book1]) # 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.assertSequenceEqual(author.book_set.order_by("title"), [book1, book2]) 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">'
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_writer.py
tests/migrations/test_writer.py
import datetime import decimal import enum import functools import math import os import pathlib import re import sys import time import uuid import zoneinfo from types import NoneType from unittest import mock import custom_migration_operations.more_operations import custom_migration_operations.operations from django import get_version from django.conf import SettingsReference, settings from django.core.validators import EmailValidator, RegexValidator from django.db import migrations, models from django.db.migrations.serializer import BaseSerializer from django.db.migrations.writer import MigrationWriter, OperationWriter from django.test import SimpleTestCase, override_settings from django.test.utils import extend_sys_path from django.utils.deconstruct import deconstructible from django.utils.functional import SimpleLazyObject from django.utils.timezone import get_default_timezone, get_fixed_timezone from django.utils.translation import gettext_lazy as _ from .models import FoodManager, FoodQuerySet def get_choices(): return [(i, str(i)) for i in range(3)] class DeconstructibleInstances: def deconstruct(self): return ("DeconstructibleInstances", [], {}) @deconstructible class DeconstructibleArbitrary: def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs class Money(decimal.Decimal): def deconstruct(self): return ( "%s.%s" % (self.__class__.__module__, self.__class__.__name__), [str(self)], {}, ) class TestModel1: def upload_to(self): return "/somewhere/dynamic/" thing = models.FileField(upload_to=upload_to) class TextEnum(enum.Enum): A = "a-value" B = "value-b" class TextTranslatedEnum(enum.Enum): A = _("a-value") B = _("value-b") class BinaryEnum(enum.Enum): A = b"a-value" B = b"value-b" class IntEnum(enum.IntEnum): A = 1 B = 2 class IntFlagEnum(enum.IntFlag): A = 1 B = 2 def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): return f(*args, **kwargs) return wrapper @decorator def function_with_decorator(): pass @functools.cache def function_with_cache(): pass @functools.lru_cache(maxsize=10) def function_with_lru_cache(): pass class OperationWriterTests(SimpleTestCase): def test_empty_signature(self): operation = custom_migration_operations.operations.TestOperation() buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.TestOperation(\n),", ) def test_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation(1, 2) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1=1,\n" " arg2=2,\n" "),", ) def test_kwargs_signature(self): operation = custom_migration_operations.operations.KwargsOperation(kwarg1=1) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=1,\n" "),", ) def test_args_kwargs_signature(self): operation = custom_migration_operations.operations.ArgsKwargsOperation( 1, 2, kwarg2=4 ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsKwargsOperation(\n" " arg1=1,\n" " arg2=2,\n" " kwarg2=4,\n" "),", ) def test_keyword_only_args_signature(self): operation = ( custom_migration_operations.operations.ArgsAndKeywordOnlyArgsOperation( 1, 2, kwarg1=3, kwarg2=4 ) ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsAndKeywordOnlyArgsOperation(\n" " arg1=1,\n" " arg2=2,\n" " kwarg1=3,\n" " kwarg2=4,\n" "),", ) def test_nested_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation( custom_migration_operations.operations.ArgsOperation(1, 2), custom_migration_operations.operations.KwargsOperation(kwarg1=3, kwarg2=4), ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1=custom_migration_operations.operations.ArgsOperation(\n" " arg1=1,\n" " arg2=2,\n" " ),\n" " arg2=custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=3,\n" " kwarg2=4,\n" " ),\n" "),", ) def test_multiline_args_signature(self): operation = custom_migration_operations.operations.ArgsOperation( "test\n arg1", "test\narg2" ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ArgsOperation(\n" " arg1='test\\n arg1',\n" " arg2='test\\narg2',\n" "),", ) def test_expand_args_signature(self): operation = custom_migration_operations.operations.ExpandArgsOperation([1, 2]) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ExpandArgsOperation(\n" " arg=[\n" " 1,\n" " 2,\n" " ],\n" "),", ) def test_nested_operation_expand_args_signature(self): operation = custom_migration_operations.operations.ExpandArgsOperation( arg=[ custom_migration_operations.operations.KwargsOperation( kwarg1=1, kwarg2=2, ), ] ) buff, imports = OperationWriter(operation, indentation=0).serialize() self.assertEqual(imports, {"import custom_migration_operations.operations"}) self.assertEqual( buff, "custom_migration_operations.operations.ExpandArgsOperation(\n" " arg=[\n" " custom_migration_operations.operations.KwargsOperation(\n" " kwarg1=1,\n" " kwarg2=2,\n" " ),\n" " ],\n" "),", ) class WriterTests(SimpleTestCase): """ Tests the migration writer (makes migration files from Migration instances) """ class NestedEnum(enum.IntEnum): A = 1 B = 2 class NestedChoices(models.TextChoices): X = "X", "X value" Y = "Y", "Y value" @classmethod def method(cls): return cls.X def safe_exec(self, string, value=None): d = {} try: exec(string, globals(), d) except Exception as e: if value: self.fail( "Could not exec %r (from value %r): %s" % (string.strip(), value, e) ) else: self.fail("Could not exec %r: %s" % (string.strip(), e)) return d def serialize_round_trip(self, value): string, imports = MigrationWriter.serialize(value) return self.safe_exec( "%s\ntest_value_result = %s" % ("\n".join(imports), string), value )["test_value_result"] def assertSerializedEqual(self, value): self.assertEqual(self.serialize_round_trip(value), value) def assertSerializedResultEqual(self, value, target): self.assertEqual(MigrationWriter.serialize(value), target) def assertSerializedFieldEqual(self, value): new_value = self.serialize_round_trip(value) self.assertEqual(value.__class__, new_value.__class__) self.assertEqual(value.max_length, new_value.max_length) self.assertEqual(value.null, new_value.null) self.assertEqual(value.unique, new_value.unique) def assertSerializedFunctoolsPartialEqual( self, value, expected_string, expected_imports ): string, imports = MigrationWriter.serialize(value) self.assertEqual(string, expected_string) self.assertEqual(imports, expected_imports) result = self.serialize_round_trip(value) self.assertEqual(result.func, value.func) self.assertEqual(result.args, value.args) self.assertEqual(result.keywords, value.keywords) return result def test_serialize_numbers(self): self.assertSerializedEqual(1) self.assertSerializedEqual(1.2) self.assertTrue(math.isinf(self.serialize_round_trip(float("inf")))) self.assertTrue(math.isinf(self.serialize_round_trip(float("-inf")))) self.assertTrue(math.isnan(self.serialize_round_trip(float("nan")))) self.assertSerializedEqual(decimal.Decimal("1.3")) self.assertSerializedResultEqual( decimal.Decimal("1.3"), ("Decimal('1.3')", {"from decimal import Decimal"}) ) self.assertSerializedEqual(Money("1.3")) self.assertSerializedResultEqual( Money("1.3"), ("migrations.test_writer.Money('1.3')", {"import migrations.test_writer"}), ) def test_serialize_constants(self): self.assertSerializedEqual(None) self.assertSerializedEqual(True) self.assertSerializedEqual(False) def test_serialize_strings(self): self.assertSerializedEqual(b"foobar") string, imports = MigrationWriter.serialize(b"foobar") self.assertEqual(string, "b'foobar'") self.assertSerializedEqual("föobár") string, imports = MigrationWriter.serialize("foobar") self.assertEqual(string, "'foobar'") def test_serialize_multiline_strings(self): self.assertSerializedEqual(b"foo\nbar") string, imports = MigrationWriter.serialize(b"foo\nbar") self.assertEqual(string, "b'foo\\nbar'") self.assertSerializedEqual("föo\nbár") string, imports = MigrationWriter.serialize("foo\nbar") self.assertEqual(string, "'foo\\nbar'") def test_serialize_collections(self): self.assertSerializedEqual({1: 2}) self.assertSerializedEqual(["a", 2, True, None]) self.assertSerializedEqual({2, 3, "eighty"}) self.assertSerializedEqual({"lalalala": ["yeah", "no", "maybe"]}) self.assertSerializedEqual(_("Hello")) def test_serialize_builtin_types(self): self.assertSerializedEqual([list, tuple, dict, set, frozenset]) self.assertSerializedResultEqual( [list, tuple, dict, set, frozenset], ("[list, tuple, dict, set, frozenset]", set()), ) def test_serialize_lazy_objects(self): pattern = re.compile(r"^foo$") lazy_pattern = SimpleLazyObject(lambda: pattern) self.assertEqual(self.serialize_round_trip(lazy_pattern), pattern) def test_serialize_enums(self): self.assertSerializedResultEqual( TextEnum.A, ("migrations.test_writer.TextEnum['A']", {"import migrations.test_writer"}), ) self.assertSerializedResultEqual( TextTranslatedEnum.A, ( "migrations.test_writer.TextTranslatedEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( BinaryEnum.A, ( "migrations.test_writer.BinaryEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( IntEnum.B, ("migrations.test_writer.IntEnum['B']", {"import migrations.test_writer"}), ) self.assertSerializedResultEqual( self.NestedEnum.A, ( "migrations.test_writer.WriterTests.NestedEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedEqual(self.NestedEnum.A) field = models.CharField( default=TextEnum.B, choices=[(m.value, m) for m in TextEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "('a-value', migrations.test_writer.TextEnum['A']), " "('value-b', migrations.test_writer.TextEnum['B'])], " "default=migrations.test_writer.TextEnum['B'])", ) field = models.CharField( default=TextTranslatedEnum.A, choices=[(m.value, m) for m in TextTranslatedEnum], ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "('a-value', migrations.test_writer.TextTranslatedEnum['A']), " "('value-b', migrations.test_writer.TextTranslatedEnum['B'])], " "default=migrations.test_writer.TextTranslatedEnum['A'])", ) field = models.CharField( default=BinaryEnum.B, choices=[(m.value, m) for m in BinaryEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[" "(b'a-value', migrations.test_writer.BinaryEnum['A']), " "(b'value-b', migrations.test_writer.BinaryEnum['B'])], " "default=migrations.test_writer.BinaryEnum['B'])", ) field = models.IntegerField( default=IntEnum.A, choices=[(m.value, m) for m in IntEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[" "(1, migrations.test_writer.IntEnum['A']), " "(2, migrations.test_writer.IntEnum['B'])], " "default=migrations.test_writer.IntEnum['A'])", ) def test_serialize_enum_flags(self): self.assertSerializedResultEqual( IntFlagEnum.A, ( "migrations.test_writer.IntFlagEnum['A']", {"import migrations.test_writer"}, ), ) self.assertSerializedResultEqual( IntFlagEnum.B, ( "migrations.test_writer.IntFlagEnum['B']", {"import migrations.test_writer"}, ), ) field = models.IntegerField( default=IntFlagEnum.A, choices=[(m.value, m) for m in IntFlagEnum] ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[" "(1, migrations.test_writer.IntFlagEnum['A']), " "(2, migrations.test_writer.IntFlagEnum['B'])], " "default=migrations.test_writer.IntFlagEnum['A'])", ) self.assertSerializedResultEqual( IntFlagEnum.A | IntFlagEnum.B, ( "migrations.test_writer.IntFlagEnum['A'] | " "migrations.test_writer.IntFlagEnum['B']", {"import migrations.test_writer"}, ), ) def test_serialize_choices(self): class TextChoices(models.TextChoices): A = "A", "A value" B = "B", "B value" class IntegerChoices(models.IntegerChoices): A = 1, "One" B = 2, "Two" class DateChoices(datetime.date, models.Choices): DATE_1 = 1969, 7, 20, "First date" DATE_2 = 1969, 11, 19, "Second date" self.assertSerializedResultEqual(TextChoices.A, ("'A'", set())) self.assertSerializedResultEqual(IntegerChoices.A, ("1", set())) self.assertSerializedResultEqual( DateChoices.DATE_1, ("datetime.date(1969, 7, 20)", {"import datetime"}), ) field = models.CharField(default=TextChoices.B, choices=TextChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.CharField(choices=[('A', 'A value'), ('B', 'B value')], " "default='B')", ) field = models.IntegerField(default=IntegerChoices.B, choices=IntegerChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[(1, 'One'), (2, 'Two')], default=2)", ) field = models.DateField(default=DateChoices.DATE_2, choices=DateChoices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.DateField(choices=[" "(datetime.date(1969, 7, 20), 'First date'), " "(datetime.date(1969, 11, 19), 'Second date')], " "default=datetime.date(1969, 11, 19))", ) def test_serialize_dictionary_choices(self): for choices in ({"Group": [(2, "2"), (1, "1")]}, {"Group": {2: "2", 1: "1"}}): with self.subTest(choices): field = models.IntegerField(choices=choices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=[('Group', [(2, '2'), (1, '1')])])", ) def test_serialize_callable_choices(self): field = models.IntegerField(choices=get_choices) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.IntegerField(choices=migrations.test_writer.get_choices)", ) def test_serialize_nested_class(self): for nested_cls in [self.NestedEnum, self.NestedChoices]: cls_name = nested_cls.__name__ with self.subTest(cls_name): self.assertSerializedResultEqual( nested_cls, ( "migrations.test_writer.WriterTests.%s" % cls_name, {"import migrations.test_writer"}, ), ) def test_serialize_nested_class_method(self): self.assertSerializedResultEqual( self.NestedChoices.method, ( "migrations.test_writer.WriterTests.NestedChoices.method", {"import migrations.test_writer"}, ), ) def test_serialize_uuid(self): self.assertSerializedEqual(uuid.uuid1()) self.assertSerializedEqual(uuid.uuid4()) uuid_a = uuid.UUID("5c859437-d061-4847-b3f7-e6b78852f8c8") uuid_b = uuid.UUID("c7853ec1-2ea3-4359-b02d-b54e8f1bcee2") self.assertSerializedResultEqual( uuid_a, ("uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8')", {"import uuid"}), ) self.assertSerializedResultEqual( uuid_b, ("uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2')", {"import uuid"}), ) field = models.UUIDField( choices=((uuid_a, "UUID A"), (uuid_b, "UUID B")), default=uuid_a ) string = MigrationWriter.serialize(field)[0] self.assertEqual( string, "models.UUIDField(choices=[" "(uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'), 'UUID A'), " "(uuid.UUID('c7853ec1-2ea3-4359-b02d-b54e8f1bcee2'), 'UUID B')], " "default=uuid.UUID('5c859437-d061-4847-b3f7-e6b78852f8c8'))", ) def test_serialize_pathlib(self): # Pure path objects work in all platforms. self.assertSerializedEqual(pathlib.PurePosixPath()) self.assertSerializedEqual(pathlib.PureWindowsPath()) path = pathlib.PurePosixPath("/path/file.txt") expected = ("pathlib.PurePosixPath('/path/file.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) path = pathlib.PureWindowsPath("A:\\File.txt") expected = ("pathlib.PureWindowsPath('A:/File.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) # Concrete path objects work on supported platforms. if sys.platform == "win32": self.assertSerializedEqual(pathlib.WindowsPath.cwd()) path = pathlib.WindowsPath("A:\\File.txt") expected = ("pathlib.PureWindowsPath('A:/File.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) else: self.assertSerializedEqual(pathlib.PosixPath.cwd()) path = pathlib.PosixPath("/path/file.txt") expected = ("pathlib.PurePosixPath('/path/file.txt')", {"import pathlib"}) self.assertSerializedResultEqual(path, expected) field = models.FilePathField(path=pathlib.PurePosixPath("/home/user")) string, imports = MigrationWriter.serialize(field) self.assertEqual( string, "models.FilePathField(path=pathlib.PurePosixPath('/home/user'))", ) self.assertIn("import pathlib", imports) def test_serialize_path_like(self): with os.scandir(os.path.dirname(__file__)) as entries: path_like = list(entries)[0] expected = (repr(path_like.path), {}) self.assertSerializedResultEqual(path_like, expected) field = models.FilePathField(path=path_like) string = MigrationWriter.serialize(field)[0] self.assertEqual(string, "models.FilePathField(path=%r)" % path_like.path) def test_serialize_zoneinfo(self): self.assertSerializedEqual(zoneinfo.ZoneInfo("Asia/Kolkata")) self.assertSerializedResultEqual( zoneinfo.ZoneInfo("Asia/Kolkata"), ( "zoneinfo.ZoneInfo(key='Asia/Kolkata')", {"import zoneinfo"}, ), ) self.assertSerializedResultEqual( zoneinfo.ZoneInfo("Europe/Paris"), ("zoneinfo.ZoneInfo(key='Europe/Paris')", {"import zoneinfo"}), ) def test_serialize_functions(self): with self.assertRaisesMessage(ValueError, "Cannot serialize function: lambda"): self.assertSerializedEqual(lambda x: 42) self.assertSerializedEqual(models.SET_NULL) string, imports = MigrationWriter.serialize(models.SET(42)) self.assertEqual(string, "models.SET(42)") self.serialize_round_trip(models.SET(42)) def test_serialize_decorated_functions(self): self.assertSerializedEqual(function_with_decorator) self.assertSerializedEqual(function_with_cache) self.assertSerializedEqual(function_with_lru_cache) def test_serialize_datetime(self): self.assertSerializedEqual(datetime.datetime.now()) self.assertSerializedEqual(datetime.datetime.now) self.assertSerializedEqual(datetime.datetime.today()) self.assertSerializedEqual(datetime.datetime.today) self.assertSerializedEqual(datetime.date.today()) self.assertSerializedEqual(datetime.date.today) self.assertSerializedEqual(datetime.datetime.now().time()) self.assertSerializedEqual( datetime.datetime(2014, 1, 1, 1, 1, tzinfo=get_default_timezone()) ) self.assertSerializedEqual( datetime.datetime(2013, 12, 31, 22, 1, tzinfo=get_fixed_timezone(180)) ) self.assertSerializedResultEqual( datetime.datetime(2014, 1, 1, 1, 1), ("datetime.datetime(2014, 1, 1, 1, 1)", {"import datetime"}), ) self.assertSerializedResultEqual( datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.UTC), ( "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc)", {"import datetime"}, ), ) self.assertSerializedResultEqual( datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc), ( "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc)", {"import datetime"}, ), ) self.assertSerializedResultEqual( datetime.datetime( 2012, 1, 1, 2, 1, tzinfo=zoneinfo.ZoneInfo("Europe/Paris") ), ( "datetime.datetime(2012, 1, 1, 1, 1, tzinfo=datetime.timezone.utc)", {"import datetime"}, ), ) def test_serialize_fields(self): self.assertSerializedFieldEqual(models.CharField(max_length=255)) self.assertSerializedResultEqual( models.CharField(max_length=255), ("models.CharField(max_length=255)", {"from django.db import models"}), ) self.assertSerializedFieldEqual(models.TextField(null=True, blank=True)) self.assertSerializedResultEqual( models.TextField(null=True, blank=True), ( "models.TextField(blank=True, null=True)", {"from django.db import models"}, ), ) def test_serialize_settings(self): self.assertSerializedEqual( SettingsReference(settings.AUTH_USER_MODEL, "AUTH_USER_MODEL") ) self.assertSerializedResultEqual( SettingsReference("someapp.model", "AUTH_USER_MODEL"), ("settings.AUTH_USER_MODEL", {"from django.conf import settings"}), ) def test_serialize_iterators(self): self.assertSerializedResultEqual( ((x, x * x) for x in range(3)), ("((0, 0), (1, 1), (2, 4))", set()) ) def test_serialize_compiled_regex(self): """ Make sure compiled regex can be serialized. """ regex = re.compile(r"^\w+$") self.assertSerializedEqual(regex) def test_serialize_class_based_validators(self): """ Ticket #22943: Test serialization of class-based validators, including compiled regexes. """ validator = RegexValidator(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator(message='hello')" ) self.serialize_round_trip(validator) # Test with a compiled regex. validator = RegexValidator(regex=re.compile(r"^\w+$")) string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator(regex=re.compile('^\\\\w+$'))", ) self.serialize_round_trip(validator) # Test a string regex with flag validator = RegexValidator(r"^[0-9]+$", flags=re.S) string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator('^[0-9]+$', " "flags=re.RegexFlag['DOTALL'])", ) self.serialize_round_trip(validator) # Test message and code validator = RegexValidator("^[-a-zA-Z0-9_]+$", "Invalid", "invalid") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.RegexValidator('^[-a-zA-Z0-9_]+$', 'Invalid', " "'invalid')", ) self.serialize_round_trip(validator) # Test with a subclass. validator = EmailValidator(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "django.core.validators.EmailValidator(message='hello')" ) self.serialize_round_trip(validator) validator = deconstructible(path="migrations.test_writer.EmailValidator")( EmailValidator )(message="hello") string = MigrationWriter.serialize(validator)[0] self.assertEqual( string, "migrations.test_writer.EmailValidator(message='hello')" ) validator = deconstructible(path="custom.EmailValidator")(EmailValidator)( message="hello" ) with self.assertRaisesMessage(ImportError, "No module named 'custom'"): MigrationWriter.serialize(validator) validator = deconstructible(path="django.core.validators.EmailValidator2")( EmailValidator )(message="hello") with self.assertRaisesMessage( ValueError, "Could not find object EmailValidator2 in django.core.validators.", ): MigrationWriter.serialize(validator) def test_serialize_complex_func_index(self): index = models.Index( models.Func("rating", function="ABS"), models.Case( models.When(name="special", then=models.Value("X")), default=models.Value("other"), ), models.ExpressionWrapper( models.F("pages"), output_field=models.IntegerField(), ), models.OrderBy(models.F("name").desc()), name="complex_func_index", ) string, imports = MigrationWriter.serialize(index) self.assertEqual( string, "models.Index(models.Func('rating', function='ABS'), " "models.Case(models.When(name='special', then=models.Value('X')), " "default=models.Value('other')), " "models.ExpressionWrapper(" "models.F('pages'), output_field=models.IntegerField()), " "models.OrderBy(models.OrderBy(models.F('name'), descending=True)), " "name='complex_func_index')", ) self.assertEqual(imports, {"from django.db import models"}) def test_serialize_empty_nonempty_tuple(self): """ Ticket #22679: makemigrations generates invalid code for (an empty tuple) default_permissions = () """ empty_tuple = () one_item_tuple = ("a",) many_items_tuple = ("a", "b", "c") self.assertSerializedEqual(empty_tuple) self.assertSerializedEqual(one_item_tuple) self.assertSerializedEqual(many_items_tuple) def test_serialize_range(self): string, imports = MigrationWriter.serialize(range(1, 5)) self.assertEqual(string, "range(1, 5)") self.assertEqual(imports, set()) def test_serialize_builtins(self): string, imports = MigrationWriter.serialize(range) self.assertEqual(string, "range") self.assertEqual(imports, set()) def test_serialize_unbound_method_reference(self): """An unbound method used within a class body can be serialized.""" self.serialize_round_trip(TestModel1.thing) def test_serialize_local_function_reference(self): """A reference in a local scope can't be serialized.""" class TestModel2: def upload_to(self): return "somewhere dynamic" thing = models.FileField(upload_to=upload_to) with self.assertRaisesMessage( ValueError, "Could not find function upload_to in migrations.test_writer" ): self.serialize_round_trip(TestModel2.thing) def test_serialize_managers(self): self.assertSerializedEqual(models.Manager()) self.assertSerializedResultEqual( FoodQuerySet.as_manager(), (
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_loader.py
tests/migrations/test_loader.py
import compileall import os import subprocess import sys import tempfile from importlib import import_module from pathlib import Path from django.conf import settings from django.db import connection, connections from django.db.migrations.exceptions import ( AmbiguityError, InconsistentMigrationHistory, NodeNotFoundError, ) from django.db.migrations.loader import MigrationLoader from django.db.migrations.recorder import MigrationRecorder from django.test import TestCase, modify_settings, override_settings from .test_base import MigrationTestBase class RecorderTests(TestCase): """ Tests recording migrations as applied or not. """ databases = {"default", "other"} def test_apply(self): """ Tests marking migrations as applied/unapplied. """ recorder = MigrationRecorder(connection) self.assertEqual( {(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"}, set(), ) recorder.record_applied("myapp", "0432_ponies") self.assertEqual( {(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"}, {("myapp", "0432_ponies")}, ) # That should not affect records of another database recorder_other = MigrationRecorder(connections["other"]) self.assertEqual( {(x, y) for (x, y) in recorder_other.applied_migrations() if x == "myapp"}, set(), ) recorder.record_unapplied("myapp", "0432_ponies") self.assertEqual( {(x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"}, set(), ) def test_has_table_cached(self): """ The has_table() method caches a positive result and not continually query for the existence of the migrations table. """ recorder = MigrationRecorder(connection) self.assertIs(recorder.has_table(), True) with self.assertNumQueries(0): self.assertIs(recorder.has_table(), True) class LoaderTests(TestCase): """ Tests the disk and database loader, and running through migrations in memory. """ def setUp(self): self.applied_records = [] def tearDown(self): # Unapply records on databases that don't roll back changes after each # test method. if not connection.features.supports_transactions: for recorder, app, name in self.applied_records: recorder.record_unapplied(app, name) def record_applied(self, recorder, app, name): recorder.record_applied(app, name) self.applied_records.append((recorder, app, name)) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) @modify_settings(INSTALLED_APPS={"append": "basic"}) def test_load(self): """ Makes sure the loader can load the migrations for the test apps, and then render them out to a new Apps. """ # Load and test the plan migration_loader = MigrationLoader(connection) self.assertEqual( migration_loader.graph.forwards_plan(("migrations", "0002_second")), [ ("migrations", "0001_initial"), ("migrations", "0002_second"), ], ) # Now render it out! project_state = migration_loader.project_state(("migrations", "0002_second")) self.assertEqual(len(project_state.models), 2) author_state = project_state.models["migrations", "author"] self.assertEqual( list(author_state.fields), ["id", "name", "slug", "age", "rating"] ) book_state = project_state.models["migrations", "book"] self.assertEqual(list(book_state.fields), ["id", "author"]) # Ensure we've included unmigrated apps in there too self.assertIn("basic", project_state.real_apps) @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations", "migrations2": "migrations2.test_migrations_2", } ) @modify_settings(INSTALLED_APPS={"append": "migrations2"}) def test_plan_handles_repeated_migrations(self): """ _generate_plan() doesn't readd migrations already in the plan (#29180). """ migration_loader = MigrationLoader(connection) nodes = [("migrations", "0002_second"), ("migrations2", "0001_initial")] self.assertEqual( migration_loader.graph._generate_plan(nodes, at_end=True), [ ("migrations", "0001_initial"), ("migrations", "0002_second"), ("migrations2", "0001_initial"), ], ) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_unmigdep"} ) def test_load_unmigrated_dependency(self): """ The loader can load migrations with a dependency on an unmigrated app. """ # Load and test the plan migration_loader = MigrationLoader(connection) self.assertEqual( migration_loader.graph.forwards_plan(("migrations", "0001_initial")), [ ("contenttypes", "0001_initial"), ("auth", "0001_initial"), ("migrations", "0001_initial"), ], ) # Now render it out! project_state = migration_loader.project_state(("migrations", "0001_initial")) self.assertEqual( len([m for a, m in project_state.models if a == "migrations"]), 1 ) book_state = project_state.models["migrations", "book"] self.assertEqual(list(book_state.fields), ["id", "user"]) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"} ) def test_run_before(self): """ Makes sure the loader uses Migration.run_before. """ # Load and test the plan migration_loader = MigrationLoader(connection) self.assertEqual( migration_loader.graph.forwards_plan(("migrations", "0002_second")), [ ("migrations", "0001_initial"), ("migrations", "0003_third"), ("migrations", "0002_second"), ], ) @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations_first", "migrations2": "migrations2.test_migrations_2_first", } ) @modify_settings(INSTALLED_APPS={"append": "migrations2"}) def test_first(self): """ Makes sure the '__first__' migrations build correctly. """ migration_loader = MigrationLoader(connection) self.assertEqual( migration_loader.graph.forwards_plan(("migrations", "second")), [ ("migrations", "thefirst"), ("migrations2", "0001_initial"), ("migrations2", "0002_second"), ("migrations", "second"), ], ) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_name_match(self): "Tests prefix name matching" migration_loader = MigrationLoader(connection) self.assertEqual( migration_loader.get_migration_by_prefix("migrations", "0001").name, "0001_initial", ) msg = "There is more than one migration for 'migrations' with the prefix '0'" with self.assertRaisesMessage(AmbiguityError, msg): migration_loader.get_migration_by_prefix("migrations", "0") msg = "There is no migration for 'migrations' with the prefix 'blarg'" with self.assertRaisesMessage(KeyError, msg): migration_loader.get_migration_by_prefix("migrations", "blarg") def test_load_import_error(self): with override_settings( MIGRATION_MODULES={"migrations": "import_error_package"} ): with self.assertRaises(ImportError): MigrationLoader(connection) def test_load_module_file(self): with override_settings( MIGRATION_MODULES={"migrations": "migrations.faulty_migrations.file"} ): loader = MigrationLoader(connection) self.assertIn( "migrations", loader.unmigrated_apps, "App with migrations module file not in unmigrated apps.", ) def test_load_empty_dir(self): with override_settings( MIGRATION_MODULES={"migrations": "migrations.faulty_migrations.namespace"} ): loader = MigrationLoader(connection) self.assertIn( "migrations", loader.unmigrated_apps, "App missing __init__.py in migrations module not in unmigrated apps.", ) @override_settings( INSTALLED_APPS=["migrations.migrations_test_apps.migrated_app"], ) def test_marked_as_migrated(self): """ Undefined MIGRATION_MODULES implies default migration module. """ migration_loader = MigrationLoader(connection) self.assertEqual(migration_loader.migrated_apps, {"migrated_app"}) self.assertEqual(migration_loader.unmigrated_apps, set()) @override_settings( INSTALLED_APPS=["migrations.migrations_test_apps.migrated_app"], MIGRATION_MODULES={"migrated_app": None}, ) def test_marked_as_unmigrated(self): """ MIGRATION_MODULES allows disabling of migrations for a particular app. """ migration_loader = MigrationLoader(connection) self.assertEqual(migration_loader.migrated_apps, set()) self.assertEqual(migration_loader.unmigrated_apps, {"migrated_app"}) @override_settings( INSTALLED_APPS=["migrations.migrations_test_apps.migrated_app"], MIGRATION_MODULES={"migrated_app": "missing-module"}, ) def test_explicit_missing_module(self): """ If a MIGRATION_MODULES override points to a missing module, the error raised during the importation attempt should be propagated unless `ignore_no_migrations=True`. """ with self.assertRaisesMessage(ImportError, "missing-module"): migration_loader = MigrationLoader(connection) migration_loader = MigrationLoader(connection, ignore_no_migrations=True) self.assertEqual(migration_loader.migrated_apps, set()) self.assertEqual(migration_loader.unmigrated_apps, {"migrated_app"}) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_loading_squashed(self): "Tests loading a squashed migration" migration_loader = MigrationLoader(connection) recorder = MigrationRecorder(connection) self.addCleanup(recorder.flush) # Loading with nothing applied should just give us the one node self.assertEqual( len([x for x in migration_loader.graph.nodes if x[0] == "migrations"]), 1, ) # However, fake-apply one migration and it should now use the old two self.record_applied(recorder, "migrations", "0001_initial") migration_loader.build_graph() self.assertEqual( len([x for x in migration_loader.graph.nodes if x[0] == "migrations"]), 2, ) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"} ) def test_loading_squashed_complex(self): "Tests loading a complex set of squashed migrations" loader = MigrationLoader(connection) recorder = MigrationRecorder(connection) self.addCleanup(recorder.flush) def num_nodes(): plan = set(loader.graph.forwards_plan(("migrations", "7_auto"))) return len(plan - loader.applied_migrations.keys()) # Empty database: use squashed migration loader.build_graph() self.assertEqual(num_nodes(), 5) # Starting at 1 or 2 should use the squashed migration too self.record_applied(recorder, "migrations", "1_auto") loader.build_graph() self.assertEqual(num_nodes(), 4) self.record_applied(recorder, "migrations", "2_auto") loader.build_graph() self.assertEqual(num_nodes(), 3) # However, starting at 3 to 5 cannot use the squashed migration self.record_applied(recorder, "migrations", "3_auto") loader.build_graph() self.assertEqual(num_nodes(), 4) self.record_applied(recorder, "migrations", "4_auto") loader.build_graph() self.assertEqual(num_nodes(), 3) # Starting at 5 to 7 we are past the squashed migrations. self.record_applied(recorder, "migrations", "5_auto") loader.build_graph() self.assertEqual(num_nodes(), 2) self.record_applied(recorder, "migrations", "6_auto") loader.build_graph() self.assertEqual(num_nodes(), 1) self.record_applied(recorder, "migrations", "7_auto") loader.build_graph() self.assertEqual(num_nodes(), 0) @override_settings( MIGRATION_MODULES={ "app1": "migrations.test_migrations_squashed_complex_multi_apps.app1", "app2": "migrations.test_migrations_squashed_complex_multi_apps.app2", } ) @modify_settings( INSTALLED_APPS={ "append": [ "migrations.test_migrations_squashed_complex_multi_apps.app1", "migrations.test_migrations_squashed_complex_multi_apps.app2", ] } ) def test_loading_squashed_complex_multi_apps(self): loader = MigrationLoader(connection) loader.build_graph() plan = set(loader.graph.forwards_plan(("app1", "4_auto"))) expected_plan = { ("app1", "1_auto"), ("app2", "1_squashed_2"), ("app1", "2_squashed_3"), ("app1", "4_auto"), } self.assertEqual(plan, expected_plan) @override_settings( MIGRATION_MODULES={ "app1": "migrations.test_migrations_squashed_complex_multi_apps.app1", "app2": "migrations.test_migrations_squashed_complex_multi_apps.app2", } ) @modify_settings( INSTALLED_APPS={ "append": [ "migrations.test_migrations_squashed_complex_multi_apps.app1", "migrations.test_migrations_squashed_complex_multi_apps.app2", ] } ) def test_loading_squashed_complex_multi_apps_partially_applied(self): loader = MigrationLoader(connection) recorder = MigrationRecorder(connection) self.record_applied(recorder, "app1", "1_auto") self.record_applied(recorder, "app1", "2_auto") loader.build_graph() plan = set(loader.graph.forwards_plan(("app1", "4_auto"))) plan -= loader.applied_migrations.keys() expected_plan = { ("app2", "1_squashed_2"), ("app1", "3_auto"), ("app1", "4_auto"), } self.assertEqual(plan, expected_plan) @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations_squashed_erroneous" } ) def test_loading_squashed_erroneous(self): "Tests loading a complex but erroneous set of squashed migrations" loader = MigrationLoader(connection) recorder = MigrationRecorder(connection) self.addCleanup(recorder.flush) def num_nodes(): plan = set(loader.graph.forwards_plan(("migrations", "7_auto"))) return len(plan - loader.applied_migrations.keys()) # Empty database: use squashed migration loader.build_graph() self.assertEqual(num_nodes(), 5) # Starting at 1 or 2 should use the squashed migration too self.record_applied(recorder, "migrations", "1_auto") loader.build_graph() self.assertEqual(num_nodes(), 4) self.record_applied(recorder, "migrations", "2_auto") loader.build_graph() self.assertEqual(num_nodes(), 3) # However, starting at 3 or 4, nonexistent migrations would be needed. msg = ( "Migration migrations.6_auto depends on nonexistent node " "('migrations', '5_auto'). Django tried to replace migration " "migrations.5_auto with any of [migrations.3_squashed_5] but wasn't able " "to because some of the replaced migrations are already applied." ) self.record_applied(recorder, "migrations", "3_auto") with self.assertRaisesMessage(NodeNotFoundError, msg): loader.build_graph() self.record_applied(recorder, "migrations", "4_auto") with self.assertRaisesMessage(NodeNotFoundError, msg): loader.build_graph() # Starting at 5 to 7 we are passed the squashed migrations self.record_applied(recorder, "migrations", "5_auto") loader.build_graph() self.assertEqual(num_nodes(), 2) self.record_applied(recorder, "migrations", "6_auto") loader.build_graph() self.assertEqual(num_nodes(), 1) self.record_applied(recorder, "migrations", "7_auto") loader.build_graph() self.assertEqual(num_nodes(), 0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations"}, INSTALLED_APPS=["migrations"], ) def test_check_consistent_history(self): loader = MigrationLoader(connection=None) loader.check_consistent_history(connection) recorder = MigrationRecorder(connection) self.record_applied(recorder, "migrations", "0002_second") msg = ( "Migration migrations.0002_second is applied before its dependency " "migrations.0001_initial on database 'default'." ) with self.assertRaisesMessage(InconsistentMigrationHistory, msg): loader.check_consistent_history(connection) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_extra"}, INSTALLED_APPS=["migrations"], ) def test_check_consistent_history_squashed(self): """ MigrationLoader.check_consistent_history() should ignore unapplied squashed migrations that have all of their `replaces` applied. """ loader = MigrationLoader(connection=None) recorder = MigrationRecorder(connection) self.record_applied(recorder, "migrations", "0001_initial") self.record_applied(recorder, "migrations", "0002_second") loader.check_consistent_history(connection) self.record_applied(recorder, "migrations", "0003_third") loader.check_consistent_history(connection) @override_settings( MIGRATION_MODULES={ "app1": "migrations.test_migrations_squashed_ref_squashed.app1", "app2": "migrations.test_migrations_squashed_ref_squashed.app2", } ) @modify_settings( INSTALLED_APPS={ "append": [ "migrations.test_migrations_squashed_ref_squashed.app1", "migrations.test_migrations_squashed_ref_squashed.app2", ] } ) def test_loading_squashed_ref_squashed(self): """ Tests loading a squashed migration with a new migration referencing it """ r""" The sample migrations are structured like this: app_1 1 --> 2 ---------------------*--> 3 *--> 4 \ / / *-------------------*----/--> 2_sq_3 --* \ / / =============== \ ============= / == / ====================== app_2 *--> 1_sq_2 --* / \ / *--> 1 --> 2 --* Where 2_sq_3 is a replacing migration for 2 and 3 in app_1, as 1_sq_2 is a replacing migration for 1 and 2 in app_2. """ loader = MigrationLoader(connection) recorder = MigrationRecorder(connection) self.addCleanup(recorder.flush) # Load with nothing applied: both migrations squashed. loader.build_graph() plan = set(loader.graph.forwards_plan(("app1", "4_auto"))) plan -= loader.applied_migrations.keys() expected_plan = { ("app1", "1_auto"), ("app2", "1_squashed_2"), ("app1", "2_squashed_3"), ("app1", "4_auto"), } self.assertEqual(plan, expected_plan) # Load with nothing applied and migrate to a replaced migration. # Not possible if loader.replace_migrations is True (default). loader.build_graph() msg = "Node ('app1', '3_auto') not a valid node" with self.assertRaisesMessage(NodeNotFoundError, msg): loader.graph.forwards_plan(("app1", "3_auto")) # Possible if loader.replace_migrations is False. loader.replace_migrations = False loader.build_graph() plan = set(loader.graph.forwards_plan(("app1", "3_auto"))) plan -= loader.applied_migrations.keys() expected_plan = { ("app1", "1_auto"), ("app2", "1_auto"), ("app2", "2_auto"), ("app1", "2_auto"), ("app1", "3_auto"), } self.assertEqual(plan, expected_plan) loader.replace_migrations = True # Fake-apply a few from app1: unsquashes migration in app1. self.record_applied(recorder, "app1", "1_auto") self.record_applied(recorder, "app1", "2_auto") loader.build_graph() plan = set(loader.graph.forwards_plan(("app1", "4_auto"))) plan -= loader.applied_migrations.keys() expected_plan = { ("app2", "1_squashed_2"), ("app1", "3_auto"), ("app1", "4_auto"), } self.assertEqual(plan, expected_plan) # Fake-apply one from app2: unsquashes migration in app2 too. self.record_applied(recorder, "app2", "1_auto") loader.build_graph() plan = set(loader.graph.forwards_plan(("app1", "4_auto"))) plan -= loader.applied_migrations.keys() expected_plan = { ("app2", "2_auto"), ("app1", "3_auto"), ("app1", "4_auto"), } self.assertEqual(plan, expected_plan) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_private"} ) def test_ignore_files(self): """Files prefixed with underscore, tilde, or dot aren't loaded.""" loader = MigrationLoader(connection) loader.load_disk() migrations = [ name for app, name in loader.disk_migrations if app == "migrations" ] self.assertEqual(migrations, ["0001_initial"]) @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations_namespace_package" }, ) def test_loading_namespace_package(self): """Migration directories without an __init__.py file are ignored.""" loader = MigrationLoader(connection) loader.load_disk() migrations = [ name for app, name in loader.disk_migrations if app == "migrations" ] self.assertEqual(migrations, []) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_loading_package_without__file__(self): """ To support frozen environments, MigrationLoader loads migrations from regular packages with no __file__ attribute. """ test_module = import_module("migrations.test_migrations") loader = MigrationLoader(connection) # __file__ == __spec__.origin or the latter is None and former is # undefined. module_file = test_module.__file__ module_origin = test_module.__spec__.origin module_has_location = test_module.__spec__.has_location try: del test_module.__file__ test_module.__spec__.origin = None test_module.__spec__.has_location = False loader.load_disk() migrations = [ name for app, name in loader.disk_migrations if app == "migrations" ] self.assertCountEqual(migrations, ["0001_initial", "0002_second"]) finally: test_module.__file__ = module_file test_module.__spec__.origin = module_origin test_module.__spec__.has_location = module_has_location def test_loading_order_does_not_create_circular_dependency(self): """ Before, for these migrations: app1 [ ] 0001_squashed_initial <- replaces app1.0001 [ ] 0002_squashed_initial <- replaces app1.0001 depends on app1.0001_squashed_initial & app2.0001_squashed_initial app2 [ ] 0001_squashed_initial <- replaces app2.0001 When loading app1's migrations, if 0002_squashed_initial was first: {'0002_squashed_initial', '0001_initial', '0001_squashed_initial'} Then CircularDependencyError was raised, but it's resolvable as: {'0001_initial', '0001_squashed_initial', '0002_squashed_initial'} """ # Create a test settings file to provide to the subprocess. MIGRATION_MODULES = { "app1": "migrations.test_migrations_squashed_replaced_order.app1", "app2": "migrations.test_migrations_squashed_replaced_order.app2", } INSTALLED_APPS = [ "migrations.test_migrations_squashed_replaced_order.app1", "migrations.test_migrations_squashed_replaced_order.app2", ] tests_dir = Path(__file__).parent.parent with tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", suffix=".py", dir=tests_dir, delete=False ) as test_settings: self.addCleanup(os.remove, test_settings.name) for attr, value in settings._wrapped.__dict__.items(): # Only write builtin values so that any settings that reference # a value that needs an import are omitted. if attr.isupper() and type(value).__module__ == "builtins": test_settings.write(f"{attr} = {value!r}\n") # Provide overrides here, instead of via decorators. test_settings.write(f"DATABASES = {settings.DATABASES}\n") test_settings.write(f"MIGRATION_MODULES = {MIGRATION_MODULES}\n") # Isolate away other test apps. test_settings.write( "INSTALLED_APPS=[a for a in INSTALLED_APPS if a.startswith('django')]\n" ) test_settings.write(f"INSTALLED_APPS += {INSTALLED_APPS}\n") test_environ = os.environ.copy() test_environ["PYTHONPATH"] = str(tests_dir) # Ensure deterministic failures. test_environ["PYTHONHASHSEED"] = "1" args = [ sys.executable, "-m", "django", "showmigrations", "app1", "--skip-checks", "--settings", Path(test_settings.name).stem, ] try: subprocess.run( args, capture_output=True, env=test_environ, check=True, text=True ) except subprocess.CalledProcessError as err: self.fail(err.stderr) class PycLoaderTests(MigrationTestBase): def test_valid(self): """ To support frozen environments, MigrationLoader loads .pyc migrations. """ with self.temporary_migration_module( module="migrations.test_migrations" ) as migration_dir: # Compile .py files to .pyc files and delete .py files. compileall.compile_dir(migration_dir, force=True, quiet=1, legacy=True) for name in os.listdir(migration_dir): if name.endswith(".py"): os.remove(os.path.join(migration_dir, name)) loader = MigrationLoader(connection) self.assertIn(("migrations", "0001_initial"), loader.disk_migrations) def test_invalid(self): """ MigrationLoader reraises ImportErrors caused by "bad magic number" pyc files with a more helpful message. """ with self.temporary_migration_module( module="migrations.test_migrations_bad_pyc" ) as migration_dir: # The -tpl suffix is to avoid the pyc exclusion in MANIFEST.in. os.rename( os.path.join(migration_dir, "0001_initial.pyc-tpl"), os.path.join(migration_dir, "0001_initial.pyc"), ) msg = ( r"Couldn't import '\w+.migrations.0001_initial' as it appears " "to be a stale .pyc file." ) with self.assertRaisesRegex(ImportError, msg): MigrationLoader(connection)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_operations.py
tests/migrations/test_operations.py
import math from decimal import Decimal from django.core.exceptions import FieldDoesNotExist from django.db import IntegrityError, connection, migrations, models, transaction from django.db.migrations.migration import Migration from django.db.migrations.operations.base import Operation from django.db.migrations.operations.fields import FieldOperation from django.db.migrations.state import ModelState, ProjectState from django.db.models import F from django.db.models.expressions import Value from django.db.models.functions import Abs, Concat, Pi from django.db.transaction import atomic from django.test import ( SimpleTestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from django.test.utils import CaptureQueriesContext from .models import FoodManager, FoodQuerySet, UnicodeModel from .test_base import OperationTestBase class Mixin: pass class OperationTests(OperationTestBase): """ Tests running the operations and making sure they do what they say they do. Each test looks at their state changing, and then their database operation, both forwards and backwards. """ def test_create_model(self): """ Tests the CreateModel operation. Most other tests use this operation as part of setup, so check failures here first. """ operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], ) self.assertEqual(operation.describe(), "Create model Pony") self.assertEqual(operation.formatted_description(), "+ Create model Pony") self.assertEqual(operation.migration_name_fragment, "pony") # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony") self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2) # Test the database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["fields", "name"]) # And default manager not in set operation = migrations.CreateModel( "Foo", fields=[], managers=[("objects", models.Manager())] ) definition = operation.deconstruct() self.assertNotIn("managers", definition[2]) def test_create_model_with_duplicate_field_name(self): with self.assertRaisesMessage( ValueError, "Found duplicate value pink in CreateModel fields argument." ): migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.TextField()), ("pink", models.IntegerField(default=1)), ], ) def test_create_model_with_duplicate_base(self): message = "Found duplicate value test_crmo.pony in CreateModel bases argument." with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( "test_crmo.Pony", "test_crmo.Pony", ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( "test_crmo.Pony", "test_crmo.pony", ), ) message = ( "Found duplicate value migrations.unicodemodel in CreateModel bases " "argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, UnicodeModel, ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, "migrations.unicodemodel", ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, "migrations.UnicodeModel", ), ) message = ( "Found duplicate value <class 'django.db.models.base.Model'> in " "CreateModel bases argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( models.Model, models.Model, ), ) message = ( "Found duplicate value <class 'migrations.test_operations.Mixin'> in " "CreateModel bases argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( Mixin, Mixin, ), ) def test_create_model_with_duplicate_manager_name(self): with self.assertRaisesMessage( ValueError, "Found duplicate value objects in CreateModel managers argument.", ): migrations.CreateModel( "Pony", fields=[], managers=[ ("objects", models.Manager()), ("objects", models.Manager()), ], ) def test_create_model_with_unique_after(self): """ Tests the CreateModel operation directly followed by an AlterUniqueTogether (bug #22844 - sqlite remake issues) """ operation1 = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], ) operation2 = migrations.CreateModel( "Rider", [ ("id", models.AutoField(primary_key=True)), ("number", models.IntegerField(default=1)), ("pony", models.ForeignKey("test_crmoua.Pony", models.CASCADE)), ], ) operation3 = migrations.AlterUniqueTogether( "Rider", [ ("number", "pony"), ], ) # Test the database alteration project_state = ProjectState() self.assertTableNotExists("test_crmoua_pony") self.assertTableNotExists("test_crmoua_rider") with connection.schema_editor() as editor: new_state = project_state.clone() operation1.state_forwards("test_crmoua", new_state) operation1.database_forwards( "test_crmoua", editor, project_state, new_state ) project_state, new_state = new_state, new_state.clone() operation2.state_forwards("test_crmoua", new_state) operation2.database_forwards( "test_crmoua", editor, project_state, new_state ) project_state, new_state = new_state, new_state.clone() operation3.state_forwards("test_crmoua", new_state) operation3.database_forwards( "test_crmoua", editor, project_state, new_state ) self.assertTableExists("test_crmoua_pony") self.assertTableExists("test_crmoua_rider") def test_create_model_m2m(self): """ Test the creation of a model with a ManyToMany field and the auto-created "through" model. """ project_state = self.set_up_test_model("test_crmomm") operation = migrations.CreateModel( "Stable", [ ("id", models.AutoField(primary_key=True)), ("ponies", models.ManyToManyField("Pony", related_name="stables")), ], ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_crmomm", new_state) # Test the database alteration self.assertTableNotExists("test_crmomm_stable_ponies") with connection.schema_editor() as editor: operation.database_forwards("test_crmomm", editor, project_state, new_state) self.assertTableExists("test_crmomm_stable") self.assertTableExists("test_crmomm_stable_ponies") self.assertColumnNotExists("test_crmomm_stable", "ponies") # Make sure the M2M field actually works with atomic(): Pony = new_state.apps.get_model("test_crmomm", "Pony") Stable = new_state.apps.get_model("test_crmomm", "Stable") stable = Stable.objects.create() p1 = Pony.objects.create(pink=False, weight=4.55) p2 = Pony.objects.create(pink=True, weight=5.43) stable.ponies.add(p1, p2) self.assertEqual(stable.ponies.count(), 2) stable.ponies.all().delete() # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crmomm", editor, new_state, project_state ) self.assertTableNotExists("test_crmomm_stable") self.assertTableNotExists("test_crmomm_stable_ponies") @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys") def test_create_fk_models_to_pk_field_db_collation(self): """Creation of models with a FK to a PK with db_collation.""" collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") app_label = "test_cfkmtopkfdbc" operations = [ migrations.CreateModel( "Pony", [ ( "id", models.CharField( primary_key=True, max_length=10, db_collation=collation, ), ), ], ) ] project_state = self.apply_operations(app_label, ProjectState(), operations) # ForeignKey. new_state = project_state.clone() operation = migrations.CreateModel( "Rider", [ ("id", models.AutoField(primary_key=True)), ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # OneToOneField. new_state = project_state.clone() operation = migrations.CreateModel( "ShetlandPony", [ ( "pony", models.OneToOneField("Pony", models.CASCADE, primary_key=True), ), ("cuteness", models.IntegerField(default=1)), ], ) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_shetlandpony", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) def test_create_model_inheritance(self): """ Tests the CreateModel operation on a multi-table inheritance setup. """ project_state = self.set_up_test_model("test_crmoih") # Test the state alteration operation = migrations.CreateModel( "ShetlandPony", [ ( "pony_ptr", models.OneToOneField( "test_crmoih.Pony", models.CASCADE, auto_created=True, primary_key=True, to_field="id", serialize=False, ), ), ("cuteness", models.IntegerField(default=1)), ], ) new_state = project_state.clone() operation.state_forwards("test_crmoih", new_state) self.assertIn(("test_crmoih", "shetlandpony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crmoih_shetlandpony") with connection.schema_editor() as editor: operation.database_forwards("test_crmoih", editor, project_state, new_state) self.assertTableExists("test_crmoih_shetlandpony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crmoih", editor, new_state, project_state ) self.assertTableNotExists("test_crmoih_shetlandpony") def test_create_proxy_model(self): """ CreateModel ignores proxy models. """ project_state = self.set_up_test_model("test_crprmo") # Test the state alteration operation = migrations.CreateModel( "ProxyPony", [], options={"proxy": True}, bases=("test_crprmo.Pony",), ) self.assertEqual(operation.describe(), "Create proxy model ProxyPony") new_state = project_state.clone() operation.state_forwards("test_crprmo", new_state) self.assertIn(("test_crprmo", "proxypony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crprmo", editor, project_state, new_state) self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crprmo", editor, new_state, project_state ) self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["bases", "fields", "name", "options"]) def test_create_unmanaged_model(self): """ CreateModel ignores unmanaged models. """ project_state = self.set_up_test_model("test_crummo") # Test the state alteration operation = migrations.CreateModel( "UnmanagedPony", [], options={"proxy": True}, bases=("test_crummo.Pony",), ) self.assertEqual(operation.describe(), "Create proxy model UnmanagedPony") new_state = project_state.clone() operation.state_forwards("test_crummo", new_state) self.assertIn(("test_crummo", "unmanagedpony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crummo", editor, project_state, new_state) self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crummo", editor, new_state, project_state ) self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") @skipUnlessDBFeature("supports_table_check_constraints") def test_create_model_with_constraint(self): where = models.Q(pink__gt=2) check_constraint = models.CheckConstraint( condition=where, name="test_constraint_pony_pink_gt_2" ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ], options={"constraints": [check_constraint]}, ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) # Test database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") with connection.cursor() as cursor: with self.assertRaises(IntegrityError): cursor.execute("INSERT INTO test_crmo_pony (id, pink) VALUES (1, 1)") # Test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(definition[2]["options"]["constraints"], [check_constraint]) @skipUnlessDBFeature("supports_table_check_constraints") def test_create_model_with_boolean_expression_in_check_constraint(self): app_label = "test_crmobechc" rawsql_constraint = models.CheckConstraint( condition=models.expressions.RawSQL( "price < %s", (1000,), output_field=models.BooleanField() ), name=f"{app_label}_price_lt_1000_raw", ) wrapper_constraint = models.CheckConstraint( condition=models.expressions.ExpressionWrapper( models.Q(price__gt=500) | models.Q(price__lt=500), output_field=models.BooleanField(), ), name=f"{app_label}_price_neq_500_wrap", ) operation = migrations.CreateModel( "Product", [ ("id", models.AutoField(primary_key=True)), ("price", models.IntegerField(null=True)), ], options={"constraints": [rawsql_constraint, wrapper_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Add table. self.assertTableNotExists(app_label) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertTableExists(f"{app_label}_product") insert_sql = f"INSERT INTO {app_label}_product (id, price) VALUES (%d, %d)" with connection.cursor() as cursor: with self.assertRaises(IntegrityError): cursor.execute(insert_sql % (1, 1000)) cursor.execute(insert_sql % (1, 999)) with self.assertRaises(IntegrityError): cursor.execute(insert_sql % (2, 500)) cursor.execute(insert_sql % (2, 499)) def test_create_model_with_partial_unique_constraint(self): partial_unique_constraint = models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ("weight", models.FloatField()), ], options={"constraints": [partial_unique_constraint]}, ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) # Test database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") # Test constraint works Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [partial_unique_constraint] ) def test_create_model_with_deferred_unique_constraint(self): deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferrable_pink_constraint", deferrable=models.Deferrable.DEFERRED, ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ], options={"constraints": [deferred_unique_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) self.assertTableNotExists("test_crmo_pony") # Create table. with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1) obj.pink = 3 obj.save() else: Pony.objects.create(pink=1) # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [deferred_unique_constraint], ) @skipUnlessDBFeature("supports_covering_indexes") def test_create_model_with_covering_unique_constraint(self): covering_unique_constraint = models.UniqueConstraint( fields=["pink"], include=["weight"], name="test_constraint_pony_pink_covering_weight", ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ("weight", models.FloatField()), ], options={"constraints": [covering_unique_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) self.assertTableNotExists("test_crmo_pony") # Create table. with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1, weight=4.0) with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=7.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [covering_unique_constraint], ) def test_create_model_managers(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_cmoma") # Test the state alteration operation = migrations.CreateModel( "Food", fields=[ ("id", models.AutoField(primary_key=True)), ], managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) self.assertEqual(operation.describe(), "Create model Food") new_state = project_state.clone() operation.state_forwards("test_cmoma", new_state) self.assertIn(("test_cmoma", "food"), new_state.models) managers = new_state.models["test_cmoma", "food"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) def test_delete_model(self): """ Tests the DeleteModel operation. """ project_state = self.set_up_test_model("test_dlmo") # Test the state alteration operation = migrations.DeleteModel("Pony") self.assertEqual(operation.describe(), "Delete model Pony") self.assertEqual(operation.formatted_description(), "- Delete model Pony") self.assertEqual(operation.migration_name_fragment, "delete_pony") new_state = project_state.clone() operation.state_forwards("test_dlmo", new_state) self.assertNotIn(("test_dlmo", "pony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_dlmo", editor, project_state, new_state) self.assertTableNotExists("test_dlmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_dlmo", editor, new_state, project_state) self.assertTableExists("test_dlmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "DeleteModel") self.assertEqual(definition[1], []) self.assertEqual(list(definition[2]), ["name"]) def test_delete_proxy_model(self): """ Tests the DeleteModel operation ignores proxy models. """ project_state = self.set_up_test_model("test_dlprmo", proxy_model=True) # Test the state alteration operation = migrations.DeleteModel("ProxyPony") new_state = project_state.clone() operation.state_forwards("test_dlprmo", new_state) self.assertIn(("test_dlprmo", "proxypony"), project_state.models) self.assertNotIn(("test_dlprmo", "proxypony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") with connection.schema_editor() as editor: operation.database_forwards("test_dlprmo", editor, project_state, new_state) self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dlprmo", editor, new_state, project_state ) self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") def test_delete_mti_model(self): project_state = self.set_up_test_model("test_dlmtimo", mti_model=True) # Test the state alteration operation = migrations.DeleteModel("ShetlandPony") new_state = project_state.clone() operation.state_forwards("test_dlmtimo", new_state) self.assertIn(("test_dlmtimo", "shetlandpony"), project_state.models) self.assertNotIn(("test_dlmtimo", "shetlandpony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlmtimo_pony") self.assertTableExists("test_dlmtimo_shetlandpony") self.assertColumnExists("test_dlmtimo_shetlandpony", "pony_ptr_id") with connection.schema_editor() as editor: operation.database_forwards( "test_dlmtimo", editor, project_state, new_state ) self.assertTableExists("test_dlmtimo_pony") self.assertTableNotExists("test_dlmtimo_shetlandpony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dlmtimo", editor, new_state, project_state )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_autodetector.py
tests/migrations/test_autodetector.py
import copy import functools import re from unittest import mock from django.apps import apps from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core.validators import RegexValidator, validate_slug from django.db import connection, migrations, models from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.graph import MigrationGraph from django.db.migrations.loader import MigrationLoader from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.state import ModelState, ProjectState from django.db.models.functions import Concat, Lower, Upper from django.test import SimpleTestCase, TestCase, override_settings from django.test.utils import isolate_lru_cache from .models import FoodManager, FoodQuerySet class DeconstructibleObject: """ A custom deconstructible object. """ def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def deconstruct(self): return (self.__module__ + "." + self.__class__.__name__, self.args, self.kwargs) class BaseAutodetectorTests(TestCase): def repr_changes(self, changes, include_dependencies=False): output = "" for app_label, migrations_ in sorted(changes.items()): output += " %s:\n" % app_label for migration in migrations_: output += " %s\n" % migration.name for operation in migration.operations: output += " %s\n" % operation if include_dependencies: output += " Dependencies:\n" if migration.dependencies: for dep in migration.dependencies: output += " %s\n" % (dep,) else: output += " None\n" return output def assertNumberMigrations(self, changes, app_label, number): if len(changes.get(app_label, [])) != number: self.fail( "Incorrect number of migrations (%s) for %s (expected %s)\n%s" % ( len(changes.get(app_label, [])), app_label, number, self.repr_changes(changes), ) ) def assertMigrationDependencies(self, changes, app_label, position, dependencies): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if set(migration.dependencies) != set(dependencies): self.fail( "Migration dependencies mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, dependencies, self.repr_changes(changes, include_dependencies=True), ) ) def assertOperationTypes(self, changes, app_label, position, types): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] real_types = [ operation.__class__.__name__ for operation in migration.operations ] if types != real_types: self.fail( "Operation type mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, types, self.repr_changes(changes), ) ) def assertOperationAttributes( self, changes, app_label, position, operation_position, **attrs ): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail( "No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), ) ) operation = migration.operations[operation_position] for attr, value in attrs.items(): if getattr(operation, attr, None) != value: self.fail( "Attribute mismatch for %s.%s op #%s, %s (expected %r, got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(operation, attr, None), self.repr_changes(changes), ) ) def assertOperationFieldAttributes( self, changes, app_label, position, operation_position, **attrs ): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail( "No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), ) ) operation = migration.operations[operation_position] if not hasattr(operation, "field"): self.fail( "No field attribute for %s.%s op #%s." % ( app_label, migration.name, operation_position, ) ) field = operation.field for attr, value in attrs.items(): if getattr(field, attr, None) != value: self.fail( "Field attribute mismatch for %s.%s op #%s, field.%s (expected %r, " "got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(field, attr, None), self.repr_changes(changes), ) ) def make_project_state(self, model_states): "Shortcut to make ProjectStates from lists of predefined models" project_state = ProjectState() for model_state in model_states: project_state.add_model(model_state.clone()) return project_state def get_changes(self, before_states, after_states, questioner=None): if not isinstance(before_states, ProjectState): before_states = self.make_project_state(before_states) if not isinstance(after_states, ProjectState): after_states = self.make_project_state(after_states) return MigrationAutodetector( before_states, after_states, questioner, )._detect_changes() class AutodetectorTests(BaseAutodetectorTests): """ Tests the migration autodetector. """ author_empty = ModelState( "testapp", "Author", [("id", models.AutoField(primary_key=True))] ) author_name = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], ) author_name_null = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, null=True)), ], ) author_name_longer = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=400)), ], ) author_name_renamed = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("names", models.CharField(max_length=200)), ], ) author_name_default = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default="Ada Lovelace")), ], ) author_name_db_default = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, db_default="Ada Lovelace")), ], ) author_name_check_constraint = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], { "constraints": [ models.CheckConstraint( condition=models.Q(name__contains="Bob"), name="name_contains_bob" ) ] }, ) author_dates_of_birth_auto_now = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now=True)), ("date_time_of_birth", models.DateTimeField(auto_now=True)), ("time_of_birth", models.TimeField(auto_now=True)), ], ) author_dates_of_birth_auto_now_add = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now_add=True)), ("date_time_of_birth", models.DateTimeField(auto_now_add=True)), ("time_of_birth", models.TimeField(auto_now_add=True)), ], ) author_name_deconstructible_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ], ) author_name_deconstructible_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ], ) author_name_deconstructible_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ], ) author_name_deconstructible_4 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ], ) author_name_deconstructible_list_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 123] ), ), ], ) author_name_deconstructible_list_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 123] ), ), ], ) author_name_deconstructible_list_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 999] ), ), ], ) author_name_deconstructible_tuple_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 123) ), ), ], ) author_name_deconstructible_tuple_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 123) ), ), ], ) author_name_deconstructible_tuple_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 999) ), ), ], ) author_name_deconstructible_dict_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 123}, ), ), ], ) author_name_deconstructible_dict_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 123}, ), ), ], ) author_name_deconstructible_dict_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 999}, ), ), ], ) author_name_nested_deconstructible_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_changed_arg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2-changed"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_extra_arg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), None, a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_changed_kwarg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c-changed")), ), ), ), ], ) author_name_nested_deconstructible_extra_kwarg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), c=None, ), ), ), ], ) author_custom_pk = ModelState( "testapp", "Author", [("pk_field", models.IntegerField(primary_key=True))] ) author_with_biography_non_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField()), ("biography", models.TextField()), ], ) author_with_biography_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(blank=True)), ("biography", models.TextField(blank=True)), ], ) author_with_book = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) author_with_book_order_wrt = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={"order_with_respect_to": "book"}, ) author_renamed_with_book = ModelState( "testapp", "Writer", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) author_with_publisher_string = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher_name", models.CharField(max_length=200)), ], ) author_with_publisher = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) author_with_user = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("auth.User", models.CASCADE)), ], ) author_with_custom_user = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("thirdapp.CustomUser", models.CASCADE)), ], ) author_proxy = ModelState( "testapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",) ) author_proxy_options = ModelState( "testapp", "AuthorProxy", [], { "proxy": True, "verbose_name": "Super Author", }, ("testapp.author",), ) author_proxy_notproxy = ModelState( "testapp", "AuthorProxy", [], {}, ("testapp.author",) ) author_proxy_third = ModelState( "thirdapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",) ) author_proxy_third_notproxy = ModelState( "thirdapp", "AuthorProxy", [], {}, ("testapp.author",) ) author_proxy_proxy = ModelState( "testapp", "AAuthorProxyProxy", [], {"proxy": True}, ("testapp.authorproxy",) ) author_unmanaged = ModelState( "testapp", "AuthorUnmanaged", [], {"managed": False}, ("testapp.author",) ) author_unmanaged_managed = ModelState( "testapp", "AuthorUnmanaged", [], {}, ("testapp.author",) ) author_unmanaged_default_pk = ModelState( "testapp", "Author", [("id", models.AutoField(primary_key=True))] ) author_unmanaged_custom_pk = ModelState( "testapp", "Author", [ ("pk_field", models.IntegerField(primary_key=True)), ], ) author_with_m2m = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher")), ], ) author_with_m2m_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", blank=True)), ], ) other_publisher = ModelState( "testapp", "OtherPublisher", [ ("id", models.AutoField(primary_key=True)), ], ) author_with_m2m_through = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Contract"), ), ], ) author_with_renamed_m2m_through = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Deal"), ), ], ) author_with_former_m2m = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.CharField(max_length=100)), ], ) author_with_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], { "permissions": [("can_hire", "Can hire")], "verbose_name": "Authi", }, ) author_with_db_table_comment = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table_comment": "Table comment"}, ) author_with_db_table_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}, ) author_with_new_db_table_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_two"}, ) author_renamed_with_db_table_options = ModelState( "testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}, ) author_renamed_with_new_db_table_options = ModelState( "testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_three"}, ) contract = ModelState( "testapp", "Contract", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) contract_renamed = ModelState( "testapp", "Deal", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) publisher = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], ) publisher_with_author = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) publisher_with_aardvark_author = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Aardvark", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) publisher_with_book = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Book", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) other_pony = ModelState( "otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ], ) other_pony_food = ModelState( "otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ], managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) other_stable = ModelState( "otherapp", "Stable", [("id", models.AutoField(primary_key=True))] ) third_thing = ModelState( "thirdapp", "Thing", [("id", models.AutoField(primary_key=True))] ) book = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_proxy_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("thirdapp.AuthorProxy", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_proxy_proxy_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.AAuthorProxyProxy", models.CASCADE)), ], ) book_migrations_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("migrations.UnmigratedModel", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_no_author_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.IntegerField()), ("title", models.CharField(max_length=200)), ], ) book_with_no_author = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ], ) book_with_author_renamed = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_field_and_author_renamed = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("writer", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_multiple_authors = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author")), ("title", models.CharField(max_length=200)), ], ) book_with_multiple_authors_through_attribution = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ( "authors", models.ManyToManyField( "testapp.Author", through="otherapp.Attribution" ), ), ("title", models.CharField(max_length=200)), ], ) book_indexes = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index(fields=["author", "title"], name="book_title_author_idx") ], }, ) book_unordered_indexes = ModelState( "otherapp",
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_questioner.py
tests/migrations/test_questioner.py
import datetime from io import StringIO from unittest import mock from django.core.management.base import OutputWrapper from django.db.migrations.questioner import ( InteractiveMigrationQuestioner, MigrationQuestioner, ) from django.db.models import NOT_PROVIDED from django.test import SimpleTestCase from django.test.utils import override_settings class QuestionerTests(SimpleTestCase): @override_settings( INSTALLED_APPS=["migrations"], MIGRATION_MODULES={"migrations": None}, ) def test_ask_initial_with_disabled_migrations(self): questioner = MigrationQuestioner() self.assertIs(False, questioner.ask_initial("migrations")) def test_ask_not_null_alteration(self): questioner = MigrationQuestioner() self.assertIsNone( questioner.ask_not_null_alteration("field_name", "model_name") ) @mock.patch("builtins.input", return_value="2") def test_ask_not_null_alteration_not_provided(self, mock): questioner = InteractiveMigrationQuestioner( prompt_output=OutputWrapper(StringIO()) ) question = questioner.ask_not_null_alteration("field_name", "model_name") self.assertEqual(question, NOT_PROVIDED) class QuestionerHelperMethodsTests(SimpleTestCase): def setUp(self): self.prompt = OutputWrapper(StringIO()) self.questioner = InteractiveMigrationQuestioner(prompt_output=self.prompt) @mock.patch("builtins.input", return_value="datetime.timedelta(days=1)") def test_questioner_default_timedelta(self, mock_input): value = self.questioner._ask_default() self.assertEqual(value, datetime.timedelta(days=1)) @mock.patch("builtins.input", return_value="") def test_questioner_default_no_user_entry(self, mock_input): value = self.questioner._ask_default(default="datetime.timedelta(days=1)") self.assertEqual(value, datetime.timedelta(days=1)) @mock.patch("builtins.input", side_effect=["", "exit"]) def test_questioner_no_default_no_user_entry(self, mock_input): with self.assertRaises(SystemExit): self.questioner._ask_default() self.assertIn( "Please enter some code, or 'exit' (without quotes) to exit.", self.prompt.getvalue(), ) @mock.patch("builtins.input", side_effect=["bad code", "exit"]) def test_questioner_no_default_syntax_error(self, mock_input): with self.assertRaises(SystemExit): self.questioner._ask_default() self.assertIn("SyntaxError: invalid syntax", self.prompt.getvalue()) @mock.patch("builtins.input", side_effect=["datetim", "exit"]) def test_questioner_no_default_name_error(self, mock_input): with self.assertRaises(SystemExit): self.questioner._ask_default() self.assertIn( "NameError: name 'datetim' is not defined", self.prompt.getvalue() ) @mock.patch("builtins.input", side_effect=["datetime.dat", "exit"]) def test_questioner_no_default_attribute_error(self, mock_input): with self.assertRaises(SystemExit): self.questioner._ask_default() self.assertIn( "AttributeError: module 'datetime' has no attribute 'dat'", self.prompt.getvalue(), ) @mock.patch("builtins.input", side_effect=[KeyboardInterrupt()]) def test_questioner_no_default_keyboard_interrupt(self, mock_input): with self.assertRaises(SystemExit): self.questioner._ask_default() self.assertIn("Cancelled.\n", self.prompt.getvalue()) @mock.patch("builtins.input", side_effect=["", "n"]) def test_questioner_no_default_no_user_entry_boolean(self, mock_input): value = self.questioner._boolean_input("Proceed?") self.assertIs(value, False) @mock.patch("builtins.input", return_value="") def test_questioner_default_no_user_entry_boolean(self, mock_input): value = self.questioner._boolean_input("Proceed?", default=True) self.assertIs(value, True) @mock.patch("builtins.input", side_effect=[10, "garbage", 1]) def test_questioner_bad_user_choice(self, mock_input): question = "Make a choice:" value = self.questioner._choice_input(question, choices="abc") expected_msg = f"{question}\n" f" 1) a\n" f" 2) b\n" f" 3) c\n" self.assertIn(expected_msg, self.prompt.getvalue()) self.assertEqual(value, 1) @mock.patch("builtins.input", side_effect=[KeyboardInterrupt()]) def test_questioner_no_choice_keyboard_interrupt(self, mock_input): question = "Make a choice:" with self.assertRaises(SystemExit): self.questioner._choice_input(question, choices="abc") expected_msg = ( f"{question}\n" f" 1) a\n" f" 2) b\n" f" 3) c\n" f"Select an option: \n" f"Cancelled.\n" ) self.assertIn(expected_msg, self.prompt.getvalue())
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_optimizer.py
tests/migrations/test_optimizer.py
from django.db import migrations, models from django.db.migrations import operations from django.db.migrations.optimizer import MigrationOptimizer from django.db.models.functions import Abs from .models import EmptyManager, UnicodeModel from .test_base import OptimizerTestBase class OptimizerTests(OptimizerTestBase): """ Tests the migration optimizer. """ def test_none_app_label(self): optimizer = MigrationOptimizer() with self.assertRaisesMessage(TypeError, "app_label must be a str"): optimizer.optimize([], None) def test_single(self): """ The optimizer does nothing on a single operation, and that it does it in just one pass. """ self.assertOptimizesTo( [migrations.DeleteModel("Foo")], [migrations.DeleteModel("Foo")], exact=1, ) def test_create_delete_model(self): """ CreateModel and DeleteModel should collapse into nothing. """ self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.DeleteModel("Foo"), ], [], ) def test_create_rename_model(self): """ CreateModel should absorb RenameModels. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.RenameModel("Foo", "Bar"), ], [ migrations.CreateModel( "Bar", [("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ) ], ) def test_rename_model_self(self): """ RenameModels should absorb themselves. """ self.assertOptimizesTo( [ migrations.RenameModel("Foo", "Baa"), migrations.RenameModel("Baa", "Bar"), ], [ migrations.RenameModel("Foo", "Bar"), ], ) def test_create_alter_model_options(self): self.assertOptimizesTo( [ migrations.CreateModel("Foo", fields=[]), migrations.AlterModelOptions( name="Foo", options={"verbose_name_plural": "Foozes"} ), ], [ migrations.CreateModel( "Foo", fields=[], options={"verbose_name_plural": "Foozes"} ), ], ) def test_create_alter_model_managers(self): self.assertOptimizesTo( [ migrations.CreateModel("Foo", fields=[]), migrations.AlterModelManagers( name="Foo", managers=[ ("objects", models.Manager()), ("things", models.Manager()), ], ), ], [ migrations.CreateModel( "Foo", fields=[], managers=[ ("objects", models.Manager()), ("things", models.Manager()), ], ), ], ) def test_create_alter_model_table(self): self.assertOptimizesTo( [ migrations.CreateModel("Foo", fields=[]), migrations.AlterModelTable( name="foo", table="foo", ), ], [ migrations.CreateModel( "Foo", fields=[], options={ "db_table": "foo", }, ), ], ) def test_create_alter_model_table_comment(self): self.assertOptimizesTo( [ migrations.CreateModel("Foo", fields=[]), migrations.AlterModelTableComment( name="foo", table_comment="A lovely table.", ), ], [ migrations.CreateModel( "Foo", fields=[], options={ "db_table_comment": "A lovely table.", }, ), ], ) def test_create_model_and_remove_model_options(self): self.assertOptimizesTo( [ migrations.CreateModel( "MyModel", fields=[], options={"verbose_name": "My Model"}, ), migrations.AlterModelOptions("MyModel", options={}), ], [migrations.CreateModel("MyModel", fields=[])], ) self.assertOptimizesTo( [ migrations.CreateModel( "MyModel", fields=[], options={ "verbose_name": "My Model", "verbose_name_plural": "My Model plural", }, ), migrations.AlterModelOptions( "MyModel", options={"verbose_name": "My Model"}, ), ], [ migrations.CreateModel( "MyModel", fields=[], options={"verbose_name": "My Model"}, ), ], ) def _test_create_alter_foo_delete_model(self, alter_foo): """ CreateModel, AlterModelTable, AlterUniqueTogether/AlterIndexTogether/ AlterOrderWithRespectTo, and DeleteModel should collapse into nothing. """ self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.AlterModelTable("Foo", "woohoo"), alter_foo, migrations.DeleteModel("Foo"), ], [], ) def test_create_alter_unique_delete_model(self): self._test_create_alter_foo_delete_model( migrations.AlterUniqueTogether("Foo", [["a", "b"]]) ) def test_create_alter_index_delete_model(self): self._test_create_alter_foo_delete_model( migrations.AlterIndexTogether("Foo", [["a", "b"]]) ) def test_create_alter_owrt_delete_model(self): self._test_create_alter_foo_delete_model( migrations.AlterOrderWithRespectTo("Foo", "a") ) def _test_alter_alter(self, alter_foo, alter_bar): """ Two AlterUniqueTogether/AlterIndexTogether/AlterOrderWithRespectTo /AlterField should collapse into the second. """ self.assertOptimizesTo( [ alter_foo, alter_bar, ], [ alter_bar, ], ) def test_alter_alter_table_model(self): self._test_alter_alter( migrations.AlterModelTable("Foo", "a"), migrations.AlterModelTable("Foo", "b"), ) def test_alter_alter_unique_model(self): self._test_alter_alter( migrations.AlterUniqueTogether("Foo", [["a", "b"]]), migrations.AlterUniqueTogether("Foo", [["a", "c"]]), ) def test_alter_alter_index_model(self): self._test_alter_alter( migrations.AlterIndexTogether("Foo", [["a", "b"]]), migrations.AlterIndexTogether("Foo", [["a", "c"]]), ) def test_alter_alter_owrt_model(self): self._test_alter_alter( migrations.AlterOrderWithRespectTo("Foo", "a"), migrations.AlterOrderWithRespectTo("Foo", "b"), ) def test_alter_alter_field(self): self._test_alter_alter( migrations.AlterField("Foo", "name", models.IntegerField()), migrations.AlterField("Foo", "name", models.IntegerField(help_text="help")), ) def test_optimize_through_create(self): """ We should be able to optimize away create/delete through a create or delete of a different model, but only if the create operation does not mention the model at all. """ # These should work self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Bar", [("size", models.IntegerField())]), migrations.DeleteModel("Foo"), ], [ migrations.CreateModel("Bar", [("size", models.IntegerField())]), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Bar", [("size", models.IntegerField())]), migrations.DeleteModel("Bar"), migrations.DeleteModel("Foo"), ], [], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Bar", [("size", models.IntegerField())]), migrations.DeleteModel("Foo"), migrations.DeleteModel("Bar"), ], [], ) # Operations should be optimized if the FK references a model from the # other app. self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("other", models.ForeignKey("testapp.Foo", models.CASCADE))] ), migrations.DeleteModel("Foo"), ], [ migrations.CreateModel( "Bar", [("other", models.ForeignKey("testapp.Foo", models.CASCADE))] ), ], app_label="otherapp", ) # But it shouldn't work if a FK references a model with the same # app_label. self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("other", models.ForeignKey("Foo", models.CASCADE))] ), migrations.DeleteModel("Foo"), ], ) self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("other", models.ForeignKey("testapp.Foo", models.CASCADE))] ), migrations.DeleteModel("Foo"), ], app_label="testapp", ) # This should not work - bases should block it self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("Foo",) ), migrations.DeleteModel("Foo"), ], ) self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), migrations.DeleteModel("Foo"), ], app_label="testapp", ) # The same operations should be optimized if app_label and none of # bases belong to that app. self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), migrations.DeleteModel("Foo"), ], [ migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), ], app_label="otherapp", ) # But it shouldn't work if some of bases belongs to the specified app. self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [("size", models.IntegerField())], bases=("testapp.Foo",) ), migrations.DeleteModel("Foo"), ], app_label="testapp", ) self.assertOptimizesTo( [ migrations.CreateModel( "Book", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Person", [("name", models.CharField(max_length=255))] ), migrations.AddField( "book", "author", models.ForeignKey("test_app.Person", models.CASCADE), ), migrations.CreateModel( "Review", [("book", models.ForeignKey("test_app.Book", models.CASCADE))], ), migrations.CreateModel( "Reviewer", [("name", models.CharField(max_length=255))] ), migrations.AddField( "review", "reviewer", models.ForeignKey("test_app.Reviewer", models.CASCADE), ), migrations.RemoveField("book", "author"), migrations.DeleteModel("Person"), ], [ migrations.CreateModel( "Book", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Reviewer", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Review", [ ("book", models.ForeignKey("test_app.Book", models.CASCADE)), ( "reviewer", models.ForeignKey("test_app.Reviewer", models.CASCADE), ), ], ), ], app_label="test_app", ) def test_create_model_add_field(self): """ AddField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.AddField("Foo", "age", models.IntegerField()), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ("age", models.IntegerField()), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_create_model_reordering(self): """ AddField optimizes into CreateModel if it's a FK to a model that's between them (and there's no FK in the other direction), by changing the order of the CreateModel operations. """ self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Link", [("url", models.TextField())]), migrations.AddField( "Foo", "link", models.ForeignKey("migrations.Link", models.CASCADE) ), ], [ migrations.CreateModel("Link", [("url", models.TextField())]), migrations.CreateModel( "Foo", [ ("name", models.CharField(max_length=255)), ("link", models.ForeignKey("migrations.Link", models.CASCADE)), ], ), ], ) def test_create_model_reordering_circular_fk(self): """ CreateModel reordering behavior doesn't result in an infinite loop if there are FKs in both directions. """ self.assertOptimizesTo( [ migrations.CreateModel("Bar", [("url", models.TextField())]), migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.AddField( "Bar", "foo_fk", models.ForeignKey("migrations.Foo", models.CASCADE) ), migrations.AddField( "Foo", "bar_fk", models.ForeignKey("migrations.Bar", models.CASCADE) ), ], [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel( "Bar", [ ("url", models.TextField()), ("foo_fk", models.ForeignKey("migrations.Foo", models.CASCADE)), ], ), migrations.AddField( "Foo", "bar_fk", models.ForeignKey("migrations.Bar", models.CASCADE) ), ], ) def test_create_model_no_reordering_for_unrelated_fk(self): """ CreateModel order remains unchanged if the later AddField operation isn't a FK between them. """ self.assertDoesNotOptimize( [ migrations.CreateModel( "Foo", [("name", models.CharField(max_length=255))] ), migrations.CreateModel("Link", [("url", models.TextField())]), migrations.AddField( "Other", "link", models.ForeignKey("migrations.Link", models.CASCADE), ), ], ) def test_create_model_no_reordering_of_inherited_model(self): """ A CreateModel that inherits from another isn't reordered to avoid moving it earlier than its parent CreateModel operation. """ self.assertOptimizesTo( [ migrations.CreateModel( "Other", [("foo", models.CharField(max_length=255))] ), migrations.CreateModel( "ParentModel", [("bar", models.CharField(max_length=255))] ), migrations.CreateModel( "ChildModel", [("baz", models.CharField(max_length=255))], bases=("migrations.parentmodel",), ), migrations.AddField( "Other", "fk", models.ForeignKey("migrations.ChildModel", models.CASCADE), ), ], [ migrations.CreateModel( "ParentModel", [("bar", models.CharField(max_length=255))] ), migrations.CreateModel( "ChildModel", [("baz", models.CharField(max_length=255))], bases=("migrations.parentmodel",), ), migrations.CreateModel( "Other", [ ("foo", models.CharField(max_length=255)), ( "fk", models.ForeignKey("migrations.ChildModel", models.CASCADE), ), ], ), ], ) def test_create_model_add_field_not_through_m2m_through(self): """ AddField should NOT optimize into CreateModel if it's an M2M using a through that's created between them. """ self.assertDoesNotOptimize( [ migrations.CreateModel("Employee", []), migrations.CreateModel("Employer", []), migrations.CreateModel( "Employment", [ ( "employee", models.ForeignKey("migrations.Employee", models.CASCADE), ), ( "employment", models.ForeignKey("migrations.Employer", models.CASCADE), ), ], ), migrations.AddField( "Employer", "employees", models.ManyToManyField( "migrations.Employee", through="migrations.Employment", ), ), ], ) def test_create_model_alter_field(self): """ AlterField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.AlterField("Foo", "name", models.IntegerField()), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.IntegerField()), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_create_model_rename_field(self): """ RenameField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[("name", models.CharField(max_length=255))], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.RenameField("Foo", "name", "title"), ], [ migrations.CreateModel( name="Foo", fields=[ ("title", models.CharField(max_length=255)), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_add_field_rename_field(self): """ RenameField should optimize into AddField """ self.assertOptimizesTo( [ migrations.AddField("Foo", "name", models.CharField(max_length=255)), migrations.RenameField("Foo", "name", "title"), ], [ migrations.AddField("Foo", "title", models.CharField(max_length=255)), ], ) def test_alter_field_rename_field(self): """ RenameField should optimize to the other side of AlterField, and into itself. """ self.assertOptimizesTo( [ migrations.AlterField("Foo", "name", models.CharField(max_length=255)), migrations.RenameField("Foo", "name", "title"), migrations.RenameField("Foo", "title", "nom"), ], [ migrations.RenameField("Foo", "name", "nom"), migrations.AlterField("Foo", "nom", models.CharField(max_length=255)), ], ) def test_swapping_fields_names(self): self.assertDoesNotOptimize( [ migrations.CreateModel( "MyModel", [ ("field_a", models.IntegerField()), ("field_b", models.IntegerField()), ], ), migrations.RunPython(migrations.RunPython.noop), migrations.RenameField("MyModel", "field_a", "field_c"), migrations.RenameField("MyModel", "field_b", "field_a"), migrations.RenameField("MyModel", "field_c", "field_b"), ], ) def test_create_model_remove_field(self): """ RemoveField should optimize into CreateModel. """ managers = [("objects", EmptyManager())] self.assertOptimizesTo( [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ("age", models.IntegerField()), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), migrations.RemoveField("Foo", "age"), ], [ migrations.CreateModel( name="Foo", fields=[ ("name", models.CharField(max_length=255)), ], options={"verbose_name": "Foo"}, bases=(UnicodeModel,), managers=managers, ), ], ) def test_add_field_alter_field(self): """ AlterField should optimize into AddField. """ self.assertOptimizesTo( [ migrations.AddField("Foo", "age", models.IntegerField()), migrations.AlterField("Foo", "age", models.FloatField(default=2.4)), ], [ migrations.AddField( "Foo", name="age", field=models.FloatField(default=2.4) ), ], ) def test_add_field_delete_field(self): """ RemoveField should cancel AddField """ self.assertOptimizesTo( [ migrations.AddField("Foo", "age", models.IntegerField()), migrations.RemoveField("Foo", "age"), ], [], ) def test_alter_field_delete_field(self): """ RemoveField should absorb AlterField """ self.assertOptimizesTo( [ migrations.AlterField("Foo", "age", models.IntegerField()), migrations.RemoveField("Foo", "age"), ], [ migrations.RemoveField("Foo", "age"), ], ) def _test_create_alter_foo_field(self, alter): """ CreateModel, AlterFooTogether/AlterOrderWithRespectTo followed by an add/alter/rename field should optimize to CreateModel with options. """ option_value = getattr(alter, alter.option_name) options = {alter.option_name: option_value} # AddField self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.AddField("Foo", "c", models.IntegerField()), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.IntegerField()), ], options=options, ), ], ) # AlterField self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.AlterField("Foo", "b", models.CharField(max_length=255)), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.CharField(max_length=255)), ], options=options, ), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.IntegerField()), ], ), alter, migrations.AlterField("Foo", "c", models.CharField(max_length=255)), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ("c", models.CharField(max_length=255)), ], options=options, ), ], ) # RenameField if isinstance(option_value, str): renamed_options = {alter.option_name: "c"} else: renamed_options = { alter.option_name: { tuple("c" if value == "b" else value for value in item) for item in option_value } } self.assertOptimizesTo( [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("b", models.IntegerField()), ], ), alter, migrations.RenameField("Foo", "b", "c"), ], [ migrations.CreateModel( "Foo", [ ("a", models.IntegerField()), ("c", models.IntegerField()), ], options=renamed_options, ), ], ) self.assertOptimizesTo( [ migrations.CreateModel( "Foo",
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_executor.py
tests/migrations/test_executor.py
from unittest import mock from django.apps.registry import apps as global_apps from django.db import DatabaseError, connection, migrations, models from django.db.migrations.exceptions import InvalidMigrationPlan from django.db.migrations.executor import MigrationExecutor from django.db.migrations.graph import MigrationGraph from django.db.migrations.recorder import MigrationRecorder from django.db.migrations.state import ProjectState from django.test import ( SimpleTestCase, modify_settings, override_settings, skipUnlessDBFeature, ) from django.test.utils import isolate_lru_cache from .test_base import MigrationTestBase @modify_settings(INSTALLED_APPS={"append": "migrations2"}) class ExecutorTests(MigrationTestBase): """ Tests the migration executor (full end-to-end running). Bear in mind that if these are failing you should fix the other test failures first, as they may be propagating into here. """ available_apps = [ "migrations", "migrations2", "django.contrib.auth", "django.contrib.contenttypes", ] @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_run(self): """ Tests running a simple set of migrations. """ executor = MigrationExecutor(connection) # Let's look at the plan first and make sure it's up to scratch plan = executor.migration_plan([("migrations", "0002_second")]) self.assertEqual( plan, [ (executor.loader.graph.nodes["migrations", "0001_initial"], False), (executor.loader.graph.nodes["migrations", "0002_second"], False), ], ) # Were the tables there before? self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_book") # Alright, let's try running it executor.migrate([("migrations", "0002_second")]) # Are the tables there now? self.assertTableExists("migrations_author") self.assertTableExists("migrations_book") # Rebuild the graph to reflect the new DB state executor.loader.build_graph() # Alright, let's undo what we did plan = executor.migration_plan([("migrations", None)]) self.assertEqual( plan, [ (executor.loader.graph.nodes["migrations", "0002_second"], True), (executor.loader.graph.nodes["migrations", "0001_initial"], True), ], ) executor.migrate([("migrations", None)]) # Are the tables gone? self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_book") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_run_with_squashed(self): """ Tests running a squashed migration from zero (should ignore what it replaces) """ executor = MigrationExecutor(connection) # Check our leaf node is the squashed one leaves = [ key for key in executor.loader.graph.leaf_nodes() if key[0] == "migrations" ] self.assertEqual(leaves, [("migrations", "0001_squashed_0002")]) # Check the plan plan = executor.migration_plan([("migrations", "0001_squashed_0002")]) self.assertEqual( plan, [ ( executor.loader.graph.nodes["migrations", "0001_squashed_0002"], False, ), ], ) # Were the tables there before? self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_book") # Alright, let's try running it executor.migrate([("migrations", "0001_squashed_0002")]) # Are the tables there now? self.assertTableExists("migrations_author") self.assertTableExists("migrations_book") # Rebuild the graph to reflect the new DB state executor.loader.build_graph() # Alright, let's undo what we did. Should also just use squashed. plan = executor.migration_plan([("migrations", None)]) self.assertEqual( plan, [ (executor.loader.graph.nodes["migrations", "0001_squashed_0002"], True), ], ) executor.migrate([("migrations", None)]) # Are the tables gone? self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_book") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"}, ) def test_migrate_backward_to_squashed_migration(self): executor = MigrationExecutor(connection) try: self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_book") executor.migrate([("migrations", "0001_squashed_0002")]) self.assertTableExists("migrations_author") self.assertTableExists("migrations_book") executor.loader.build_graph() # Migrate backward to a squashed migration. executor.migrate([("migrations", "0001_initial")]) self.assertTableExists("migrations_author") self.assertTableNotExists("migrations_book") finally: # Unmigrate everything. executor = MigrationExecutor(connection) executor.migrate([("migrations", None)]) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_book") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_non_atomic"} ) def test_non_atomic_migration(self): """ Applying a non-atomic migration works as expected. """ executor = MigrationExecutor(connection) with self.assertRaisesMessage(RuntimeError, "Abort migration"): executor.migrate([("migrations", "0001_initial")]) self.assertTableExists("migrations_publisher") migrations_apps = executor.loader.project_state( ("migrations", "0001_initial") ).apps Publisher = migrations_apps.get_model("migrations", "Publisher") self.assertTrue(Publisher.objects.exists()) self.assertTableNotExists("migrations_book") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_atomic_operation"} ) def test_atomic_operation_in_non_atomic_migration(self): """ An atomic operation is properly rolled back inside a non-atomic migration. """ executor = MigrationExecutor(connection) with self.assertRaisesMessage(RuntimeError, "Abort migration"): executor.migrate([("migrations", "0001_initial")]) migrations_apps = executor.loader.project_state( ("migrations", "0001_initial") ).apps Editor = migrations_apps.get_model("migrations", "Editor") self.assertFalse(Editor.objects.exists()) # Record previous migration as successful. executor.migrate([("migrations", "0001_initial")], fake=True) # Rebuild the graph to reflect the new DB state. executor.loader.build_graph() # Migrating backwards is also atomic. with self.assertRaisesMessage(RuntimeError, "Abort migration"): executor.migrate([("migrations", None)]) self.assertFalse(Editor.objects.exists()) @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations", "migrations2": "migrations2.test_migrations_2", } ) def test_empty_plan(self): """ Re-planning a full migration of a fully-migrated set doesn't perform spurious unmigrations and remigrations. There was previously a bug where the executor just always performed the backwards plan for applied migrations - which even for the most recent migration in an app, might include other, dependent apps, and these were being unmigrated. """ # Make the initial plan, check it executor = MigrationExecutor(connection) plan = executor.migration_plan( [ ("migrations", "0002_second"), ("migrations2", "0001_initial"), ] ) self.assertEqual( plan, [ (executor.loader.graph.nodes["migrations", "0001_initial"], False), (executor.loader.graph.nodes["migrations", "0002_second"], False), (executor.loader.graph.nodes["migrations2", "0001_initial"], False), ], ) # Fake-apply all migrations executor.migrate( [("migrations", "0002_second"), ("migrations2", "0001_initial")], fake=True ) # Rebuild the graph to reflect the new DB state executor.loader.build_graph() # Now plan a second time and make sure it's empty plan = executor.migration_plan( [ ("migrations", "0002_second"), ("migrations2", "0001_initial"), ] ) self.assertEqual(plan, []) # The resulting state should include applied migrations. state = executor.migrate( [ ("migrations", "0002_second"), ("migrations2", "0001_initial"), ] ) self.assertIn(("migrations", "book"), state.models) self.assertIn(("migrations", "author"), state.models) self.assertIn(("migrations2", "otherauthor"), state.models) # Erase all the fake records executor.recorder.record_unapplied("migrations2", "0001_initial") executor.recorder.record_unapplied("migrations", "0002_second") executor.recorder.record_unapplied("migrations", "0001_initial") @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations", "migrations2": "migrations2.test_migrations_2_no_deps", } ) def test_mixed_plan_not_supported(self): """ Although the MigrationExecutor interfaces allows for mixed migration plans (combined forwards and backwards migrations) this is not supported. """ # Prepare for mixed plan executor = MigrationExecutor(connection) plan = executor.migration_plan([("migrations", "0002_second")]) self.assertEqual( plan, [ (executor.loader.graph.nodes["migrations", "0001_initial"], False), (executor.loader.graph.nodes["migrations", "0002_second"], False), ], ) executor.migrate(None, plan) # Rebuild the graph to reflect the new DB state executor.loader.build_graph() self.assertIn( ("migrations", "0001_initial"), executor.loader.applied_migrations ) self.assertIn(("migrations", "0002_second"), executor.loader.applied_migrations) self.assertNotIn( ("migrations2", "0001_initial"), executor.loader.applied_migrations ) # Generate mixed plan plan = executor.migration_plan( [ ("migrations", None), ("migrations2", "0001_initial"), ] ) msg = ( "Migration plans with both forwards and backwards migrations are " "not supported. Please split your migration process into separate " "plans of only forwards OR backwards migrations." ) with self.assertRaisesMessage(InvalidMigrationPlan, msg) as cm: executor.migrate(None, plan) self.assertEqual( cm.exception.args[1], [ (executor.loader.graph.nodes["migrations", "0002_second"], True), (executor.loader.graph.nodes["migrations", "0001_initial"], True), (executor.loader.graph.nodes["migrations2", "0001_initial"], False), ], ) # Rebuild the graph to reflect the new DB state executor.loader.build_graph() executor.migrate( [ ("migrations", None), ("migrations2", None), ] ) # Are the tables gone? self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_book") self.assertTableNotExists("migrations2_otherauthor") @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_soft_apply(self): """ Tests detection of initial migrations already having been applied. """ state = {"faked": None} def fake_storer(phase, migration=None, fake=None): state["faked"] = fake executor = MigrationExecutor(connection, progress_callback=fake_storer) # Were the tables there before? self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") # Run it normally self.assertEqual( executor.migration_plan([("migrations", "0001_initial")]), [ (executor.loader.graph.nodes["migrations", "0001_initial"], False), ], ) executor.migrate([("migrations", "0001_initial")]) # Are the tables there now? self.assertTableExists("migrations_author") self.assertTableExists("migrations_tribble") # We shouldn't have faked that one self.assertIs(state["faked"], False) # Rebuild the graph to reflect the new DB state executor.loader.build_graph() # Fake-reverse that executor.migrate([("migrations", None)], fake=True) # Are the tables still there? self.assertTableExists("migrations_author") self.assertTableExists("migrations_tribble") # Make sure that was faked self.assertIs(state["faked"], True) # Finally, migrate forwards; this should fake-apply our initial # migration executor.loader.build_graph() self.assertEqual( executor.migration_plan([("migrations", "0001_initial")]), [ (executor.loader.graph.nodes["migrations", "0001_initial"], False), ], ) # Applying the migration should raise a database level error # because we haven't given the --fake-initial option with self.assertRaises(DatabaseError): executor.migrate([("migrations", "0001_initial")]) # Reset the faked state state = {"faked": None} # Allow faking of initial CreateModel operations executor.migrate([("migrations", "0001_initial")], fake_initial=True) self.assertIs(state["faked"], True) # And migrate back to clean up the database executor.loader.build_graph() executor.migrate([("migrations", None)]) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations_custom_user", "django.contrib.auth": "django.contrib.auth.migrations", }, AUTH_USER_MODEL="migrations.Author", ) def test_custom_user(self): """ Regression test for #22325 - references to a custom user model defined in the same app are not resolved correctly. """ with isolate_lru_cache(global_apps.get_swappable_settings_name): executor = MigrationExecutor(connection) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") # Migrate forwards executor.migrate([("migrations", "0001_initial")]) self.assertTableExists("migrations_author") self.assertTableExists("migrations_tribble") # The soft-application detection works. # Change table_names to not return auth_user during this as it # wouldn't be there in a normal run, and ensure migrations.Author # exists in the global app registry temporarily. old_table_names = connection.introspection.table_names connection.introspection.table_names = lambda c: [ x for x in old_table_names(c) if x != "auth_user" ] migrations_apps = executor.loader.project_state( ("migrations", "0001_initial"), ).apps global_apps.get_app_config("migrations").models["author"] = ( migrations_apps.get_model("migrations", "author") ) try: migration = executor.loader.get_migration("auth", "0001_initial") self.assertIs(executor.detect_soft_applied(None, migration)[0], True) finally: connection.introspection.table_names = old_table_names del global_apps.get_app_config("migrations").models["author"] # Migrate back to clean up the database. executor.loader.build_graph() executor.migrate([("migrations", None)]) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_add_many_to_many_field_initial", }, ) def test_detect_soft_applied_add_field_manytomanyfield(self): """ executor.detect_soft_applied() detects ManyToManyField tables from an AddField operation. This checks the case of AddField in a migration with other operations (0001) and the case of AddField in its own migration (0002). """ tables = [ # from 0001 "migrations_project", "migrations_task", "migrations_project_tasks", # from 0002 "migrations_task_projects", ] executor = MigrationExecutor(connection) # Create the tables for 0001 but make it look like the migration hasn't # been applied. executor.migrate([("migrations", "0001_initial")]) executor.migrate([("migrations", None)], fake=True) for table in tables[:3]: self.assertTableExists(table) # Table detection sees 0001 is applied but not 0002. migration = executor.loader.get_migration("migrations", "0001_initial") self.assertIs(executor.detect_soft_applied(None, migration)[0], True) migration = executor.loader.get_migration("migrations", "0002_initial") self.assertIs(executor.detect_soft_applied(None, migration)[0], False) # Create the tables for both migrations but make it look like neither # has been applied. executor.loader.build_graph() executor.migrate([("migrations", "0001_initial")], fake=True) executor.migrate([("migrations", "0002_initial")]) executor.loader.build_graph() executor.migrate([("migrations", None)], fake=True) # Table detection sees 0002 is applied. migration = executor.loader.get_migration("migrations", "0002_initial") self.assertIs(executor.detect_soft_applied(None, migration)[0], True) # Leave the tables for 0001 except the many-to-many table. That missing # table should cause detect_soft_applied() to return False. with connection.schema_editor() as editor: for table in tables[2:]: editor.execute(editor.sql_delete_table % {"table": table}) migration = executor.loader.get_migration("migrations", "0001_initial") self.assertIs(executor.detect_soft_applied(None, migration)[0], False) # Cleanup by removing the remaining tables. with connection.schema_editor() as editor: for table in tables[:2]: editor.execute(editor.sql_delete_table % {"table": table}) for table in tables: self.assertTableNotExists(table) @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.lookuperror_a", "migrations.migrations_test_apps.lookuperror_b", "migrations.migrations_test_apps.lookuperror_c", ] ) def test_unrelated_model_lookups_forwards(self): """ #24123 - All models of apps already applied which are unrelated to the first app being applied are part of the initial model state. """ try: executor = MigrationExecutor(connection) self.assertTableNotExists("lookuperror_a_a1") self.assertTableNotExists("lookuperror_b_b1") self.assertTableNotExists("lookuperror_c_c1") executor.migrate([("lookuperror_b", "0003_b3")]) self.assertTableExists("lookuperror_b_b3") # Rebuild the graph to reflect the new DB state executor.loader.build_graph() # Migrate forwards -- This led to a lookup LookupErrors because # lookuperror_b.B2 is already applied executor.migrate( [ ("lookuperror_a", "0004_a4"), ("lookuperror_c", "0003_c3"), ] ) self.assertTableExists("lookuperror_a_a4") self.assertTableExists("lookuperror_c_c3") # Rebuild the graph to reflect the new DB state executor.loader.build_graph() finally: # Cleanup executor.migrate( [ ("lookuperror_a", None), ("lookuperror_b", None), ("lookuperror_c", None), ] ) self.assertTableNotExists("lookuperror_a_a1") self.assertTableNotExists("lookuperror_b_b1") self.assertTableNotExists("lookuperror_c_c1") @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.lookuperror_a", "migrations.migrations_test_apps.lookuperror_b", "migrations.migrations_test_apps.lookuperror_c", ] ) def test_unrelated_model_lookups_backwards(self): """ #24123 - All models of apps being unapplied which are unrelated to the first app being unapplied are part of the initial model state. """ try: executor = MigrationExecutor(connection) self.assertTableNotExists("lookuperror_a_a1") self.assertTableNotExists("lookuperror_b_b1") self.assertTableNotExists("lookuperror_c_c1") executor.migrate( [ ("lookuperror_a", "0004_a4"), ("lookuperror_b", "0003_b3"), ("lookuperror_c", "0003_c3"), ] ) self.assertTableExists("lookuperror_b_b3") self.assertTableExists("lookuperror_a_a4") self.assertTableExists("lookuperror_c_c3") # Rebuild the graph to reflect the new DB state executor.loader.build_graph() # Migrate backwards -- This led to a lookup LookupErrors because # lookuperror_b.B2 is not in the initial state (unrelated to app c) executor.migrate([("lookuperror_a", None)]) # Rebuild the graph to reflect the new DB state executor.loader.build_graph() finally: # Cleanup executor.migrate([("lookuperror_b", None), ("lookuperror_c", None)]) self.assertTableNotExists("lookuperror_a_a1") self.assertTableNotExists("lookuperror_b_b1") self.assertTableNotExists("lookuperror_c_c1") @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.mutate_state_a", "migrations.migrations_test_apps.mutate_state_b", ] ) def test_unrelated_applied_migrations_mutate_state(self): """ #26647 - Unrelated applied migrations should be part of the final state in both directions. """ executor = MigrationExecutor(connection) executor.migrate( [ ("mutate_state_b", "0002_add_field"), ] ) # Migrate forward. executor.loader.build_graph() state = executor.migrate( [ ("mutate_state_a", "0001_initial"), ] ) self.assertIn("added", state.models["mutate_state_b", "b"].fields) executor.loader.build_graph() # Migrate backward. state = executor.migrate( [ ("mutate_state_a", None), ] ) self.assertIn("added", state.models["mutate_state_b", "b"].fields) executor.migrate( [ ("mutate_state_b", None), ] ) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_process_callback(self): """ #24129 - Tests callback process """ call_args_list = [] def callback(*args): call_args_list.append(args) executor = MigrationExecutor(connection, progress_callback=callback) # Were the tables there before? self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") executor.migrate( [ ("migrations", "0001_initial"), ("migrations", "0002_second"), ] ) # Rebuild the graph to reflect the new DB state executor.loader.build_graph() executor.migrate( [ ("migrations", None), ("migrations", None), ] ) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") migrations = executor.loader.graph.nodes expected = [ ("render_start",), ("render_success",), ("apply_start", migrations["migrations", "0001_initial"], False), ("apply_success", migrations["migrations", "0001_initial"], False), ("apply_start", migrations["migrations", "0002_second"], False), ("apply_success", migrations["migrations", "0002_second"], False), ("render_start",), ("render_success",), ("unapply_start", migrations["migrations", "0002_second"], False), ("unapply_success", migrations["migrations", "0002_second"], False), ("unapply_start", migrations["migrations", "0001_initial"], False), ("unapply_success", migrations["migrations", "0001_initial"], False), ] self.assertEqual(call_args_list, expected) @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.alter_fk.author_app", "migrations.migrations_test_apps.alter_fk.book_app", ] ) def test_alter_id_type_with_fk(self): try: executor = MigrationExecutor(connection) self.assertTableNotExists("author_app_author") self.assertTableNotExists("book_app_book") # Apply initial migrations executor.migrate( [ ("author_app", "0001_initial"), ("book_app", "0001_initial"), ] ) self.assertTableExists("author_app_author") self.assertTableExists("book_app_book") # Rebuild the graph to reflect the new DB state executor.loader.build_graph() # Apply PK type alteration executor.migrate([("author_app", "0002_alter_id")]) # Rebuild the graph to reflect the new DB state executor.loader.build_graph() finally: # We can't simply unapply the migrations here because there is no # implicit cast from VARCHAR to INT on the database level. with connection.schema_editor() as editor: editor.execute(editor.sql_delete_table % {"table": "book_app_book"}) editor.execute(editor.sql_delete_table % {"table": "author_app_author"}) self.assertTableNotExists("author_app_author") self.assertTableNotExists("book_app_book") executor.migrate([("author_app", None)], fake=True) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_apply_all_replaced_marks_replacement_as_applied(self): """ Applying all replaced migrations marks replacement as applied (#24628). """ recorder = MigrationRecorder(connection) # Place the database in a state where the replaced migrations are # partially applied: 0001 is applied, 0002 is not. recorder.record_applied("migrations", "0001_initial") executor = MigrationExecutor(connection) # Use fake because we don't actually have the first migration # applied, so the second will fail. And there's no need to actually # create/modify tables here, we're just testing the # MigrationRecord, which works the same with or without fake. executor.migrate([("migrations", "0002_second")], fake=True) # Because we've now applied 0001 and 0002 both, their squashed # replacement should be marked as applied. self.assertIn( ("migrations", "0001_squashed_0002"), recorder.applied_migrations(), ) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_migrate_marks_replacement_applied_even_if_it_did_nothing(self): """ A new squash migration will be marked as applied even if all its replaced migrations were previously already applied (#24628). """ recorder = MigrationRecorder(connection) # Record all replaced migrations as applied recorder.record_applied("migrations", "0001_initial") recorder.record_applied("migrations", "0002_second") executor = MigrationExecutor(connection) executor.migrate([("migrations", "0001_squashed_0002")]) # Because 0001 and 0002 are both applied, even though this migrate run # didn't apply anything new, their squashed replacement should be # marked as applied. self.assertIn( ("migrations", "0001_squashed_0002"), recorder.applied_migrations(), ) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_migrate_marks_replacement_unapplied(self): executor = MigrationExecutor(connection) executor.migrate([("migrations", "0001_squashed_0002")]) try: self.assertIn( ("migrations", "0001_squashed_0002"), executor.recorder.applied_migrations(), ) finally: executor.loader.build_graph() executor.migrate([("migrations", None)]) self.assertNotIn( ("migrations", "0001_squashed_0002"), executor.recorder.applied_migrations(), ) # When the feature is False, the operation and the record won't be # performed in a transaction and the test will systematically pass. @skipUnlessDBFeature("can_rollback_ddl") def test_migrations_applied_and_recorded_atomically(self): """Migrations are applied and recorded atomically.""" class Migration(migrations.Migration): operations = [ migrations.CreateModel( "model", [ ("id", models.AutoField(primary_key=True)), ], ), ] executor = MigrationExecutor(connection) with mock.patch( "django.db.migrations.executor.MigrationExecutor.record_migration" ) as record_migration: record_migration.side_effect = RuntimeError("Recording migration failed.") with self.assertRaisesMessage(RuntimeError, "Recording migration failed."): executor.apply_migration( ProjectState(), Migration("0001_initial", "record_migration"),
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_multidb.py
tests/migrations/test_multidb.py
from django.db import connection, migrations, models from django.db.migrations.state import ProjectState from django.test import override_settings from .test_base import OperationTestBase class AgnosticRouter: """ A router that doesn't have an opinion regarding migrating. """ def allow_migrate(self, db, app_label, **hints): return None class MigrateNothingRouter: """ A router that doesn't allow migrating. """ def allow_migrate(self, db, app_label, **hints): return False class MigrateEverythingRouter: """ A router that always allows migrating. """ def allow_migrate(self, db, app_label, **hints): return True class MigrateWhenFooRouter: """ A router that allows migrating depending on a hint. """ def allow_migrate(self, db, app_label, **hints): return hints.get("foo", False) class MultiDBOperationTests(OperationTestBase): databases = {"default", "other"} def _test_create_model(self, app_label, should_run): """ CreateModel honors multi-db settings. """ operation = migrations.CreateModel( "Pony", [("id", models.AutoField(primary_key=True))], ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Test the database alteration self.assertTableNotExists("%s_pony" % app_label) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) if should_run: self.assertTableExists("%s_pony" % app_label) else: self.assertTableNotExists("%s_pony" % app_label) # And test reversal with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertTableNotExists("%s_pony" % app_label) @override_settings(DATABASE_ROUTERS=[AgnosticRouter()]) def test_create_model(self): """ Test when router doesn't have an opinion (i.e. CreateModel should run). """ self._test_create_model("test_mltdb_crmo", should_run=True) @override_settings(DATABASE_ROUTERS=[MigrateNothingRouter()]) def test_create_model2(self): """ Test when router returns False (i.e. CreateModel shouldn't run). """ self._test_create_model("test_mltdb_crmo2", should_run=False) @override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter()]) def test_create_model3(self): """ Test when router returns True (i.e. CreateModel should run). """ self._test_create_model("test_mltdb_crmo3", should_run=True) def test_create_model4(self): """ Test multiple routers. """ with override_settings(DATABASE_ROUTERS=[AgnosticRouter(), AgnosticRouter()]): self._test_create_model("test_mltdb_crmo4", should_run=True) with override_settings( DATABASE_ROUTERS=[MigrateNothingRouter(), MigrateEverythingRouter()] ): self._test_create_model("test_mltdb_crmo4", should_run=False) with override_settings( DATABASE_ROUTERS=[MigrateEverythingRouter(), MigrateNothingRouter()] ): self._test_create_model("test_mltdb_crmo4", should_run=True) def _test_run_sql(self, app_label, should_run, hints=None): with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter()]): project_state = self.set_up_test_model(app_label) sql = """ INSERT INTO {0}_pony (pink, weight) VALUES (1, 3.55); INSERT INTO {0}_pony (pink, weight) VALUES (3, 5.0); """.format( app_label ) operation = migrations.RunSQL(sql, hints=hints or {}) # Test the state alteration does nothing new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(new_state, project_state) # Test the database alteration self.assertEqual( project_state.apps.get_model(app_label, "Pony").objects.count(), 0 ) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) Pony = project_state.apps.get_model(app_label, "Pony") if should_run: self.assertEqual(Pony.objects.count(), 2) else: self.assertEqual(Pony.objects.count(), 0) @override_settings(DATABASE_ROUTERS=[MigrateNothingRouter()]) def test_run_sql_migrate_nothing_router(self): self._test_run_sql("test_mltdb_runsql", should_run=False) @override_settings(DATABASE_ROUTERS=[MigrateWhenFooRouter()]) def test_run_sql_migrate_foo_router_without_hints(self): self._test_run_sql("test_mltdb_runsql2", should_run=False) @override_settings(DATABASE_ROUTERS=[MigrateWhenFooRouter()]) def test_run_sql_migrate_foo_router_with_hints(self): self._test_run_sql("test_mltdb_runsql3", should_run=True, hints={"foo": True}) def _test_run_python(self, app_label, should_run, hints=None): with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter()]): project_state = self.set_up_test_model(app_label) # Create the operation def inner_method(models, schema_editor): Pony = models.get_model(app_label, "Pony") Pony.objects.create(pink=1, weight=3.55) Pony.objects.create(weight=5) operation = migrations.RunPython(inner_method, hints=hints or {}) # Test the state alteration does nothing new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(new_state, project_state) # Test the database alteration self.assertEqual( project_state.apps.get_model(app_label, "Pony").objects.count(), 0 ) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) Pony = project_state.apps.get_model(app_label, "Pony") if should_run: self.assertEqual(Pony.objects.count(), 2) else: self.assertEqual(Pony.objects.count(), 0) @override_settings(DATABASE_ROUTERS=[MigrateNothingRouter()]) def test_run_python_migrate_nothing_router(self): self._test_run_python("test_mltdb_runpython", should_run=False) @override_settings(DATABASE_ROUTERS=[MigrateWhenFooRouter()]) def test_run_python_migrate_foo_router_without_hints(self): self._test_run_python("test_mltdb_runpython2", should_run=False) @override_settings(DATABASE_ROUTERS=[MigrateWhenFooRouter()]) def test_run_python_migrate_foo_router_with_hints(self): self._test_run_python( "test_mltdb_runpython3", should_run=True, hints={"foo": True} )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_base.py
tests/migrations/test_base.py
import os import shutil import tempfile from contextlib import contextmanager from importlib import import_module from user_commands.utils import AssertFormatterFailureCaughtContext from django.apps import apps from django.core.management import call_command from django.db import connection, connections, migrations, models from django.db.migrations.migration import Migration from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.recorder import MigrationRecorder from django.db.migrations.serializer import serializer_factory from django.db.migrations.state import ProjectState from django.test import SimpleTestCase, TransactionTestCase from django.test.utils import extend_sys_path from django.utils.module_loading import module_dir class MigrationTestBase(TransactionTestCase): """ Contains an extended set of asserts for testing migrations and schema operations. """ available_apps = ["migrations"] databases = {"default", "other"} def tearDown(self): # Reset applied-migrations state. for db in self.databases: recorder = MigrationRecorder(connections[db]) recorder.migration_qs.filter(app="migrations").delete() def get_table_description(self, table, using="default"): with connections[using].cursor() as cursor: return connections[using].introspection.get_table_description(cursor, table) def assertTableExists(self, table, using="default"): with connections[using].cursor() as cursor: self.assertIn(table, connections[using].introspection.table_names(cursor)) def assertTableNotExists(self, table, using="default"): with connections[using].cursor() as cursor: self.assertNotIn( table, connections[using].introspection.table_names(cursor) ) def assertColumnExists(self, table, column, using="default"): self.assertIn( column, [c.name for c in self.get_table_description(table, using=using)] ) def assertColumnNotExists(self, table, column, using="default"): self.assertNotIn( column, [c.name for c in self.get_table_description(table, using=using)] ) def _get_column_allows_null(self, table, column, using): return [ c.null_ok for c in self.get_table_description(table, using=using) if c.name == column ][0] def assertColumnNull(self, table, column, using="default"): self.assertTrue(self._get_column_allows_null(table, column, using)) def assertColumnNotNull(self, table, column, using="default"): self.assertFalse(self._get_column_allows_null(table, column, using)) def _get_column_collation(self, table, column, using): return next( f.collation for f in self.get_table_description(table, using=using) if f.name == column ) def assertColumnCollation(self, table, column, collation, using="default"): self.assertEqual(self._get_column_collation(table, column, using), collation) def _get_table_comment(self, table, using): with connections[using].cursor() as cursor: return next( t.comment for t in connections[using].introspection.get_table_list(cursor) if t.name == table ) def assertTableComment(self, table, comment, using="default"): self.assertEqual(self._get_table_comment(table, using), comment) def assertTableCommentNotExists(self, table, using="default"): self.assertIn(self._get_table_comment(table, using), [None, ""]) def assertIndexExists( self, table, columns, value=True, using="default", index_type=None ): with connections[using].cursor() as cursor: self.assertEqual( value, any( c["index"] for c in connections[using] .introspection.get_constraints(cursor, table) .values() if ( c["columns"] == list(columns) and c["index"] is True and (index_type is None or c["type"] == index_type) and not c["unique"] ) ), ) def assertIndexNotExists(self, table, columns): return self.assertIndexExists(table, columns, False) def assertIndexNameExists(self, table, index, using="default"): with connections[using].cursor() as cursor: self.assertIn( index, connection.introspection.get_constraints(cursor, table), ) def assertIndexNameNotExists(self, table, index, using="default"): with connections[using].cursor() as cursor: self.assertNotIn( index, connection.introspection.get_constraints(cursor, table), ) def assertConstraintExists(self, table, name, value=True, using="default"): with connections[using].cursor() as cursor: constraints = ( connections[using].introspection.get_constraints(cursor, table).items() ) self.assertEqual( value, any(c["check"] for n, c in constraints if n == name), ) def assertConstraintNotExists(self, table, name): return self.assertConstraintExists(table, name, False) def assertUniqueConstraintExists(self, table, columns, value=True, using="default"): with connections[using].cursor() as cursor: constraints = ( connections[using].introspection.get_constraints(cursor, table).values() ) self.assertEqual( value, any(c["unique"] for c in constraints if c["columns"] == list(columns)), ) def assertFKExists(self, table, columns, to, value=True, using="default"): if not connections[using].features.can_introspect_foreign_keys: return with connections[using].cursor() as cursor: self.assertEqual( value, any( c["foreign_key"] == to for c in connections[using] .introspection.get_constraints(cursor, table) .values() if c["columns"] == list(columns) ), ) def assertFKNotExists(self, table, columns, to): return self.assertFKExists(table, columns, to, False) def assertFormatterFailureCaught( self, *args, module="migrations.test_migrations", **kwargs ): with ( self.temporary_migration_module(module=module), AssertFormatterFailureCaughtContext(self) as ctx, ): call_command(*args, stdout=ctx.stdout, stderr=ctx.stderr, **kwargs) @contextmanager def temporary_migration_module(self, app_label="migrations", module=None): """ Allows testing management commands in a temporary migrations module. Wrap all invocations to makemigrations and squashmigrations with this context manager in order to avoid creating migration files in your source tree inadvertently. Takes the application label that will be passed to makemigrations or squashmigrations and the Python path to a migrations module. The migrations module is used as a template for creating the temporary migrations module. If it isn't provided, the application's migrations module is used, if it exists. Returns the filesystem path to the temporary migrations module. """ with tempfile.TemporaryDirectory() as temp_dir: target_dir = tempfile.mkdtemp(dir=temp_dir) with open(os.path.join(target_dir, "__init__.py"), "w"): pass target_migrations_dir = os.path.join(target_dir, "migrations") if module is None: module = apps.get_app_config(app_label).name + ".migrations" try: source_migrations_dir = module_dir(import_module(module)) except (ImportError, ValueError): pass else: shutil.copytree(source_migrations_dir, target_migrations_dir) with extend_sys_path(temp_dir): new_module = os.path.basename(target_dir) + ".migrations" with self.settings(MIGRATION_MODULES={app_label: new_module}): yield target_migrations_dir class OperationTestBase(MigrationTestBase): """Common functions to help test operations.""" @classmethod def setUpClass(cls): super().setUpClass() cls._initial_table_names = frozenset(connection.introspection.table_names()) def tearDown(self): self.cleanup_test_tables() super().tearDown() def cleanup_test_tables(self): table_names = ( frozenset(connection.introspection.table_names()) - self._initial_table_names ) with connection.schema_editor() as editor: with connection.constraint_checks_disabled(): for table_name in table_names: editor.execute( editor.sql_delete_table % { "table": editor.quote_name(table_name), } ) def apply_operations(self, app_label, project_state, operations, atomic=True): migration = Migration("name", app_label) migration.operations = operations with connection.schema_editor(atomic=atomic) as editor: return migration.apply(project_state, editor) def unapply_operations(self, app_label, project_state, operations, atomic=True): migration = Migration("name", app_label) migration.operations = operations with connection.schema_editor(atomic=atomic) as editor: return migration.unapply(project_state, editor) def make_test_state(self, app_label, operation, **kwargs): """ Makes a test state using set_up_test_model and returns the original state and the state after the migration is applied. """ project_state = self.set_up_test_model(app_label, **kwargs) new_state = project_state.clone() operation.state_forwards(app_label, new_state) return project_state, new_state def set_up_test_model( self, app_label, second_model=False, third_model=False, index=False, multicol_index=False, related_model=False, mti_model=False, proxy_model=False, manager_model=False, unique_together=False, options=False, db_table=None, constraints=None, indexes=None, ): """Creates a test model state and database table.""" # Make the "current" state. model_options = { "swappable": "TEST_SWAP_MODEL", "unique_together": [["pink", "weight"]] if unique_together else [], } if options: model_options["permissions"] = [("can_groom", "Can groom")] if db_table: model_options["db_table"] = db_table operations = [ migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ("weight", models.FloatField()), ("green", models.IntegerField(null=True)), ( "yellow", models.CharField( blank=True, null=True, db_default="Yellow", max_length=20 ), ), ], options=model_options, ) ] if index: operations.append( migrations.AddIndex( "Pony", models.Index(fields=["pink"], name="pony_pink_idx"), ) ) if multicol_index: operations.append( migrations.AddIndex( "Pony", models.Index(fields=["pink", "weight"], name="pony_test_idx"), ) ) if indexes: for index in indexes: operations.append(migrations.AddIndex("Pony", index)) if constraints: for constraint in constraints: operations.append(migrations.AddConstraint("Pony", constraint)) if second_model: operations.append( migrations.CreateModel( "Stable", [ ("id", models.AutoField(primary_key=True)), ], ) ) if third_model: operations.append( migrations.CreateModel( "Van", [ ("id", models.AutoField(primary_key=True)), ], ) ) if related_model: operations.append( migrations.CreateModel( "Rider", [ ("id", models.AutoField(primary_key=True)), ("pony", models.ForeignKey("Pony", models.CASCADE)), ( "friend", models.ForeignKey("self", models.CASCADE, null=True), ), ], ) ) if mti_model: operations.append( migrations.CreateModel( "ShetlandPony", fields=[ ( "pony_ptr", models.OneToOneField( "Pony", models.CASCADE, auto_created=True, parent_link=True, primary_key=True, to_field="id", serialize=False, ), ), ("cuteness", models.IntegerField(default=1)), ], bases=["%s.Pony" % app_label], ) ) if proxy_model: operations.append( migrations.CreateModel( "ProxyPony", fields=[], options={"proxy": True}, bases=["%s.Pony" % app_label], ) ) if manager_model: from .models import FoodManager, FoodQuerySet operations.append( migrations.CreateModel( "Food", fields=[ ("id", models.AutoField(primary_key=True)), ], managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) ) return self.apply_operations(app_label, ProjectState(), operations) class OptimizerTestBase(SimpleTestCase): """Common functions to help test the optimizer.""" def optimize(self, operations, app_label): """ Handy shortcut for getting results + number of loops """ optimizer = MigrationOptimizer() return optimizer.optimize(operations, app_label), optimizer._iterations def serialize(self, value): return serializer_factory(value).serialize()[0] def assertOptimizesTo( self, operations, expected, exact=None, less_than=None, app_label=None ): result, iterations = self.optimize(operations, app_label or "migrations") result = [self.serialize(f) for f in result] expected = [self.serialize(f) for f in expected] self.assertEqual(expected, result) if exact is not None and iterations != exact: raise self.failureException( "Optimization did not take exactly %s iterations (it took %s)" % (exact, iterations) ) if less_than is not None and iterations >= less_than: raise self.failureException( "Optimization did not take less than %s iterations (it took %s)" % (less_than, iterations) ) def assertDoesNotOptimize(self, operations, **kwargs): self.assertOptimizesTo(operations, operations, **kwargs)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/models.py
tests/migrations/models.py
from django.apps.registry import Apps from django.db import models class CustomModelBase(models.base.ModelBase): pass class ModelWithCustomBase(models.Model, metaclass=CustomModelBase): pass class UnicodeModel(models.Model): title = models.CharField("ÚÑÍ¢ÓÐÉ", max_length=20, default="“Ðjáñgó”") class Meta: # Disable auto loading of this model as we load it on our own apps = Apps() verbose_name = "úñí©óðé µóðéø" verbose_name_plural = "úñí©óðé µóðéøß" def __str__(self): return self.title class Unserializable: """ An object that migration doesn't know how to serialize. """ pass class UnserializableModel(models.Model): title = models.CharField(max_length=20, default=Unserializable()) class Meta: # Disable auto loading of this model as we load it on our own apps = Apps() class UnmigratedModel(models.Model): """ A model that is in a migration-less app (which this app is if its migrations directory has not been repointed) """ pass class EmptyManager(models.Manager): use_in_migrations = True class FoodQuerySet(models.query.QuerySet): pass class BaseFoodManager(models.Manager): def __init__(self, a, b, c=1, d=2): super().__init__() self.args = (a, b, c, d) class FoodManager(BaseFoodManager.from_queryset(FoodQuerySet)): use_in_migrations = True class NoMigrationFoodManager(BaseFoodManager.from_queryset(FoodQuerySet)): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_state.py
tests/migrations/test_state.py
from django.apps.registry import Apps from django.contrib.contenttypes.fields import GenericForeignKey from django.db import models from django.db.migrations.exceptions import InvalidBasesError from django.db.migrations.operations import ( AddField, AlterField, DeleteModel, RemoveField, ) from django.db.migrations.state import ( ModelState, ProjectState, get_related_models_recursive, ) from django.test import SimpleTestCase, override_settings from django.test.utils import isolate_apps from .models import ( FoodManager, FoodQuerySet, ModelWithCustomBase, NoMigrationFoodManager, UnicodeModel, ) class StateTests(SimpleTestCase): """ Tests state construction, rendering and modification by operations. """ def test_create(self): """ Tests making a ProjectState from an Apps """ new_apps = Apps(["migrations"]) class Author(models.Model): name = models.CharField(max_length=255) bio = models.TextField() age = models.IntegerField(blank=True, null=True) class Meta: app_label = "migrations" apps = new_apps unique_together = ["name", "bio"] class AuthorProxy(Author): class Meta: app_label = "migrations" apps = new_apps proxy = True ordering = ["name"] class SubAuthor(Author): width = models.FloatField(null=True) class Meta: app_label = "migrations" apps = new_apps class Book(models.Model): title = models.CharField(max_length=1000) author = models.ForeignKey(Author, models.CASCADE) contributors = models.ManyToManyField(Author) class Meta: app_label = "migrations" apps = new_apps verbose_name = "tome" db_table = "test_tome" indexes = [models.Index(fields=["title"])] class Food(models.Model): food_mgr = FoodManager("a", "b") food_qs = FoodQuerySet.as_manager() food_no_mgr = NoMigrationFoodManager("x", "y") class Meta: app_label = "migrations" apps = new_apps class FoodNoManagers(models.Model): class Meta: app_label = "migrations" apps = new_apps class FoodNoDefaultManager(models.Model): food_no_mgr = NoMigrationFoodManager("x", "y") food_mgr = FoodManager("a", "b") food_qs = FoodQuerySet.as_manager() class Meta: app_label = "migrations" apps = new_apps mgr1 = FoodManager("a", "b") mgr2 = FoodManager("x", "y", c=3, d=4) class FoodOrderedManagers(models.Model): # The managers on this model should be ordered by their creation # counter and not by the order in model body food_no_mgr = NoMigrationFoodManager("x", "y") food_mgr2 = mgr2 food_mgr1 = mgr1 class Meta: app_label = "migrations" apps = new_apps project_state = ProjectState.from_apps(new_apps) author_state = project_state.models["migrations", "author"] author_proxy_state = project_state.models["migrations", "authorproxy"] sub_author_state = project_state.models["migrations", "subauthor"] book_state = project_state.models["migrations", "book"] food_state = project_state.models["migrations", "food"] food_no_managers_state = project_state.models["migrations", "foodnomanagers"] food_no_default_manager_state = project_state.models[ "migrations", "foodnodefaultmanager" ] food_order_manager_state = project_state.models[ "migrations", "foodorderedmanagers" ] book_index = models.Index(fields=["title"]) book_index.set_name_with_model(Book) self.assertEqual(author_state.app_label, "migrations") self.assertEqual(author_state.name, "Author") self.assertEqual(list(author_state.fields), ["id", "name", "bio", "age"]) self.assertEqual(author_state.fields["name"].max_length, 255) self.assertIs(author_state.fields["bio"].null, False) self.assertIs(author_state.fields["age"].null, True) self.assertEqual( author_state.options, { "unique_together": {("name", "bio")}, "indexes": [], "constraints": [], }, ) self.assertEqual(author_state.bases, (models.Model,)) self.assertEqual(book_state.app_label, "migrations") self.assertEqual(book_state.name, "Book") self.assertEqual( list(book_state.fields), ["id", "title", "author", "contributors"] ) self.assertEqual(book_state.fields["title"].max_length, 1000) self.assertIs(book_state.fields["author"].null, False) self.assertEqual( book_state.fields["contributors"].__class__.__name__, "ManyToManyField" ) self.assertEqual( book_state.options, { "verbose_name": "tome", "db_table": "test_tome", "indexes": [book_index], "constraints": [], }, ) self.assertEqual(book_state.bases, (models.Model,)) self.assertEqual(author_proxy_state.app_label, "migrations") self.assertEqual(author_proxy_state.name, "AuthorProxy") self.assertEqual(author_proxy_state.fields, {}) self.assertEqual( author_proxy_state.options, {"proxy": True, "ordering": ["name"], "indexes": [], "constraints": []}, ) self.assertEqual(author_proxy_state.bases, ("migrations.author",)) self.assertEqual(sub_author_state.app_label, "migrations") self.assertEqual(sub_author_state.name, "SubAuthor") self.assertEqual(len(sub_author_state.fields), 2) self.assertEqual(sub_author_state.bases, ("migrations.author",)) # The default manager is used in migrations self.assertEqual([name for name, mgr in food_state.managers], ["food_mgr"]) self.assertTrue(all(isinstance(name, str) for name, mgr in food_state.managers)) self.assertEqual(food_state.managers[0][1].args, ("a", "b", 1, 2)) # No explicit managers defined. Migrations will fall back to the # default self.assertEqual(food_no_managers_state.managers, []) # food_mgr is used in migration but isn't the default mgr, hence add # the default self.assertEqual( [name for name, mgr in food_no_default_manager_state.managers], ["food_no_mgr", "food_mgr"], ) self.assertTrue( all( isinstance(name, str) for name, mgr in food_no_default_manager_state.managers ) ) self.assertEqual( food_no_default_manager_state.managers[0][1].__class__, models.Manager ) self.assertIsInstance(food_no_default_manager_state.managers[1][1], FoodManager) self.assertEqual( [name for name, mgr in food_order_manager_state.managers], ["food_mgr1", "food_mgr2"], ) self.assertTrue( all( isinstance(name, str) for name, mgr in food_order_manager_state.managers ) ) self.assertEqual( [mgr.args for name, mgr in food_order_manager_state.managers], [("a", "b", 1, 2), ("x", "y", 3, 4)], ) def test_custom_default_manager_added_to_the_model_state(self): """ When the default manager of the model is a custom manager, it needs to be added to the model state. """ new_apps = Apps(["migrations"]) custom_manager = models.Manager() class Author(models.Model): objects = models.TextField() authors = custom_manager class Meta: app_label = "migrations" apps = new_apps project_state = ProjectState.from_apps(new_apps) author_state = project_state.models["migrations", "author"] self.assertEqual(author_state.managers, [("authors", custom_manager)]) def test_custom_default_manager_named_objects_with_false_migration_flag(self): """ When a manager is added with a name of 'objects' but it does not have `use_in_migrations = True`, no migration should be added to the model state (#26643). """ new_apps = Apps(["migrations"]) class Author(models.Model): objects = models.Manager() class Meta: app_label = "migrations" apps = new_apps project_state = ProjectState.from_apps(new_apps) author_state = project_state.models["migrations", "author"] self.assertEqual(author_state.managers, []) def test_no_duplicate_managers(self): """ When a manager is added with `use_in_migrations = True` and a parent model had a manager with the same name and `use_in_migrations = True`, the parent's manager shouldn't appear in the model state (#26881). """ new_apps = Apps(["migrations"]) class PersonManager(models.Manager): use_in_migrations = True class Person(models.Model): objects = PersonManager() class Meta: abstract = True class BossManager(PersonManager): use_in_migrations = True class Boss(Person): objects = BossManager() class Meta: app_label = "migrations" apps = new_apps project_state = ProjectState.from_apps(new_apps) boss_state = project_state.models["migrations", "boss"] self.assertEqual(boss_state.managers, [("objects", Boss.objects)]) def test_custom_default_manager(self): new_apps = Apps(["migrations"]) class Author(models.Model): manager1 = models.Manager() manager2 = models.Manager() class Meta: app_label = "migrations" apps = new_apps default_manager_name = "manager2" project_state = ProjectState.from_apps(new_apps) author_state = project_state.models["migrations", "author"] self.assertEqual(author_state.options["default_manager_name"], "manager2") self.assertEqual(author_state.managers, [("manager2", Author.manager1)]) def test_custom_base_manager(self): new_apps = Apps(["migrations"]) class Author(models.Model): manager1 = models.Manager() manager2 = models.Manager() class Meta: app_label = "migrations" apps = new_apps base_manager_name = "manager2" class Author2(models.Model): manager1 = models.Manager() manager2 = models.Manager() class Meta: app_label = "migrations" apps = new_apps base_manager_name = "manager1" project_state = ProjectState.from_apps(new_apps) author_state = project_state.models["migrations", "author"] self.assertEqual(author_state.options["base_manager_name"], "manager2") self.assertEqual( author_state.managers, [ ("manager1", Author.manager1), ("manager2", Author.manager2), ], ) author2_state = project_state.models["migrations", "author2"] self.assertEqual(author2_state.options["base_manager_name"], "manager1") self.assertEqual( author2_state.managers, [ ("manager1", Author2.manager1), ], ) def test_apps_bulk_update(self): """ StateApps.bulk_update() should update apps.ready to False and reset the value afterward. """ project_state = ProjectState() apps = project_state.apps with apps.bulk_update(): self.assertFalse(apps.ready) self.assertTrue(apps.ready) with self.assertRaises(ValueError): with apps.bulk_update(): self.assertFalse(apps.ready) raise ValueError() self.assertTrue(apps.ready) def test_render(self): """ Tests rendering a ProjectState into an Apps. """ project_state = ProjectState() project_state.add_model( ModelState( app_label="migrations", name="Tag", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ("hidden", models.BooleanField()), ], ) ) project_state.add_model( ModelState( app_label="migrations", name="SubTag", fields=[ ( "tag_ptr", models.OneToOneField( "migrations.Tag", models.CASCADE, auto_created=True, parent_link=True, primary_key=True, to_field="id", serialize=False, ), ), ("awesome", models.BooleanField()), ], bases=("migrations.Tag",), ) ) base_mgr = models.Manager() mgr1 = FoodManager("a", "b") mgr2 = FoodManager("x", "y", c=3, d=4) project_state.add_model( ModelState( app_label="migrations", name="Food", fields=[ ("id", models.AutoField(primary_key=True)), ], managers=[ # The ordering we really want is objects, mgr1, mgr2 ("default", base_mgr), ("food_mgr2", mgr2), ("food_mgr1", mgr1), ], ) ) new_apps = project_state.apps self.assertEqual( new_apps.get_model("migrations", "Tag")._meta.get_field("name").max_length, 100, ) self.assertIs( new_apps.get_model("migrations", "Tag")._meta.get_field("hidden").null, False, ) self.assertEqual( len(new_apps.get_model("migrations", "SubTag")._meta.local_fields), 2 ) Food = new_apps.get_model("migrations", "Food") self.assertEqual( [mgr.name for mgr in Food._meta.managers], ["default", "food_mgr1", "food_mgr2"], ) self.assertTrue(all(isinstance(mgr.name, str) for mgr in Food._meta.managers)) self.assertEqual( [mgr.__class__ for mgr in Food._meta.managers], [models.Manager, FoodManager, FoodManager], ) def test_render_model_inheritance(self): class Book(models.Model): title = models.CharField(max_length=1000) class Meta: app_label = "migrations" apps = Apps() class Novel(Book): class Meta: app_label = "migrations" apps = Apps() # First, test rendering individually apps = Apps(["migrations"]) # We shouldn't be able to render yet ms = ModelState.from_model(Novel) with self.assertRaises(InvalidBasesError): ms.render(apps) # Once the parent model is in the app registry, it should be fine ModelState.from_model(Book).render(apps) ModelState.from_model(Novel).render(apps) def test_render_model_with_multiple_inheritance(self): class Foo(models.Model): class Meta: app_label = "migrations" apps = Apps() class Bar(models.Model): class Meta: app_label = "migrations" apps = Apps() class FooBar(Foo, Bar): class Meta: app_label = "migrations" apps = Apps() class AbstractSubFooBar(FooBar): class Meta: abstract = True apps = Apps() class SubFooBar(AbstractSubFooBar): class Meta: app_label = "migrations" apps = Apps() apps = Apps(["migrations"]) # We shouldn't be able to render yet ms = ModelState.from_model(FooBar) with self.assertRaises(InvalidBasesError): ms.render(apps) # Once the parent models are in the app registry, it should be fine ModelState.from_model(Foo).render(apps) self.assertSequenceEqual(ModelState.from_model(Foo).bases, [models.Model]) ModelState.from_model(Bar).render(apps) self.assertSequenceEqual(ModelState.from_model(Bar).bases, [models.Model]) ModelState.from_model(FooBar).render(apps) self.assertSequenceEqual( ModelState.from_model(FooBar).bases, ["migrations.foo", "migrations.bar"] ) ModelState.from_model(SubFooBar).render(apps) self.assertSequenceEqual( ModelState.from_model(SubFooBar).bases, ["migrations.foobar"] ) def test_render_project_dependencies(self): """ The ProjectState render method correctly renders models to account for inter-model base dependencies. """ new_apps = Apps() class A(models.Model): class Meta: app_label = "migrations" apps = new_apps class B(A): class Meta: app_label = "migrations" apps = new_apps class C(B): class Meta: app_label = "migrations" apps = new_apps class D(A): class Meta: app_label = "migrations" apps = new_apps class E(B): class Meta: app_label = "migrations" apps = new_apps proxy = True class F(D): class Meta: app_label = "migrations" apps = new_apps proxy = True # Make a ProjectState and render it project_state = ProjectState() project_state.add_model(ModelState.from_model(A)) project_state.add_model(ModelState.from_model(B)) project_state.add_model(ModelState.from_model(C)) project_state.add_model(ModelState.from_model(D)) project_state.add_model(ModelState.from_model(E)) project_state.add_model(ModelState.from_model(F)) final_apps = project_state.apps self.assertEqual(len(final_apps.get_models()), 6) # Now make an invalid ProjectState and make sure it fails project_state = ProjectState() project_state.add_model(ModelState.from_model(A)) project_state.add_model(ModelState.from_model(B)) project_state.add_model(ModelState.from_model(C)) project_state.add_model(ModelState.from_model(F)) with self.assertRaises(InvalidBasesError): project_state.apps def test_render_unique_app_labels(self): """ The ProjectState render method doesn't raise an ImproperlyConfigured exception about unique labels if two dotted app names have the same last part. """ class A(models.Model): class Meta: app_label = "django.contrib.auth" class B(models.Model): class Meta: app_label = "vendor.auth" # Make a ProjectState and render it project_state = ProjectState() project_state.add_model(ModelState.from_model(A)) project_state.add_model(ModelState.from_model(B)) self.assertEqual(len(project_state.apps.get_models()), 2) def test_reload_related_model_on_non_relational_fields(self): """ The model is reloaded even on changes that are not involved in relations. Other models pointing to or from it are also reloaded. """ project_state = ProjectState() project_state.apps # Render project state. project_state.add_model(ModelState("migrations", "A", [])) project_state.add_model( ModelState( "migrations", "B", [ ("a", models.ForeignKey("A", models.CASCADE)), ], ) ) project_state.add_model( ModelState( "migrations", "C", [ ("b", models.ForeignKey("B", models.CASCADE)), ("name", models.TextField()), ], ) ) project_state.add_model( ModelState( "migrations", "D", [ ("a", models.ForeignKey("A", models.CASCADE)), ], ) ) operation = AlterField( model_name="C", name="name", field=models.TextField(blank=True), ) operation.state_forwards("migrations", project_state) project_state.reload_model("migrations", "a", delay=True) A = project_state.apps.get_model("migrations.A") B = project_state.apps.get_model("migrations.B") D = project_state.apps.get_model("migrations.D") self.assertIs(B._meta.get_field("a").related_model, A) self.assertIs(D._meta.get_field("a").related_model, A) def test_reload_model_relationship_consistency(self): project_state = ProjectState() project_state.add_model(ModelState("migrations", "A", [])) project_state.add_model( ModelState( "migrations", "B", [ ("a", models.ForeignKey("A", models.CASCADE)), ], ) ) project_state.add_model( ModelState( "migrations", "C", [ ("b", models.ForeignKey("B", models.CASCADE)), ], ) ) A = project_state.apps.get_model("migrations.A") B = project_state.apps.get_model("migrations.B") C = project_state.apps.get_model("migrations.C") self.assertEqual([r.related_model for r in A._meta.related_objects], [B]) self.assertEqual([r.related_model for r in B._meta.related_objects], [C]) self.assertEqual([r.related_model for r in C._meta.related_objects], []) project_state.reload_model("migrations", "a", delay=True) A = project_state.apps.get_model("migrations.A") B = project_state.apps.get_model("migrations.B") C = project_state.apps.get_model("migrations.C") self.assertEqual([r.related_model for r in A._meta.related_objects], [B]) self.assertEqual([r.related_model for r in B._meta.related_objects], [C]) self.assertEqual([r.related_model for r in C._meta.related_objects], []) def test_add_relations(self): """ #24573 - Adding relations to existing models should reload the referenced models too. """ new_apps = Apps() class A(models.Model): class Meta: app_label = "something" apps = new_apps class B(A): class Meta: app_label = "something" apps = new_apps class C(models.Model): class Meta: app_label = "something" apps = new_apps project_state = ProjectState() project_state.add_model(ModelState.from_model(A)) project_state.add_model(ModelState.from_model(B)) project_state.add_model(ModelState.from_model(C)) project_state.apps # We need to work with rendered models old_state = project_state.clone() model_a_old = old_state.apps.get_model("something", "A") model_b_old = old_state.apps.get_model("something", "B") model_c_old = old_state.apps.get_model("something", "C") # The relations between the old models are correct self.assertIs(model_a_old._meta.get_field("b").related_model, model_b_old) self.assertIs(model_b_old._meta.get_field("a_ptr").related_model, model_a_old) operation = AddField( "c", "to_a", models.OneToOneField( "something.A", models.CASCADE, related_name="from_c", ), ) operation.state_forwards("something", project_state) model_a_new = project_state.apps.get_model("something", "A") model_b_new = project_state.apps.get_model("something", "B") model_c_new = project_state.apps.get_model("something", "C") # All models have changed self.assertIsNot(model_a_old, model_a_new) self.assertIsNot(model_b_old, model_b_new) self.assertIsNot(model_c_old, model_c_new) # The relations between the old models still hold self.assertIs(model_a_old._meta.get_field("b").related_model, model_b_old) self.assertIs(model_b_old._meta.get_field("a_ptr").related_model, model_a_old) # The relations between the new models correct self.assertIs(model_a_new._meta.get_field("b").related_model, model_b_new) self.assertIs(model_b_new._meta.get_field("a_ptr").related_model, model_a_new) self.assertIs(model_a_new._meta.get_field("from_c").related_model, model_c_new) self.assertIs(model_c_new._meta.get_field("to_a").related_model, model_a_new) def test_remove_relations(self): """ #24225 - Relations between models are updated while remaining the relations and references for models of an old state. """ new_apps = Apps() class A(models.Model): class Meta: app_label = "something" apps = new_apps class B(models.Model): to_a = models.ForeignKey(A, models.CASCADE) class Meta: app_label = "something" apps = new_apps def get_model_a(state): return [ mod for mod in state.apps.get_models() if mod._meta.model_name == "a" ][0] project_state = ProjectState() project_state.add_model(ModelState.from_model(A)) project_state.add_model(ModelState.from_model(B)) self.assertEqual(len(get_model_a(project_state)._meta.related_objects), 1) old_state = project_state.clone() operation = RemoveField("b", "to_a") operation.state_forwards("something", project_state) # Model from old_state still has the relation model_a_old = get_model_a(old_state) model_a_new = get_model_a(project_state) self.assertIsNot(model_a_old, model_a_new) self.assertEqual(len(model_a_old._meta.related_objects), 1) self.assertEqual(len(model_a_new._meta.related_objects), 0) # Same test for deleted model project_state = ProjectState() project_state.add_model(ModelState.from_model(A)) project_state.add_model(ModelState.from_model(B)) old_state = project_state.clone() operation = DeleteModel("b") operation.state_forwards("something", project_state) model_a_old = get_model_a(old_state) model_a_new = get_model_a(project_state) self.assertIsNot(model_a_old, model_a_new) self.assertEqual(len(model_a_old._meta.related_objects), 1) self.assertEqual(len(model_a_new._meta.related_objects), 0) def test_self_relation(self): """ #24513 - Modifying an object pointing to itself would cause it to be rendered twice and thus breaking its related M2M through objects. """ class A(models.Model): to_a = models.ManyToManyField("something.A", symmetrical=False) class Meta: app_label = "something" def get_model_a(state): return [ mod for mod in state.apps.get_models() if mod._meta.model_name == "a" ][0] project_state = ProjectState() project_state.add_model(ModelState.from_model(A)) self.assertEqual(len(get_model_a(project_state)._meta.related_objects), 1) old_state = project_state.clone() operation = AlterField( model_name="a", name="to_a", field=models.ManyToManyField("something.A", symmetrical=False, blank=True), ) # At this point the model would be rendered twice causing its related # M2M through objects to point to an old copy and thus breaking their # attribute lookup. operation.state_forwards("something", project_state) model_a_old = get_model_a(old_state) model_a_new = get_model_a(project_state) self.assertIsNot(model_a_old, model_a_new) # The old model's _meta is still consistent field_to_a_old = model_a_old._meta.get_field("to_a") self.assertEqual(field_to_a_old.m2m_field_name(), "from_a") self.assertEqual(field_to_a_old.m2m_reverse_field_name(), "to_a") self.assertIs(field_to_a_old.related_model, model_a_old) self.assertIs( field_to_a_old.remote_field.through._meta.get_field("to_a").related_model, model_a_old, ) self.assertIs( field_to_a_old.remote_field.through._meta.get_field("from_a").related_model, model_a_old, ) # The new model's _meta is still consistent field_to_a_new = model_a_new._meta.get_field("to_a") self.assertEqual(field_to_a_new.m2m_field_name(), "from_a") self.assertEqual(field_to_a_new.m2m_reverse_field_name(), "to_a") self.assertIs(field_to_a_new.related_model, model_a_new) self.assertIs( field_to_a_new.remote_field.through._meta.get_field("to_a").related_model, model_a_new, ) self.assertIs( field_to_a_new.remote_field.through._meta.get_field("from_a").related_model, model_a_new, ) def test_equality(self): """ == and != are implemented correctly. """ # Test two things that should be equal project_state = ProjectState() project_state.add_model( ModelState( "migrations", "Tag", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ("hidden", models.BooleanField()), ], {}, None, ) ) project_state.apps # Fill the apps cached property other_state = project_state.clone() self.assertEqual(project_state, project_state) self.assertEqual(project_state, other_state) self.assertIs(project_state != project_state, False) self.assertIs(project_state != other_state, False) self.assertNotEqual(project_state.apps, other_state.apps) # Make a very small change (max_len 99) and see if that affects it project_state = ProjectState() project_state.add_model( ModelState( "migrations", "Tag", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=99)), ("hidden", models.BooleanField()), ], {}, None, ) ) self.assertNotEqual(project_state, other_state) self.assertIs(project_state == other_state, False) def test_dangling_references_throw_error(self): new_apps = Apps() class Author(models.Model): name = models.TextField()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_graph.py
tests/migrations/test_graph.py
from django.db.migrations.exceptions import CircularDependencyError, NodeNotFoundError from django.db.migrations.graph import DummyNode, MigrationGraph, Node from django.test import SimpleTestCase class GraphTests(SimpleTestCase): """ Tests the digraph structure. """ def test_simple_graph(self): """ Tests a basic dependency graph: app_a: 0001 <-- 0002 <--- 0003 <-- 0004 / app_b: 0001 <-- 0002 <-/ """ # Build graph graph = MigrationGraph() graph.add_node(("app_a", "0001"), None) graph.add_node(("app_a", "0002"), None) graph.add_node(("app_a", "0003"), None) graph.add_node(("app_a", "0004"), None) graph.add_node(("app_b", "0001"), None) graph.add_node(("app_b", "0002"), None) graph.add_dependency("app_a.0004", ("app_a", "0004"), ("app_a", "0003")) graph.add_dependency("app_a.0003", ("app_a", "0003"), ("app_a", "0002")) graph.add_dependency("app_a.0002", ("app_a", "0002"), ("app_a", "0001")) graph.add_dependency("app_a.0003", ("app_a", "0003"), ("app_b", "0002")) graph.add_dependency("app_b.0002", ("app_b", "0002"), ("app_b", "0001")) # Test root migration case self.assertEqual( graph.forwards_plan(("app_a", "0001")), [("app_a", "0001")], ) # Test branch B only self.assertEqual( graph.forwards_plan(("app_b", "0002")), [("app_b", "0001"), ("app_b", "0002")], ) # Test whole graph self.assertEqual( graph.forwards_plan(("app_a", "0004")), [ ("app_b", "0001"), ("app_b", "0002"), ("app_a", "0001"), ("app_a", "0002"), ("app_a", "0003"), ("app_a", "0004"), ], ) # Test reverse to b:0002 self.assertEqual( graph.backwards_plan(("app_b", "0002")), [("app_a", "0004"), ("app_a", "0003"), ("app_b", "0002")], ) # Test roots and leaves self.assertEqual( graph.root_nodes(), [("app_a", "0001"), ("app_b", "0001")], ) self.assertEqual( graph.leaf_nodes(), [("app_a", "0004"), ("app_b", "0002")], ) def test_complex_graph(self): r""" Tests a complex dependency graph: app_a: 0001 <-- 0002 <--- 0003 <-- 0004 \ \ / / app_b: 0001 <-\ 0002 <-X / \ \ / app_c: \ 0001 <-- 0002 <- """ # Build graph graph = MigrationGraph() graph.add_node(("app_a", "0001"), None) graph.add_node(("app_a", "0002"), None) graph.add_node(("app_a", "0003"), None) graph.add_node(("app_a", "0004"), None) graph.add_node(("app_b", "0001"), None) graph.add_node(("app_b", "0002"), None) graph.add_node(("app_c", "0001"), None) graph.add_node(("app_c", "0002"), None) graph.add_dependency("app_a.0004", ("app_a", "0004"), ("app_a", "0003")) graph.add_dependency("app_a.0003", ("app_a", "0003"), ("app_a", "0002")) graph.add_dependency("app_a.0002", ("app_a", "0002"), ("app_a", "0001")) graph.add_dependency("app_a.0003", ("app_a", "0003"), ("app_b", "0002")) graph.add_dependency("app_b.0002", ("app_b", "0002"), ("app_b", "0001")) graph.add_dependency("app_a.0004", ("app_a", "0004"), ("app_c", "0002")) graph.add_dependency("app_c.0002", ("app_c", "0002"), ("app_c", "0001")) graph.add_dependency("app_c.0001", ("app_c", "0001"), ("app_b", "0001")) graph.add_dependency("app_c.0002", ("app_c", "0002"), ("app_a", "0002")) # Test branch C only self.assertEqual( graph.forwards_plan(("app_c", "0002")), [ ("app_b", "0001"), ("app_c", "0001"), ("app_a", "0001"), ("app_a", "0002"), ("app_c", "0002"), ], ) # Test whole graph self.assertEqual( graph.forwards_plan(("app_a", "0004")), [ ("app_b", "0001"), ("app_c", "0001"), ("app_a", "0001"), ("app_a", "0002"), ("app_c", "0002"), ("app_b", "0002"), ("app_a", "0003"), ("app_a", "0004"), ], ) # Test reverse to b:0001 self.assertEqual( graph.backwards_plan(("app_b", "0001")), [ ("app_a", "0004"), ("app_c", "0002"), ("app_c", "0001"), ("app_a", "0003"), ("app_b", "0002"), ("app_b", "0001"), ], ) # Test roots and leaves self.assertEqual( graph.root_nodes(), [("app_a", "0001"), ("app_b", "0001"), ("app_c", "0001")], ) self.assertEqual( graph.leaf_nodes(), [("app_a", "0004"), ("app_b", "0002"), ("app_c", "0002")], ) def test_circular_graph(self): """ Tests a circular dependency graph. """ # Build graph graph = MigrationGraph() graph.add_node(("app_a", "0001"), None) graph.add_node(("app_a", "0002"), None) graph.add_node(("app_a", "0003"), None) graph.add_node(("app_b", "0001"), None) graph.add_node(("app_b", "0002"), None) graph.add_dependency("app_a.0003", ("app_a", "0003"), ("app_a", "0002")) graph.add_dependency("app_a.0002", ("app_a", "0002"), ("app_a", "0001")) graph.add_dependency("app_a.0001", ("app_a", "0001"), ("app_b", "0002")) graph.add_dependency("app_b.0002", ("app_b", "0002"), ("app_b", "0001")) graph.add_dependency("app_b.0001", ("app_b", "0001"), ("app_a", "0003")) # Test whole graph with self.assertRaises(CircularDependencyError): graph.ensure_not_cyclic() def test_circular_graph_2(self): graph = MigrationGraph() graph.add_node(("A", "0001"), None) graph.add_node(("C", "0001"), None) graph.add_node(("B", "0001"), None) graph.add_dependency("A.0001", ("A", "0001"), ("B", "0001")) graph.add_dependency("B.0001", ("B", "0001"), ("A", "0001")) graph.add_dependency("C.0001", ("C", "0001"), ("B", "0001")) with self.assertRaises(CircularDependencyError): graph.ensure_not_cyclic() def test_iterative_dfs(self): graph = MigrationGraph() root = ("app_a", "1") graph.add_node(root, None) expected = [root] for i in range(2, 750): parent = ("app_a", str(i - 1)) child = ("app_a", str(i)) graph.add_node(child, None) graph.add_dependency(str(i), child, parent) expected.append(child) leaf = expected[-1] forwards_plan = graph.forwards_plan(leaf) self.assertEqual(expected, forwards_plan) backwards_plan = graph.backwards_plan(root) self.assertEqual(expected[::-1], backwards_plan) def test_iterative_dfs_complexity(self): """ In a graph with merge migrations, iterative_dfs() traverses each node only once even if there are multiple paths leading to it. """ n = 50 graph = MigrationGraph() for i in range(1, n + 1): graph.add_node(("app_a", str(i)), None) graph.add_node(("app_b", str(i)), None) graph.add_node(("app_c", str(i)), None) for i in range(1, n): graph.add_dependency(None, ("app_b", str(i)), ("app_a", str(i))) graph.add_dependency(None, ("app_c", str(i)), ("app_a", str(i))) graph.add_dependency(None, ("app_a", str(i + 1)), ("app_b", str(i))) graph.add_dependency(None, ("app_a", str(i + 1)), ("app_c", str(i))) plan = graph.forwards_plan(("app_a", str(n))) expected = [ (app, str(i)) for i in range(1, n) for app in ["app_a", "app_c", "app_b"] ] + [("app_a", str(n))] self.assertEqual(plan, expected) def test_plan_invalid_node(self): """ Tests for forwards/backwards_plan of nonexistent node. """ graph = MigrationGraph() message = "Node ('app_b', '0001') not a valid node" with self.assertRaisesMessage(NodeNotFoundError, message): graph.forwards_plan(("app_b", "0001")) with self.assertRaisesMessage(NodeNotFoundError, message): graph.backwards_plan(("app_b", "0001")) def test_missing_parent_nodes(self): """ Tests for missing parent nodes. """ # Build graph graph = MigrationGraph() graph.add_node(("app_a", "0001"), None) graph.add_node(("app_a", "0002"), None) graph.add_node(("app_a", "0003"), None) graph.add_node(("app_b", "0001"), None) graph.add_dependency("app_a.0003", ("app_a", "0003"), ("app_a", "0002")) graph.add_dependency("app_a.0002", ("app_a", "0002"), ("app_a", "0001")) msg = ( "Migration app_a.0001 dependencies reference nonexistent parent node " "('app_b', '0002')" ) with self.assertRaisesMessage(NodeNotFoundError, msg): graph.add_dependency("app_a.0001", ("app_a", "0001"), ("app_b", "0002")) def test_missing_child_nodes(self): """ Tests for missing child nodes. """ # Build graph graph = MigrationGraph() graph.add_node(("app_a", "0001"), None) msg = ( "Migration app_a.0002 dependencies reference nonexistent child node " "('app_a', '0002')" ) with self.assertRaisesMessage(NodeNotFoundError, msg): graph.add_dependency("app_a.0002", ("app_a", "0002"), ("app_a", "0001")) def test_validate_consistency_missing_parent(self): graph = MigrationGraph() graph.add_node(("app_a", "0001"), None) graph.add_dependency( "app_a.0001", ("app_a", "0001"), ("app_b", "0002"), skip_validation=True ) msg = ( "Migration app_a.0001 dependencies reference nonexistent parent node " "('app_b', '0002')" ) with self.assertRaisesMessage(NodeNotFoundError, msg): graph.validate_consistency() def test_validate_consistency_missing_child(self): graph = MigrationGraph() graph.add_node(("app_b", "0002"), None) graph.add_dependency( "app_b.0002", ("app_a", "0001"), ("app_b", "0002"), skip_validation=True ) msg = ( "Migration app_b.0002 dependencies reference nonexistent child node " "('app_a', '0001')" ) with self.assertRaisesMessage(NodeNotFoundError, msg): graph.validate_consistency() def test_validate_consistency_no_error(self): graph = MigrationGraph() graph.add_node(("app_a", "0001"), None) graph.add_node(("app_b", "0002"), None) graph.add_dependency( "app_a.0001", ("app_a", "0001"), ("app_b", "0002"), skip_validation=True ) graph.validate_consistency() def test_validate_consistency_dummy(self): """ validate_consistency() raises an error if there's an isolated dummy node. """ msg = "app_a.0001 (req'd by app_b.0002) is missing!" graph = MigrationGraph() graph.add_dummy_node( key=("app_a", "0001"), origin="app_b.0002", error_message=msg ) with self.assertRaisesMessage(NodeNotFoundError, msg): graph.validate_consistency() def test_remove_replaced_nodes(self): """ Replaced nodes are properly removed and dependencies remapped. """ # Add some dummy nodes to be replaced. graph = MigrationGraph() graph.add_dummy_node( key=("app_a", "0001"), origin="app_a.0002", error_message="BAD!" ) graph.add_dummy_node( key=("app_a", "0002"), origin="app_b.0001", error_message="BAD!" ) graph.add_dependency( "app_a.0002", ("app_a", "0002"), ("app_a", "0001"), skip_validation=True ) # Add some normal parent and child nodes to test dependency remapping. graph.add_node(("app_c", "0001"), None) graph.add_node(("app_b", "0001"), None) graph.add_dependency( "app_a.0001", ("app_a", "0001"), ("app_c", "0001"), skip_validation=True ) graph.add_dependency( "app_b.0001", ("app_b", "0001"), ("app_a", "0002"), skip_validation=True ) # Try replacing before replacement node exists. msg = ( "Unable to find replacement node ('app_a', '0001_squashed_0002'). It was " "either never added to the migration graph, or has been removed." ) with self.assertRaisesMessage(NodeNotFoundError, msg): graph.remove_replaced_nodes( replacement=("app_a", "0001_squashed_0002"), replaced=[("app_a", "0001"), ("app_a", "0002")], ) graph.add_node(("app_a", "0001_squashed_0002"), None) # Ensure `validate_consistency()` still raises an error at this stage. with self.assertRaisesMessage(NodeNotFoundError, "BAD!"): graph.validate_consistency() # Remove the dummy nodes. graph.remove_replaced_nodes( replacement=("app_a", "0001_squashed_0002"), replaced=[("app_a", "0001"), ("app_a", "0002")], ) # Ensure graph is now consistent and dependencies have been remapped graph.validate_consistency() parent_node = graph.node_map[("app_c", "0001")] replacement_node = graph.node_map[("app_a", "0001_squashed_0002")] child_node = graph.node_map[("app_b", "0001")] self.assertIn(parent_node, replacement_node.parents) self.assertIn(replacement_node, parent_node.children) self.assertIn(child_node, replacement_node.children) self.assertIn(replacement_node, child_node.parents) def test_remove_replacement_node(self): """ A replacement node is properly removed and child dependencies remapped. We assume parent dependencies are already correct. """ # Add some dummy nodes to be replaced. graph = MigrationGraph() graph.add_node(("app_a", "0001"), None) graph.add_node(("app_a", "0002"), None) graph.add_dependency("app_a.0002", ("app_a", "0002"), ("app_a", "0001")) # Try removing replacement node before replacement node exists. msg = ( "Unable to remove replacement node ('app_a', '0001_squashed_0002'). It was" " either never added to the migration graph, or has been removed already." ) with self.assertRaisesMessage(NodeNotFoundError, msg): graph.remove_replacement_node( replacement=("app_a", "0001_squashed_0002"), replaced=[("app_a", "0001"), ("app_a", "0002")], ) graph.add_node(("app_a", "0001_squashed_0002"), None) # Add a child node to test dependency remapping. graph.add_node(("app_b", "0001"), None) graph.add_dependency( "app_b.0001", ("app_b", "0001"), ("app_a", "0001_squashed_0002") ) # Remove the replacement node. graph.remove_replacement_node( replacement=("app_a", "0001_squashed_0002"), replaced=[("app_a", "0001"), ("app_a", "0002")], ) # Ensure graph is consistent and child dependency has been remapped graph.validate_consistency() replaced_node = graph.node_map[("app_a", "0002")] child_node = graph.node_map[("app_b", "0001")] self.assertIn(child_node, replaced_node.children) self.assertIn(replaced_node, child_node.parents) # Child dependency hasn't also gotten remapped to the other replaced # node. other_replaced_node = graph.node_map[("app_a", "0001")] self.assertNotIn(child_node, other_replaced_node.children) self.assertNotIn(other_replaced_node, child_node.parents) def test_infinite_loop(self): """ Tests a complex dependency graph: app_a: 0001 <- \ app_b: 0001 <- x 0002 <- / \ app_c: 0001<- <------------- x 0002 And apply squashing on app_c. """ graph = MigrationGraph() graph.add_node(("app_a", "0001"), None) graph.add_node(("app_b", "0001"), None) graph.add_node(("app_b", "0002"), None) graph.add_node(("app_c", "0001_squashed_0002"), None) graph.add_dependency( "app_b.0001", ("app_b", "0001"), ("app_c", "0001_squashed_0002") ) graph.add_dependency("app_b.0002", ("app_b", "0002"), ("app_a", "0001")) graph.add_dependency("app_b.0002", ("app_b", "0002"), ("app_b", "0001")) graph.add_dependency( "app_c.0001_squashed_0002", ("app_c", "0001_squashed_0002"), ("app_b", "0002"), ) with self.assertRaises(CircularDependencyError): graph.ensure_not_cyclic() def test_stringify(self): graph = MigrationGraph() self.assertEqual(str(graph), "Graph: 0 nodes, 0 edges") graph.add_node(("app_a", "0001"), None) graph.add_node(("app_a", "0002"), None) graph.add_node(("app_a", "0003"), None) graph.add_node(("app_b", "0001"), None) graph.add_node(("app_b", "0002"), None) graph.add_dependency("app_a.0002", ("app_a", "0002"), ("app_a", "0001")) graph.add_dependency("app_a.0003", ("app_a", "0003"), ("app_a", "0002")) graph.add_dependency("app_a.0003", ("app_a", "0003"), ("app_b", "0002")) self.assertEqual(str(graph), "Graph: 5 nodes, 3 edges") self.assertEqual(repr(graph), "<MigrationGraph: nodes=5, edges=3>") class NodeTests(SimpleTestCase): def test_node_repr(self): node = Node(("app_a", "0001")) self.assertEqual(repr(node), "<Node: ('app_a', '0001')>") def test_node_str(self): node = Node(("app_a", "0001")) self.assertEqual(str(node), "('app_a', '0001')") def test_dummynode_repr(self): node = DummyNode( key=("app_a", "0001"), origin="app_a.0001", error_message="x is missing", ) self.assertEqual(repr(node), "<DummyNode: ('app_a', '0001')>")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_deprecated_fields.py
tests/migrations/test_deprecated_fields.py
from django.core.management import call_command from django.test import override_settings from .test_base import MigrationTestBase class Tests(MigrationTestBase): """ Deprecated model fields should still be usable in historic migrations. """ @override_settings( MIGRATION_MODULES={"migrations": "migrations.deprecated_field_migrations"} ) def test_migrate(self): # Make sure no tables are created self.assertTableNotExists("migrations_ipaddressfield") # Run migration call_command("migrate", verbosity=0) # Make sure the right tables exist self.assertTableExists("migrations_ipaddressfield") # Unmigrate everything call_command("migrate", "migrations", "zero", verbosity=0) # Make sure it's all gone self.assertTableNotExists("migrations_ipaddressfield")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/__init__.py
tests/migrations/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_exceptions.py
tests/migrations/test_exceptions.py
from django.db.migrations.exceptions import NodeNotFoundError from django.test import SimpleTestCase class ExceptionTests(SimpleTestCase): def test_node_not_found_error_repr(self): node = ("some_app_label", "some_migration_label") error_repr = repr(NodeNotFoundError("some message", node)) self.assertEqual( error_repr, "NodeNotFoundError(('some_app_label', 'some_migration_label'))" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/routers.py
tests/migrations/routers.py
class DefaultOtherRouter: def allow_migrate(self, db, app_label, model_name=None, **hints): return db in {"default", "other"} class TestRouter: def allow_migrate(self, db, app_label, model_name=None, **hints): """ The Tribble model should be the only one to appear in the 'other' db. """ if model_name == "tribble": return db == "other" elif db != "default": return False
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_commands.py
tests/migrations/test_commands.py
import datetime import importlib import io import os import re import shutil import sys from pathlib import Path from unittest import mock from django.apps import apps from django.core.checks import Error, Tags, register from django.core.checks.registry import registry from django.core.management import CommandError, call_command from django.core.management.base import SystemCheckError from django.core.management.commands.makemigrations import ( Command as MakeMigrationsCommand, ) from django.core.management.commands.migrate import Command as MigrateCommand from django.db import ( ConnectionHandler, DatabaseError, OperationalError, connection, connections, models, ) from django.db.backends.base.schema import BaseDatabaseSchemaEditor from django.db.backends.utils import truncate_name from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.exceptions import InconsistentMigrationHistory from django.db.migrations.loader import MigrationLoader from django.db.migrations.recorder import MigrationRecorder from django.db.migrations.writer import MigrationWriter from django.test import TestCase, override_settings, skipUnlessDBFeature from django.test.utils import captured_stdout, extend_sys_path, isolate_apps from django.utils import timezone from django.utils.version import get_docs_version from .models import UnicodeModel, UnserializableModel from .routers import TestRouter from .test_base import MigrationTestBase HAS_BLACK = shutil.which("black") class MigrateTests(MigrationTestBase): """ Tests running the migrate command. """ databases = {"default", "other"} @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_migrate(self): """ Tests basic usage of the migrate command. """ # No tables are created self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableNotExists("migrations_book") # Run the migrations to 0001 only stdout = io.StringIO() call_command( "migrate", "migrations", "0001", verbosity=2, stdout=stdout, no_color=True ) stdout = stdout.getvalue() self.assertIn( "Target specific migration: 0001_initial, from migrations", stdout ) self.assertIn("Applying migrations.0001_initial... OK", stdout) self.assertIn("Running pre-migrate handlers for application migrations", stdout) self.assertIn( "Running post-migrate handlers for application migrations", stdout ) # The correct tables exist self.assertTableExists("migrations_author") self.assertTableExists("migrations_tribble") self.assertTableNotExists("migrations_book") # Run migrations all the way call_command("migrate", verbosity=0) # The correct tables exist self.assertTableExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableExists("migrations_book") # Unmigrate everything stdout = io.StringIO() call_command( "migrate", "migrations", "zero", verbosity=2, stdout=stdout, no_color=True ) stdout = stdout.getvalue() self.assertIn("Unapply all migrations: migrations", stdout) self.assertIn("Unapplying migrations.0002_second... OK", stdout) self.assertIn("Running pre-migrate handlers for application migrations", stdout) self.assertIn( "Running post-migrate handlers for application migrations", stdout ) # Tables are gone self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableNotExists("migrations_book") @mock.patch("django.core.management.base.BaseCommand.check") @override_settings( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "migrations.migrations_test_apps.migrated_app", ] ) def test_migrate_with_system_checks(self, mocked_check): out = io.StringIO() call_command("migrate", skip_checks=False, no_color=True, stdout=out) self.assertIn("Apply all migrations: migrated_app", out.getvalue()) mocked_check.assert_called_once_with(databases=["default"]) def test_migrate_with_custom_system_checks(self): original_checks = registry.registered_checks.copy() @register(Tags.signals) def my_check(app_configs, **kwargs): return [Error("my error")] self.addCleanup(setattr, registry, "registered_checks", original_checks) class CustomMigrateCommandWithSignalsChecks(MigrateCommand): requires_system_checks = [Tags.signals] command = CustomMigrateCommandWithSignalsChecks() with self.assertRaises(SystemCheckError): call_command(command, skip_checks=False, stderr=io.StringIO()) class CustomMigrateCommandWithSecurityChecks(MigrateCommand): requires_system_checks = [Tags.security] command = CustomMigrateCommandWithSecurityChecks() call_command(command, skip_checks=False, stdout=io.StringIO()) @override_settings( INSTALLED_APPS=[ "django.contrib.auth", "django.contrib.contenttypes", "migrations.migrations_test_apps.migrated_app", ] ) def test_migrate_runs_database_system_checks(self): original_checks = registry.registered_checks.copy() self.addCleanup(setattr, registry, "registered_checks", original_checks) out = io.StringIO() mock_check = mock.Mock(return_value=[]) register(mock_check, Tags.database) call_command("migrate", skip_checks=False, no_color=True, stdout=out) self.assertIn("Apply all migrations: migrated_app", out.getvalue()) mock_check.assert_called_once_with(app_configs=None, databases=["default"]) @override_settings( INSTALLED_APPS=[ "migrations", "migrations.migrations_test_apps.unmigrated_app_syncdb", ] ) def test_app_without_migrations(self): msg = "App 'unmigrated_app_syncdb' does not have migrations." with self.assertRaisesMessage(CommandError, msg): call_command("migrate", app_label="unmigrated_app_syncdb") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_clashing_prefix"} ) def test_ambiguous_prefix(self): msg = ( "More than one migration matches 'a' in app 'migrations'. Please " "be more specific." ) with self.assertRaisesMessage(CommandError, msg): call_command("migrate", app_label="migrations", migration_name="a") @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_unknown_prefix(self): msg = "Cannot find a migration matching 'nonexistent' from app 'migrations'." with self.assertRaisesMessage(CommandError, msg): call_command( "migrate", app_label="migrations", migration_name="nonexistent" ) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_initial_false"} ) def test_migrate_initial_false(self): """ `Migration.initial = False` skips fake-initial detection. """ # Make sure no tables are created self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") # Run the migrations to 0001 only call_command("migrate", "migrations", "0001", verbosity=0) # Fake rollback call_command("migrate", "migrations", "zero", fake=True, verbosity=0) # Make sure fake-initial detection does not run with self.assertRaises(DatabaseError): call_command( "migrate", "migrations", "0001", fake_initial=True, verbosity=0 ) call_command("migrate", "migrations", "0001", fake=True, verbosity=0) # Real rollback call_command("migrate", "migrations", "zero", verbosity=0) # Make sure it's all gone self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableNotExists("migrations_book") @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations"}, DATABASE_ROUTERS=["migrations.routers.TestRouter"], ) def test_migrate_fake_initial(self): """ --fake-initial only works if all tables created in the initial migration of an app exists. Database routers must be obeyed when doing that check. """ # Make sure no tables are created for db in self.databases: self.assertTableNotExists("migrations_author", using=db) self.assertTableNotExists("migrations_tribble", using=db) try: # Run the migrations to 0001 only call_command("migrate", "migrations", "0001", verbosity=0) call_command("migrate", "migrations", "0001", verbosity=0, database="other") # Make sure the right tables exist self.assertTableExists("migrations_author") self.assertTableNotExists("migrations_tribble") # Also check the "other" database self.assertTableNotExists("migrations_author", using="other") self.assertTableExists("migrations_tribble", using="other") # Fake a roll-back call_command("migrate", "migrations", "zero", fake=True, verbosity=0) call_command( "migrate", "migrations", "zero", fake=True, verbosity=0, database="other", ) # Make sure the tables still exist self.assertTableExists("migrations_author") self.assertTableExists("migrations_tribble", using="other") # Try to run initial migration with self.assertRaises(DatabaseError): call_command("migrate", "migrations", "0001", verbosity=0) # Run initial migration with an explicit --fake-initial out = io.StringIO() with mock.patch( "django.core.management.color.supports_color", lambda *args: False ): call_command( "migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1, ) call_command( "migrate", "migrations", "0001", fake_initial=True, verbosity=0, database="other", ) self.assertIn("migrations.0001_initial... faked", out.getvalue().lower()) # Run migrations all the way. call_command("migrate", verbosity=0) call_command("migrate", verbosity=0, database="other") self.assertTableExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableExists("migrations_book") self.assertTableNotExists("migrations_author", using="other") self.assertTableNotExists("migrations_tribble", using="other") self.assertTableNotExists("migrations_book", using="other") # Fake a roll-back. call_command("migrate", "migrations", "zero", fake=True, verbosity=0) call_command( "migrate", "migrations", "zero", fake=True, verbosity=0, database="other", ) self.assertTableExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableExists("migrations_book") # Run initial migration. with self.assertRaises(DatabaseError): call_command("migrate", "migrations", verbosity=0) # Run initial migration with an explicit --fake-initial. with self.assertRaises(DatabaseError): # Fails because "migrations_tribble" does not exist but needs # to in order to make --fake-initial work. call_command("migrate", "migrations", fake_initial=True, verbosity=0) # Fake an apply. call_command("migrate", "migrations", fake=True, verbosity=0) call_command( "migrate", "migrations", fake=True, verbosity=0, database="other" ) finally: # Unmigrate everything. call_command("migrate", "migrations", "zero", verbosity=0) call_command("migrate", "migrations", "zero", verbosity=0, database="other") # Make sure it's all gone for db in self.databases: self.assertTableNotExists("migrations_author", using=db) self.assertTableNotExists("migrations_tribble", using=db) self.assertTableNotExists("migrations_book", using=db) @skipUnlessDBFeature("ignores_table_name_case") def test_migrate_fake_initial_case_insensitive(self): with override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_fake_initial_case_insensitive.initial", } ): call_command("migrate", "migrations", "0001", verbosity=0) call_command("migrate", "migrations", "zero", fake=True, verbosity=0) with override_settings( MIGRATION_MODULES={ "migrations": ( "migrations.test_fake_initial_case_insensitive.fake_initial" ), } ): out = io.StringIO() call_command( "migrate", "migrations", "0001", fake_initial=True, stdout=out, verbosity=1, no_color=True, ) self.assertIn( "migrations.0001_initial... faked", out.getvalue().lower(), ) @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations_fake_split_initial" } ) def test_migrate_fake_split_initial(self): """ Split initial migrations can be faked with --fake-initial. """ try: call_command("migrate", "migrations", "0002", verbosity=0) call_command("migrate", "migrations", "zero", fake=True, verbosity=0) out = io.StringIO() with mock.patch( "django.core.management.color.supports_color", lambda *args: False ): call_command( "migrate", "migrations", "0002", fake_initial=True, stdout=out, verbosity=1, ) value = out.getvalue().lower() self.assertIn("migrations.0001_initial... faked", value) self.assertIn("migrations.0002_second... faked", value) finally: # Fake an apply. call_command("migrate", "migrations", fake=True, verbosity=0) # Unmigrate everything. call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_conflict"} ) def test_migrate_conflict_exit(self): """ migrate exits if it detects a conflict. """ msg = ( "Conflicting migrations detected; multiple leaf nodes in the " "migration graph: (0002_conflicting_second, 0002_second in " "migrations).\n" "To fix them run 'python manage.py makemigrations --merge'" ) with self.assertRaisesMessage(CommandError, msg): call_command("migrate", "migrations") @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations", } ) def test_migrate_check(self): with self.assertRaises(SystemExit): call_command("migrate", "migrations", "0001", check_unapplied=True) self.assertTableNotExists("migrations_author") self.assertTableNotExists("migrations_tribble") self.assertTableNotExists("migrations_book") @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.migrated_app", ] ) def test_migrate_check_migrated_app(self): out = io.StringIO() try: call_command("migrate", "migrated_app", verbosity=0) call_command( "migrate", "migrated_app", stdout=out, check_unapplied=True, ) self.assertEqual(out.getvalue(), "") finally: # Unmigrate everything. call_command("migrate", "migrated_app", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={ "migrations": "migrations.test_migrations_plan", } ) def test_migrate_check_plan(self): out = io.StringIO() with self.assertRaises(SystemExit): call_command( "migrate", "migrations", "0001", check_unapplied=True, plan=True, stdout=out, no_color=True, ) self.assertEqual( "Planned operations:\n" "migrations.0001_initial\n" " Create model Salamander\n" " Raw Python operation -> Grow salamander tail.\n", out.getvalue(), ) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_showmigrations_list(self): """ showmigrations --list displays migrations and whether or not they're applied. """ out = io.StringIO() with mock.patch( "django.core.management.color.supports_color", lambda *args: True ): call_command( "showmigrations", format="list", stdout=out, verbosity=0, no_color=False ) self.assertEqual( "\x1b[1mmigrations\n\x1b[0m [ ] 0001_initial\n [ ] 0002_second\n", out.getvalue().lower(), ) call_command("migrate", "migrations", "0001", verbosity=0) out = io.StringIO() # Giving the explicit app_label tests for selective `show_list` in the # command call_command( "showmigrations", "migrations", format="list", stdout=out, verbosity=0, no_color=True, ) self.assertEqual( "migrations\n [x] 0001_initial\n [ ] 0002_second\n", out.getvalue().lower() ) out = io.StringIO() # Applied datetimes are displayed at verbosity 2+. call_command( "showmigrations", "migrations", stdout=out, verbosity=2, no_color=True ) migration1 = MigrationRecorder(connection).migration_qs.get( app="migrations", name="0001_initial" ) self.assertEqual( "migrations\n" " [x] 0001_initial (applied at %s)\n" " [ ] 0002_second\n" % migration1.applied.strftime("%Y-%m-%d %H:%M:%S"), out.getvalue().lower(), ) # Cleanup by unmigrating everything call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed"} ) def test_showmigrations_list_squashed(self): out = io.StringIO() call_command( "showmigrations", format="list", stdout=out, verbosity=2, no_color=True ) self.assertEqual( "migrations\n [ ] 0001_squashed_0002 (2 squashed migrations)\n", out.getvalue().lower(), ) out = io.StringIO() call_command( "migrate", "migrations", "0001_squashed_0002", stdout=out, verbosity=2, no_color=True, ) try: self.assertIn( "operations to perform:\n" " target specific migration: 0001_squashed_0002, from migrations\n" "running pre-migrate handlers for application migrations\n" "running migrations:\n" " applying migrations.0001_squashed_0002... ok (", out.getvalue().lower(), ) out = io.StringIO() call_command( "showmigrations", format="list", stdout=out, verbosity=2, no_color=True ) self.assertEqual( "migrations\n [x] 0001_squashed_0002 (2 squashed migrations)\n", out.getvalue().lower(), ) finally: # Unmigrate everything. call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_run_before"} ) def test_showmigrations_plan(self): """ Tests --plan output of showmigrations command """ out = io.StringIO() call_command("showmigrations", format="plan", stdout=out) self.assertEqual( "[ ] migrations.0001_initial\n" "[ ] migrations.0003_third\n" "[ ] migrations.0002_second\n", out.getvalue().lower(), ) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out, verbosity=2) self.assertEqual( "[ ] migrations.0001_initial\n" "[ ] migrations.0003_third ... (migrations.0001_initial)\n" "[ ] migrations.0002_second ... (migrations.0001_initial, " "migrations.0003_third)\n", out.getvalue().lower(), ) call_command("migrate", "migrations", "0003", verbosity=0) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out) self.assertEqual( "[x] migrations.0001_initial\n" "[x] migrations.0003_third\n" "[ ] migrations.0002_second\n", out.getvalue().lower(), ) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out, verbosity=2) self.assertEqual( "[x] migrations.0001_initial\n" "[x] migrations.0003_third ... (migrations.0001_initial)\n" "[ ] migrations.0002_second ... (migrations.0001_initial, " "migrations.0003_third)\n", out.getvalue().lower(), ) # Cleanup by unmigrating everything call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_plan"} ) def test_migrate_plan(self): """Tests migrate --plan output.""" out = io.StringIO() # Show the plan up to the third migration. call_command( "migrate", "migrations", "0003", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n" "migrations.0001_initial\n" " Create model Salamander\n" " Raw Python operation -> Grow salamander tail.\n" "migrations.0002_second\n" " Create model Book\n" " Raw SQL operation -> ['SELECT * FROM migrations_book']\n" "migrations.0003_third\n" " Create model Author\n" " Raw SQL operation -> ['SELECT * FROM migrations_author']\n", out.getvalue(), ) try: # Migrate to the third migration. call_command("migrate", "migrations", "0003", verbosity=0) out = io.StringIO() # Show the plan for when there is nothing to apply. call_command( "migrate", "migrations", "0003", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n No planned migration operations.\n", out.getvalue(), ) out = io.StringIO() # Show the plan for reverse migration back to 0001. call_command( "migrate", "migrations", "0001", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n" "migrations.0003_third\n" " Undo Create model Author\n" " Raw SQL operation -> ['SELECT * FROM migrations_book']\n" "migrations.0002_second\n" " Undo Create model Book\n" " Raw SQL operation -> ['SELECT * FROM migrations_salamand…\n", out.getvalue(), ) out = io.StringIO() # Show the migration plan to fourth, with truncated details. call_command( "migrate", "migrations", "0004", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n" "migrations.0004_fourth\n" " Raw SQL operation -> SELECT * FROM migrations_author WHE…\n", out.getvalue(), ) # Show the plan when an operation is irreversible. # Migrate to the fourth migration. call_command("migrate", "migrations", "0004", verbosity=0) out = io.StringIO() call_command( "migrate", "migrations", "0003", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n" "migrations.0004_fourth\n" " Raw SQL operation -> IRREVERSIBLE\n", out.getvalue(), ) out = io.StringIO() call_command( "migrate", "migrations", "0005", plan=True, stdout=out, no_color=True ) # Operation is marked as irreversible only in the revert plan. self.assertEqual( "Planned operations:\n" "migrations.0005_fifth\n" " Raw Python operation\n" " Raw Python operation\n" " Raw Python operation -> Feed salamander.\n", out.getvalue(), ) call_command("migrate", "migrations", "0005", verbosity=0) out = io.StringIO() call_command( "migrate", "migrations", "0004", plan=True, stdout=out, no_color=True ) self.assertEqual( "Planned operations:\n" "migrations.0005_fifth\n" " Raw Python operation -> IRREVERSIBLE\n" " Raw Python operation -> IRREVERSIBLE\n" " Raw Python operation\n", out.getvalue(), ) finally: # Cleanup by unmigrating everything: fake the irreversible, then # migrate all to zero. call_command("migrate", "migrations", "0003", fake=True, verbosity=0) call_command("migrate", "migrations", "zero", verbosity=0) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"} ) def test_showmigrations_no_migrations(self): out = io.StringIO() call_command("showmigrations", stdout=out, no_color=True) self.assertEqual("migrations\n (no migrations)\n", out.getvalue().lower()) @override_settings( INSTALLED_APPS=["migrations.migrations_test_apps.unmigrated_app"] ) def test_showmigrations_unmigrated_app(self): out = io.StringIO() call_command("showmigrations", "unmigrated_app", stdout=out, no_color=True) try: self.assertEqual( "unmigrated_app\n (no migrations)\n", out.getvalue().lower() ) finally: # unmigrated_app.SillyModel has a foreign key to # 'migrations.Tribble', but that model is only defined in a # migration, so the global app registry never sees it and the # reference is left dangling. Remove it to avoid problems in # subsequent tests. apps._pending_operations.pop(("migrations", "tribble"), None) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_empty"} ) def test_showmigrations_plan_no_migrations(self): """ Tests --plan output of showmigrations command without migrations """ out = io.StringIO() call_command("showmigrations", format="plan", stdout=out, no_color=True) self.assertEqual("(no migrations)\n", out.getvalue().lower()) out = io.StringIO() call_command( "showmigrations", format="plan", stdout=out, verbosity=2, no_color=True ) self.assertEqual("(no migrations)\n", out.getvalue().lower()) @override_settings( MIGRATION_MODULES={"migrations": "migrations.test_migrations_squashed_complex"} ) def test_showmigrations_plan_squashed(self): """ Tests --plan output of showmigrations command with squashed migrations. """ out = io.StringIO() call_command("showmigrations", format="plan", stdout=out) self.assertEqual( "[ ] migrations.1_auto\n" "[ ] migrations.2_auto\n" "[ ] migrations.3_squashed_5\n" "[ ] migrations.6_auto\n" "[ ] migrations.7_auto\n", out.getvalue().lower(), ) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out, verbosity=2) self.assertEqual( "[ ] migrations.1_auto\n" "[ ] migrations.2_auto ... (migrations.1_auto)\n" "[ ] migrations.3_squashed_5 ... (migrations.2_auto)\n" "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n" "[ ] migrations.7_auto ... (migrations.6_auto)\n", out.getvalue().lower(), ) call_command("migrate", "migrations", "3_squashed_5", verbosity=0) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out) self.assertEqual( "[x] migrations.1_auto\n" "[x] migrations.2_auto\n" "[x] migrations.3_squashed_5\n" "[ ] migrations.6_auto\n" "[ ] migrations.7_auto\n", out.getvalue().lower(), ) out = io.StringIO() call_command("showmigrations", format="plan", stdout=out, verbosity=2) self.assertEqual( "[x] migrations.1_auto\n" "[x] migrations.2_auto ... (migrations.1_auto)\n" "[x] migrations.3_squashed_5 ... (migrations.2_auto)\n" "[ ] migrations.6_auto ... (migrations.3_squashed_5)\n" "[ ] migrations.7_auto ... (migrations.6_auto)\n", out.getvalue().lower(), ) @override_settings( INSTALLED_APPS=[ "migrations.migrations_test_apps.mutate_state_b", "migrations.migrations_test_apps.alter_fk.author_app", "migrations.migrations_test_apps.alter_fk.book_app", ] ) def test_showmigrations_plan_single_app_label(self): """ `showmigrations --plan app_label` output with a single app_label. """ # Single app with no dependencies on other apps. out = io.StringIO() call_command("showmigrations", "mutate_state_b", format="plan", stdout=out) self.assertEqual( "[ ] mutate_state_b.0001_initial\n[ ] mutate_state_b.0002_add_field\n", out.getvalue(), ) # Single app with dependencies. out = io.StringIO() call_command("showmigrations", "author_app", format="plan", stdout=out) self.assertEqual( "[ ] author_app.0001_initial\n" "[ ] book_app.0001_initial\n"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_squashed_complex/3_auto.py
tests/migrations/test_migrations_squashed_complex/3_auto.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [("migrations", "2_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_squashed_complex/1_auto.py
tests/migrations/test_migrations_squashed_complex/1_auto.py
from django.db import migrations class Migration(migrations.Migration): operations = [migrations.RunPython(migrations.RunPython.noop)]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_squashed_complex/4_auto.py
tests/migrations/test_migrations_squashed_complex/4_auto.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [("migrations", "3_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_squashed_complex/2_auto.py
tests/migrations/test_migrations_squashed_complex/2_auto.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [("migrations", "1_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_squashed_complex/6_auto.py
tests/migrations/test_migrations_squashed_complex/6_auto.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [("migrations", "5_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_squashed_complex/5_auto.py
tests/migrations/test_migrations_squashed_complex/5_auto.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [("migrations", "4_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_squashed_complex/7_auto.py
tests/migrations/test_migrations_squashed_complex/7_auto.py
from django.db import migrations class Migration(migrations.Migration): dependencies = [("migrations", "6_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_squashed_complex/__init__.py
tests/migrations/test_migrations_squashed_complex/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_squashed_complex/3_squashed_5.py
tests/migrations/test_migrations_squashed_complex/3_squashed_5.py
from django.db import migrations class Migration(migrations.Migration): replaces = [ ("migrations", "3_auto"), ("migrations", "4_auto"), ("migrations", "5_auto"), ] dependencies = [("migrations", "2_auto")] operations = [migrations.RunPython(migrations.RunPython.noop)]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_fake_initial_case_insensitive/initial/0001_initial.py
tests/migrations/test_fake_initial_case_insensitive/initial/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True operations = [ migrations.CreateModel( name="fakeinitialmodel", fields=[ ("id", models.AutoField(primary_key=True)), ("field", models.CharField(max_length=20)), ( "field_mixed_case", models.CharField(max_length=20, db_column="FiEld_MiXeD_CaSe"), ), ( "fake_initial_mode", models.ManyToManyField( "migrations.FakeInitialModel", db_table="m2m_MiXeD_CaSe" ), ), ], options={ "db_table": "migrations_MiXeD_CaSe_MoDel", }, ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_fake_initial_case_insensitive/initial/__init__.py
tests/migrations/test_fake_initial_case_insensitive/initial/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_fake_initial_case_insensitive/fake_initial/0001_initial.py
tests/migrations/test_fake_initial_case_insensitive/fake_initial/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True operations = [ migrations.CreateModel( "fakeinitialmodel", [ ("id", models.AutoField(primary_key=True)), ("field", models.CharField(max_length=20)), ], options={ "db_table": "migrations_mIxEd_cAsE_mOdEl", }, ), migrations.AddField( model_name="fakeinitialmodel", name="field_mixed_case", field=models.CharField(max_length=20, db_column="fIeLd_mIxEd_cAsE"), ), migrations.AddField( model_name="fakeinitialmodel", name="fake_initial_model", field=models.ManyToManyField( to="migrations.fakeinitialmodel", db_table="m2m_mIxEd_cAsE" ), ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_fake_initial_case_insensitive/fake_initial/__init__.py
tests/migrations/test_fake_initial_case_insensitive/fake_initial/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/faulty_migrations/file.py
tests/migrations/faulty_migrations/file.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/faulty_migrations/__init__.py
tests/migrations/faulty_migrations/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/faulty_migrations/namespace/foo/__init__.py
tests/migrations/faulty_migrations/namespace/foo/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_private/.util.py
tests/migrations/test_migrations_private/.util.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_private/~util.py
tests/migrations/test_migrations_private/~util.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_private/0001_initial.py
tests/migrations/test_migrations_private/0001_initial.py
from django.db import migrations class Migration(migrations.Migration): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_private/_util.py
tests/migrations/test_migrations_private/_util.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_private/__init__.py
tests/migrations/test_migrations_private/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_add_many_to_many_field_initial/0001_initial.py
tests/migrations/test_add_many_to_many_field_initial/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [ migrations.CreateModel( name="Project", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ], ), migrations.CreateModel( name="Task", fields=[ ( "id", models.AutoField( auto_created=True, primary_key=True, serialize=False, verbose_name="ID", ), ), ], ), migrations.AddField( model_name="project", name="tasks", field=models.ManyToManyField(to="Task"), ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_add_many_to_many_field_initial/0002_initial.py
tests/migrations/test_add_many_to_many_field_initial/0002_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ("migrations", "0001_initial"), ] operations = [ migrations.AddField( model_name="task", name="projects", field=models.ManyToManyField(to="Project"), ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_add_many_to_many_field_initial/__init__.py
tests/migrations/test_add_many_to_many_field_initial/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_conflict_long_name/0002_conflicting_second_migration_with_long_name.py
tests/migrations/test_migrations_conflict_long_name/0002_conflicting_second_migration_with_long_name.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("migrations", "0001_initial")] operations = [ migrations.CreateModel( "SomethingElse", [ ("id", models.AutoField(primary_key=True)), ], ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/tests/migrations/test_migrations_conflict_long_name/0001_initial.py
tests/migrations/test_migrations_conflict_long_name/0001_initial.py
from django.db import migrations, models class Migration(migrations.Migration): initial = True operations = [ migrations.CreateModel( "Author", [ ("id", models.AutoField(primary_key=True)), ], ), ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false