hash
stringlengths
64
64
content
stringlengths
0
1.51M
560d269ee834d733cfd7a6c03238abdb17f313eae144e602a7041afef944fb25
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) def tearDown(self): # Close down the second connection. self.conn2.rollback() self.conn2.close() def test_concurrent_delete(self): """Concurrent deletes don't collide and lock the database (#9479).""" with transaction.atomic(): Book.objects.create(id=1, pagecount=100) Book.objects.create(id=2, pagecount=200) Book.objects.create(id=3, pagecount=300) with transaction.atomic(): # Start a transaction on the main connection. self.assertEqual(3, Book.objects.count()) # Delete something using another database connection. with self.conn2.cursor() as cursor2: cursor2.execute("DELETE from delete_regress_book WHERE id = 1") self.conn2.commit() # In the same transaction on the main connection, perform a # queryset delete that covers the object deleted with the other # connection. This causes an infinite loop under MySQL InnoDB # unless we keep track of already deleted objects. Book.objects.filter(pagecount__lt=250).delete() self.assertEqual(1, Book.objects.count()) class DeleteCascadeTests(TestCase): def test_generic_relation_cascade(self): """ Django cascades deletes through generic-related objects to their reverse relations. """ person = Person.objects.create(name="Nelson Mandela") award = Award.objects.create(name="Nobel", content_object=person) AwardNote.objects.create(note="a peace prize", award=award) self.assertEqual(AwardNote.objects.count(), 1) person.delete() self.assertEqual(Award.objects.count(), 0) # first two asserts are just sanity checks, this is the kicker: self.assertEqual(AwardNote.objects.count(), 0) def test_fk_to_m2m_through(self): """ If an M2M relationship has an explicitly-specified through model, and some other model has an FK to that through model, deletion is cascaded from one of the participants in the M2M, to the through model, to its related model. """ juan = Child.objects.create(name="Juan") paints = Toy.objects.create(name="Paints") played = PlayedWith.objects.create( child=juan, toy=paints, date=datetime.date.today() ) PlayedWithNote.objects.create(played=played, note="the next Jackson Pollock") self.assertEqual(PlayedWithNote.objects.count(), 1) paints.delete() self.assertEqual(PlayedWith.objects.count(), 0) # first two asserts just sanity checks, this is the kicker: self.assertEqual(PlayedWithNote.objects.count(), 0) def test_15776(self): policy = Policy.objects.create(pk=1, policy_number="1234") version = Version.objects.create(policy=policy) location = Location.objects.create(version=version) Item.objects.create(version=version, location=location) policy.delete() class DeleteCascadeTransactionTests(TransactionTestCase): available_apps = ["delete_regress"] def test_inheritance(self): """ Auto-created many-to-many through tables referencing a parent model are correctly found by the delete cascade when a child of that parent is deleted. Refs #14896. """ r = Researcher.objects.create() email = Email.objects.create( label="office-email", email_address="[email protected]" ) r.contacts.add(email) email.delete() def test_to_field(self): """ Cascade deletion works with ForeignKey.to_field set to non-PK. """ apple = Food.objects.create(name="apple") Eaten.objects.create(food=apple, meal="lunch") apple.delete() self.assertFalse(Food.objects.exists()) self.assertFalse(Eaten.objects.exists()) class LargeDeleteTests(TestCase): def test_large_deletes(self): """ 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()) Book.objects.filter( Exists( Book.objects.filter( pk=OuterRef("pk"), owner__toys=toy.pk, ), ) ).delete() self.assertIs(Book.objects.exists(), False) class DeleteDistinct(SimpleTestCase): def test_disallowed_delete_distinct(self): msg = "Cannot call delete() after .distinct()." with self.assertRaisesMessage(TypeError, msg): Book.objects.distinct().delete() with self.assertRaisesMessage(TypeError, msg): Book.objects.distinct("id").delete()
b229d5c86b05cd38034d2762af453d313f7aac2478f1aa33d45925a804ec5c8b
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) # 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"]
a6b6e1e4751721af12001a309b9dec5f9746ff4edcfaafe50b6ec7e9ed1d8cdd
""" Testing using the Test Client The test client is a class that can act like a simple browser for testing purposes. It allows the user to compose GET and POST requests, and obtain the response that the server gave to those requests. The server Response objects are annotated with the details of the contexts and templates that were rendered during the process of serving the request. ``Client`` objects are stateful - they will retain cookie (and thus session) details for the lifetime of the ``Client`` instance. This is not intended as a replacement for Twill, Selenium, or other browser automation frameworks - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ import itertools import tempfile from unittest import mock from django.contrib.auth.models import User from django.core import mail from django.http import HttpResponse, HttpResponseNotAllowed from django.test import ( AsyncRequestFactory, Client, RequestFactory, SimpleTestCase, TestCase, modify_settings, override_settings, ) from django.urls import reverse_lazy from django.utils.decorators import async_only_middleware from django.views.generic import RedirectView from .views import TwoArgException, get_view, post_view, trace_view def middleware_urlconf(get_response): def middleware(request): request.urlconf = "tests.test_client.urls_middleware_urlconf" return get_response(request) return middleware @async_only_middleware def async_middleware_urlconf(get_response): async def middleware(request): request.urlconf = "tests.test_client.urls_middleware_urlconf" return await get_response(request) return middleware @override_settings(ROOT_URLCONF="test_client.urls") class ClientTest(TestCase): @classmethod def setUpTestData(cls): cls.u1 = User.objects.create_user(username="testclient", password="password") cls.u2 = User.objects.create_user( username="inactive", password="password", is_active=False ) def test_get_view(self): "GET a view" # The data is ignored, but let's check it doesn't crash the system # anyway. data = {"var": "\xf2"} response = self.client.get("/get_view/", data) # Check some response details self.assertContains(response, "This is a test") self.assertEqual(response.context["var"], "\xf2") self.assertEqual(response.templates[0].name, "GET Template") def test_query_string_encoding(self): # WSGI requires latin-1 encoded strings. response = self.client.get("/get_view/?var=1\ufffd") self.assertEqual(response.context["var"], "1\ufffd") def test_get_data_none(self): msg = ( "Cannot encode None for key 'value' in a query string. Did you " "mean to pass an empty string or omit the value?" ) with self.assertRaisesMessage(TypeError, msg): self.client.get("/get_view/", {"value": None}) def test_get_post_view(self): "GET a view that normally expects POSTs" response = self.client.get("/post_view/", {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Empty GET Template") self.assertTemplateUsed(response, "Empty GET Template") self.assertTemplateNotUsed(response, "Empty POST Template") def test_empty_post(self): "POST an empty dictionary to a view" response = self.client.post("/post_view/", {}) # Check some response details self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Empty POST Template") self.assertTemplateNotUsed(response, "Empty GET Template") self.assertTemplateUsed(response, "Empty POST Template") def test_post(self): "POST some data to a view" post_data = {"value": 37} response = self.client.post("/post_view/", post_data) # Check some response details self.assertContains(response, "Data received") self.assertEqual(response.context["data"], "37") self.assertEqual(response.templates[0].name, "POST Template") def test_post_data_none(self): msg = ( "Cannot encode None for key 'value' as POST data. Did you mean " "to pass an empty string or omit the value?" ) with self.assertRaisesMessage(TypeError, msg): self.client.post("/post_view/", {"value": None}) def test_json_serialization(self): """The test client serializes JSON data.""" methods = ("post", "put", "patch", "delete") tests = ( ({"value": 37}, {"value": 37}), ([37, True], [37, True]), ((37, False), [37, False]), ) for method in methods: with self.subTest(method=method): for data, expected in tests: with self.subTest(data): client_method = getattr(self.client, method) method_name = method.upper() response = client_method( "/json_view/", data, content_type="application/json" ) self.assertContains(response, "Viewing %s page." % method_name) self.assertEqual(response.context["data"], expected) def test_json_encoder_argument(self): """The test Client accepts a json_encoder.""" mock_encoder = mock.MagicMock() mock_encoding = mock.MagicMock() mock_encoder.return_value = mock_encoding mock_encoding.encode.return_value = '{"value": 37}' client = self.client_class(json_encoder=mock_encoder) # Vendored tree JSON content types are accepted. client.post( "/json_view/", {"value": 37}, content_type="application/vnd.api+json" ) self.assertTrue(mock_encoder.called) self.assertTrue(mock_encoding.encode.called) def test_put(self): response = self.client.put("/put_view/", {"foo": "bar"}) self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "PUT Template") self.assertEqual(response.context["data"], "{'foo': 'bar'}") self.assertEqual(response.context["Content-Length"], "14") def test_trace(self): """TRACE a view""" response = self.client.trace("/trace_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["method"], "TRACE") self.assertEqual(response.templates[0].name, "TRACE Template") def test_response_headers(self): "Check the value of HTTP headers returned in a response" response = self.client.get("/header_view/") self.assertEqual(response.headers["X-DJANGO-TEST"], "Slartibartfast") def test_response_attached_request(self): """ The returned response has a ``request`` attribute with the originating environ dict and a ``wsgi_request`` with the originating WSGIRequest. """ response = self.client.get("/header_view/") self.assertTrue(hasattr(response, "request")) self.assertTrue(hasattr(response, "wsgi_request")) for key, value in response.request.items(): self.assertIn(key, response.wsgi_request.environ) self.assertEqual(response.wsgi_request.environ[key], value) def test_response_resolver_match(self): """ The response contains a ResolverMatch instance. """ response = self.client.get("/header_view/") self.assertTrue(hasattr(response, "resolver_match")) def test_response_resolver_match_redirect_follow(self): """ The response ResolverMatch instance contains the correct information when following redirects. """ response = self.client.get("/redirect_view/", follow=True) self.assertEqual(response.resolver_match.url_name, "get_view") def test_response_resolver_match_regular_view(self): """ The response ResolverMatch instance contains the correct information when accessing a regular view. """ response = self.client.get("/get_view/") self.assertEqual(response.resolver_match.url_name, "get_view") def test_response_resolver_match_class_based_view(self): """ The response ResolverMatch instance can be used to access the CBV view class. """ response = self.client.get("/accounts/") self.assertIs(response.resolver_match.func.view_class, RedirectView) @modify_settings(MIDDLEWARE={"prepend": "test_client.tests.middleware_urlconf"}) def test_response_resolver_match_middleware_urlconf(self): response = self.client.get("/middleware_urlconf_view/") self.assertEqual(response.resolver_match.url_name, "middleware_urlconf_view") def test_raw_post(self): "POST raw data (with a content type) to a view" test_doc = """<?xml version="1.0" encoding="utf-8"?> <library><book><title>Blink</title><author>Malcolm Gladwell</author></book> </library> """ response = self.client.post( "/raw_post_view/", test_doc, content_type="text/xml" ) self.assertEqual(response.status_code, 200) self.assertEqual(response.templates[0].name, "Book template") self.assertEqual(response.content, b"Blink - Malcolm Gladwell") def test_insecure(self): "GET a URL through http" response = self.client.get("/secure_view/", secure=False) self.assertFalse(response.test_was_secure_request) self.assertEqual(response.test_server_port, "80") def test_secure(self): "GET a URL through https" response = self.client.get("/secure_view/", secure=True) self.assertTrue(response.test_was_secure_request) self.assertEqual(response.test_server_port, "443") def test_redirect(self): "GET a URL that redirects elsewhere" response = self.client.get("/redirect_view/") self.assertRedirects(response, "/get_view/") def test_redirect_with_query(self): "GET a URL that redirects with given GET parameters" response = self.client.get("/redirect_view/", {"var": "value"}) self.assertRedirects(response, "/get_view/?var=value") def test_redirect_with_query_ordering(self): """assertRedirects() ignores the order of query string parameters.""" response = self.client.get("/redirect_view/", {"var": "value", "foo": "bar"}) self.assertRedirects(response, "/get_view/?var=value&foo=bar") self.assertRedirects(response, "/get_view/?foo=bar&var=value") def test_permanent_redirect(self): "GET a URL that redirects permanently elsewhere" response = self.client.get("/permanent_redirect_view/") self.assertRedirects(response, "/get_view/", status_code=301) def test_temporary_redirect(self): "GET a URL that does a non-permanent redirect" response = self.client.get("/temporary_redirect_view/") self.assertRedirects(response, "/get_view/", status_code=302) def test_redirect_to_strange_location(self): "GET a URL that redirects to a non-200 page" response = self.client.get("/double_redirect_view/") # The response was a 302, and that the attempt to get the redirection # location returned 301 when retrieved self.assertRedirects( response, "/permanent_redirect_view/", target_status_code=301 ) def test_follow_redirect(self): "A URL that redirects can be followed to termination." response = self.client.get("/double_redirect_view/", follow=True) self.assertRedirects( response, "/get_view/", status_code=302, target_status_code=200 ) self.assertEqual(len(response.redirect_chain), 2) def test_follow_relative_redirect(self): "A URL with a relative redirect can be followed." response = self.client.get("/accounts/", follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/accounts/login/") def test_follow_relative_redirect_no_trailing_slash(self): "A URL with a relative redirect with no trailing slash can be followed." response = self.client.get("/accounts/no_trailing_slash", follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/accounts/login/") def test_redirect_to_querystring_only(self): """A URL that consists of a querystring only can be followed""" response = self.client.post("/post_then_get_view/", follow=True) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/post_then_get_view/") self.assertEqual(response.content, b"The value of success is true.") def test_follow_307_and_308_redirect(self): """ A 307 or 308 redirect preserves the request method after the redirect. """ methods = ("get", "post", "head", "options", "put", "patch", "delete", "trace") codes = (307, 308) for method, code in itertools.product(methods, codes): with self.subTest(method=method, code=code): req_method = getattr(self.client, method) response = req_method( "/redirect_view_%s/" % code, data={"value": "test"}, follow=True ) self.assertEqual(response.status_code, 200) self.assertEqual(response.request["PATH_INFO"], "/post_view/") self.assertEqual(response.request["REQUEST_METHOD"], method.upper()) def test_follow_307_and_308_preserves_query_string(self): methods = ("post", "options", "put", "patch", "delete", "trace") codes = (307, 308) for method, code in itertools.product(methods, codes): with self.subTest(method=method, code=code): req_method = getattr(self.client, method) response = req_method( "/redirect_view_%s_query_string/" % code, data={"value": "test"}, follow=True, ) self.assertRedirects( response, "/post_view/?hello=world", status_code=code ) self.assertEqual(response.request["QUERY_STRING"], "hello=world") def test_follow_307_and_308_get_head_query_string(self): methods = ("get", "head") codes = (307, 308) for method, code in itertools.product(methods, codes): with self.subTest(method=method, code=code): req_method = getattr(self.client, method) response = req_method( "/redirect_view_%s_query_string/" % code, data={"value": "test"}, follow=True, ) self.assertRedirects( response, "/post_view/?hello=world", status_code=code ) self.assertEqual(response.request["QUERY_STRING"], "value=test") def test_follow_307_and_308_preserves_post_data(self): for code in (307, 308): with self.subTest(code=code): response = self.client.post( "/redirect_view_%s/" % code, data={"value": "test"}, follow=True ) self.assertContains(response, "test is the value") def test_follow_307_and_308_preserves_put_body(self): for code in (307, 308): with self.subTest(code=code): response = self.client.put( "/redirect_view_%s/?to=/put_view/" % code, data="a=b", follow=True ) self.assertContains(response, "a=b is the body") def test_follow_307_and_308_preserves_get_params(self): data = {"var": 30, "to": "/get_view/"} for code in (307, 308): with self.subTest(code=code): response = self.client.get( "/redirect_view_%s/" % code, data=data, follow=True ) self.assertContains(response, "30 is the value") def test_redirect_http(self): """GET a URL that redirects to an HTTP URI.""" response = self.client.get("/http_redirect_view/", follow=True) self.assertFalse(response.test_was_secure_request) def test_redirect_https(self): """GET a URL that redirects to an HTTPS URI.""" response = self.client.get("/https_redirect_view/", follow=True) self.assertTrue(response.test_was_secure_request) def test_notfound_response(self): "GET a URL that responds as '404:Not Found'" response = self.client.get("/bad_view/") self.assertContains(response, "MAGIC", status_code=404) def test_valid_form(self): "POST valid data to a form" post_data = { "text": "Hello World", "email": "[email protected]", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Valid POST Template") def test_valid_form_with_hints(self): "GET a form, providing hints in the GET data" hints = {"text": "Hello World", "multi": ("b", "c", "e")} response = self.client.get("/form_view/", data=hints) # The multi-value data has been rolled out ok self.assertContains(response, "Select a valid choice.", 0) self.assertTemplateUsed(response, "Form GET Template") def test_incomplete_data_form(self): "POST incomplete data to a form" post_data = {"text": "Hello World", "value": 37} response = self.client.post("/form_view/", post_data) self.assertContains(response, "This field is required.", 3) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError(response, "form", "email", "This field is required.") self.assertFormError(response, "form", "single", "This field is required.") self.assertFormError(response, "form", "multi", "This field is required.") def test_form_error(self): "POST erroneous data to a form" post_data = { "text": "Hello World", "email": "not an email address", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view/", post_data) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, "Invalid POST Template") self.assertFormError(response, "form", "email", "Enter a valid email address.") def test_valid_form_with_template(self): "POST valid data to a form using multiple templates" post_data = { "text": "Hello World", "email": "[email protected]", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view_with_template/", post_data) self.assertContains(response, "POST data OK") self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, "base.html") self.assertTemplateNotUsed(response, "Valid POST Template") def test_incomplete_data_form_with_template(self): "POST incomplete data to a form using multiple templates" post_data = {"text": "Hello World", "value": 37} response = self.client.post("/form_view_with_template/", post_data) self.assertContains(response, "POST data has errors") self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, "base.html") self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError(response, "form", "email", "This field is required.") self.assertFormError(response, "form", "single", "This field is required.") self.assertFormError(response, "form", "multi", "This field is required.") def test_form_error_with_template(self): "POST erroneous data to a form using multiple templates" post_data = { "text": "Hello World", "email": "not an email address", "value": 37, "single": "b", "multi": ("b", "c", "e"), } response = self.client.post("/form_view_with_template/", post_data) self.assertContains(response, "POST data has errors") self.assertTemplateUsed(response, "form_view.html") self.assertTemplateUsed(response, "base.html") self.assertTemplateNotUsed(response, "Invalid POST Template") self.assertFormError(response, "form", "email", "Enter a valid email address.") def test_unknown_page(self): "GET an invalid URL" response = self.client.get("/unknown_view/") # The response was a 404 self.assertEqual(response.status_code, 404) def test_url_parameters(self): "Make sure that URL ;-parameters are not stripped." response = self.client.get("/unknown_view/;some-parameter") # The path in the response includes it (ignore that it's a 404) self.assertEqual(response.request["PATH_INFO"], "/unknown_view/;some-parameter") def test_view_with_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") @override_settings( INSTALLED_APPS=["django.contrib.auth"], SESSION_ENGINE="django.contrib.sessions.backends.file", ) def test_view_with_login_when_sessions_app_is_not_installed(self): self.test_view_with_login() def test_view_with_force_login(self): "Request a page that is protected with @login_required" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_method_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/login_protected_method_view/" ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Request a page that requires a login response = self.client.get("/login_protected_method_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_method_force_login(self): "Request a page that is protected with a @login_required method" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/login_protected_method_view/" ) # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_method_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_login_and_custom_redirect(self): """ Request a page that is protected with @login_required(redirect_field_name='redirect_to') """ # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view_custom_redirect/") self.assertRedirects( response, "/accounts/login/?redirect_to=/login_protected_view_custom_redirect/", ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Request a page that requires a login response = self.client.get("/login_protected_view_custom_redirect/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_force_login_and_custom_redirect(self): """ Request a page that is protected with @login_required(redirect_field_name='redirect_to') """ # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view_custom_redirect/") self.assertRedirects( response, "/accounts/login/?redirect_to=/login_protected_view_custom_redirect/", ) # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_view_custom_redirect/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") def test_view_with_bad_login(self): "Request a page that is protected with @login, but use bad credentials" login = self.client.login(username="otheruser", password="nopassword") self.assertFalse(login) def test_view_with_inactive_login(self): """ An inactive user may login if the authenticate backend allows it. """ credentials = {"username": "inactive", "password": "password"} self.assertFalse(self.client.login(**credentials)) with self.settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.AllowAllUsersModelBackend" ] ): self.assertTrue(self.client.login(**credentials)) @override_settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.ModelBackend", "django.contrib.auth.backends.AllowAllUsersModelBackend", ] ) def test_view_with_inactive_force_login(self): "Request a page that is protected with @login, but use an inactive login" # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in self.client.force_login( self.u2, backend="django.contrib.auth.backends.AllowAllUsersModelBackend" ) # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "inactive") def test_logout(self): "Request a logout after logging in" # Log in self.client.login(username="testclient", password="password") # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") # Log out self.client.logout() # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") def test_logout_with_force_login(self): "Request a logout after logging in" # Log in self.client.force_login(self.u1) # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") # Log out self.client.logout() # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") @override_settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.ModelBackend", "test_client.auth_backends.TestClientBackend", ], ) def test_force_login_with_backend(self): """ Request a page that is protected with @login_required when using force_login() and passing a backend. """ # Get the page without logging in. Should result in 302. response = self.client.get("/login_protected_view/") self.assertRedirects(response, "/accounts/login/?next=/login_protected_view/") # Log in self.client.force_login( self.u1, backend="test_client.auth_backends.TestClientBackend" ) self.assertEqual(self.u1.backend, "test_client.auth_backends.TestClientBackend") # Request a page that requires a login response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") @override_settings( AUTHENTICATION_BACKENDS=[ "django.contrib.auth.backends.ModelBackend", "test_client.auth_backends.TestClientBackend", ], ) def test_force_login_without_backend(self): """ force_login() without passing a backend and with multiple backends configured should automatically use the first backend. """ self.client.force_login(self.u1) response = self.client.get("/login_protected_view/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context["user"].username, "testclient") self.assertEqual(self.u1.backend, "django.contrib.auth.backends.ModelBackend") @override_settings( AUTHENTICATION_BACKENDS=[ "test_client.auth_backends.BackendWithoutGetUserMethod", "django.contrib.auth.backends.ModelBackend", ] ) def test_force_login_with_backend_missing_get_user(self): """ force_login() skips auth backends without a get_user() method. """ self.client.force_login(self.u1) self.assertEqual(self.u1.backend, "django.contrib.auth.backends.ModelBackend") @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies") def test_logout_cookie_sessions(self): self.test_logout() def test_view_with_permissions(self): "Request a page that is protected with @permission_required" # Get the page without logging in. Should result in 302. response = self.client.get("/permission_protected_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_view/" ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Log in with wrong permissions. Should result in 302. response = self.client.get("/permission_protected_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_view/" ) # TODO: Log in with right permissions and request the page again def test_view_with_permissions_exception(self): """ Request a page that is protected with @permission_required but raises an exception. """ # Get the page without logging in. Should result in 403. response = self.client.get("/permission_protected_view_exception/") self.assertEqual(response.status_code, 403) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Log in with wrong permissions. Should result in 403. response = self.client.get("/permission_protected_view_exception/") self.assertEqual(response.status_code, 403) def test_view_with_method_permissions(self): "Request a page that is protected with a @permission_required method" # Get the page without logging in. Should result in 302. response = self.client.get("/permission_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_method_view/" ) # Log in login = self.client.login(username="testclient", password="password") self.assertTrue(login, "Could not log in") # Log in with wrong permissions. Should result in 302. response = self.client.get("/permission_protected_method_view/") self.assertRedirects( response, "/accounts/login/?next=/permission_protected_method_view/" ) # TODO: Log in with right permissions and request the page again def test_external_redirect(self): response = self.client.get("/django_project_redirect/") self.assertRedirects( response, "https://www.djangoproject.com/", fetch_redirect_response=False ) def test_external_redirect_without_trailing_slash(self): """ Client._handle_redirects() with an empty path. """ response = self.client.get("/no_trailing_slash_external_redirect/", follow=True) self.assertRedirects(response, "https://testserver") def test_external_redirect_with_fetch_error_msg(self): """ assertRedirects without fetch_redirect_response=False raises a relevant ValueError rather than a non-descript AssertionError. """ response = self.client.get("/django_project_redirect/") msg = ( "The test client is unable to fetch remote URLs (got " "https://www.djangoproject.com/). If the host is served by Django, " "add 'www.djangoproject.com' to ALLOWED_HOSTS. " "Otherwise, use assertRedirects(..., fetch_redirect_response=False)." ) with self.assertRaisesMessage(ValueError, msg): self.assertRedirects(response, "https://www.djangoproject.com/") def test_session_modifying_view(self): "Request a page that modifies the session" # Session value isn't set initially with self.assertRaises(KeyError): self.client.session["tobacconist"] self.client.post("/session_view/") # The session was modified self.assertEqual(self.client.session["tobacconist"], "hovercraft") @override_settings( INSTALLED_APPS=[], SESSION_ENGINE="django.contrib.sessions.backends.file", ) def test_sessions_app_is_not_installed(self): self.test_session_modifying_view() @override_settings( INSTALLED_APPS=[], SESSION_ENGINE="django.contrib.sessions.backends.nonexistent", ) def test_session_engine_is_invalid(self): with self.assertRaisesMessage(ImportError, "nonexistent"): self.test_session_modifying_view() def test_view_with_exception(self): "Request a page that is known to throw an error" with self.assertRaises(KeyError): self.client.get("/broken_view/") def test_exc_info(self): client = Client(raise_request_exception=False) response = client.get("/broken_view/") self.assertEqual(response.status_code, 500) exc_type, exc_value, exc_traceback = response.exc_info self.assertIs(exc_type, KeyError) self.assertIsInstance(exc_value, KeyError) self.assertEqual(str(exc_value), "'Oops! Looks like you wrote some bad code.'") self.assertIsNotNone(exc_traceback) def test_exc_info_none(self): response = self.client.get("/get_view/") self.assertIsNone(response.exc_info) def test_mail_sending(self): "Mail is redirected to a dummy outbox during test setup" response = self.client.get("/mail_sending_view/") self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, "Test message") self.assertEqual(mail.outbox[0].body, "This is a test email") self.assertEqual(mail.outbox[0].from_email, "[email protected]") self.assertEqual(mail.outbox[0].to[0], "[email protected]") self.assertEqual(mail.outbox[0].to[1], "[email protected]") def test_reverse_lazy_decodes(self): "reverse_lazy() works in the test client" data = {"var": "data"} response = self.client.get(reverse_lazy("get_view"), data) # Check some response details self.assertContains(response, "This is a test") def test_relative_redirect(self): response = self.client.get("/accounts/") self.assertRedirects(response, "/accounts/login/") def test_relative_redirect_no_trailing_slash(self): response = self.client.get("/accounts/no_trailing_slash") self.assertRedirects(response, "/accounts/login/") def test_mass_mail_sending(self): "Mass mail is redirected to a dummy outbox during test setup" response = self.client.get("/mass_mail_sending_view/") self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 2) self.assertEqual(mail.outbox[0].subject, "First Test message") self.assertEqual(mail.outbox[0].body, "This is the first test email") self.assertEqual(mail.outbox[0].from_email, "[email protected]") self.assertEqual(mail.outbox[0].to[0], "[email protected]") self.assertEqual(mail.outbox[0].to[1], "[email protected]") self.assertEqual(mail.outbox[1].subject, "Second Test message") self.assertEqual(mail.outbox[1].body, "This is the second test email") self.assertEqual(mail.outbox[1].from_email, "[email protected]") self.assertEqual(mail.outbox[1].to[0], "[email protected]") self.assertEqual(mail.outbox[1].to[1], "[email protected]") def test_exception_following_nested_client_request(self): """ A nested test client request shouldn't clobber exception signals from the outer client request. """ with self.assertRaisesMessage(Exception, "exception message"): self.client.get("/nesting_exception_view/") def test_response_raises_multi_arg_exception(self): """A request may raise an exception with more than one required arg.""" with self.assertRaises(TwoArgException) as cm: self.client.get("/two_arg_exception/") self.assertEqual(cm.exception.args, ("one", "two")) def test_uploading_temp_file(self): with tempfile.TemporaryFile() as test_file: response = self.client.post("/upload_view/", data={"temp_file": test_file}) self.assertEqual(response.content, b"temp_file") def test_uploading_named_temp_file(self): with tempfile.NamedTemporaryFile() as test_file: response = self.client.post( "/upload_view/", data={"named_temp_file": test_file}, ) self.assertEqual(response.content, b"named_temp_file") @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], ROOT_URLCONF="test_client.urls", ) class CSRFEnabledClientTests(SimpleTestCase): def test_csrf_enabled_client(self): "A client can be instantiated with CSRF checks enabled" csrf_client = Client(enforce_csrf_checks=True) # The normal client allows the post response = self.client.post("/post_view/", {}) self.assertEqual(response.status_code, 200) # The CSRF-enabled client rejects it response = csrf_client.post("/post_view/", {}) self.assertEqual(response.status_code, 403) class CustomTestClient(Client): i_am_customized = "Yes" class CustomTestClientTest(SimpleTestCase): client_class = CustomTestClient def test_custom_test_client(self): """A test case can specify a custom class for self.client.""" self.assertIs(hasattr(self.client, "i_am_customized"), True) def _generic_view(request): return HttpResponse(status=200) @override_settings(ROOT_URLCONF="test_client.urls") class RequestFactoryTest(SimpleTestCase): """Tests for the request factory.""" # A mapping between names of HTTP/1.1 methods and their test views. http_methods_and_views = ( ("get", get_view), ("post", post_view), ("put", _generic_view), ("patch", _generic_view), ("delete", _generic_view), ("head", _generic_view), ("options", _generic_view), ("trace", trace_view), ) request_factory = RequestFactory() def test_request_factory(self): """The request factory implements all the HTTP/1.1 methods.""" for method_name, view in self.http_methods_and_views: method = getattr(self.request_factory, method_name) request = method("/somewhere/") response = view(request) self.assertEqual(response.status_code, 200) def test_get_request_from_factory(self): """ The request factory returns a templated response for a GET request. """ request = self.request_factory.get("/somewhere/") response = get_view(request) self.assertContains(response, "This is a test") def test_trace_request_from_factory(self): """The request factory returns an echo response for a TRACE request.""" url_path = "/somewhere/" request = self.request_factory.trace(url_path) response = trace_view(request) protocol = request.META["SERVER_PROTOCOL"] echoed_request_line = "TRACE {} {}".format(url_path, protocol) self.assertContains(response, echoed_request_line) @override_settings(ROOT_URLCONF="test_client.urls") class AsyncClientTest(TestCase): async def test_response_resolver_match(self): response = await self.async_client.get("/async_get_view/") self.assertTrue(hasattr(response, "resolver_match")) self.assertEqual(response.resolver_match.url_name, "async_get_view") @modify_settings( MIDDLEWARE={"prepend": "test_client.tests.async_middleware_urlconf"}, ) async def test_response_resolver_match_middleware_urlconf(self): response = await self.async_client.get("/middleware_urlconf_view/") self.assertEqual(response.resolver_match.url_name, "middleware_urlconf_view") async def test_follow_parameter_not_implemented(self): msg = "AsyncClient request methods do not accept the follow parameter." tests = ( "get", "post", "put", "patch", "delete", "head", "options", "trace", ) for method_name in tests: with self.subTest(method=method_name): method = getattr(self.async_client, method_name) with self.assertRaisesMessage(NotImplementedError, msg): await method("/redirect_view/", follow=True) async def test_get_data(self): response = await self.async_client.get("/get_view/", {"var": "val"}) self.assertContains(response, "This is a test. val is the value.") @override_settings(ROOT_URLCONF="test_client.urls") class AsyncRequestFactoryTest(SimpleTestCase): request_factory = AsyncRequestFactory() async def test_request_factory(self): tests = ( "get", "post", "put", "patch", "delete", "head", "options", "trace", ) for method_name in tests: with self.subTest(method=method_name): async def async_generic_view(request): if request.method.lower() != method_name: return HttpResponseNotAllowed(method_name) return HttpResponse(status=200) method = getattr(self.request_factory, method_name) request = method("/somewhere/") response = await async_generic_view(request) self.assertEqual(response.status_code, 200) async def test_request_factory_data(self): async def async_generic_view(request): return HttpResponse(status=200, content=request.body) request = self.request_factory.post( "/somewhere/", data={"example": "data"}, content_type="application/json", ) self.assertEqual(request.headers["content-length"], "19") self.assertEqual(request.headers["content-type"], "application/json") response = await async_generic_view(request) self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b'{"example": "data"}') def test_request_factory_sets_headers(self): request = self.request_factory.get( "/somewhere/", AUTHORIZATION="Bearer faketoken", X_ANOTHER_HEADER="some other value", ) self.assertEqual(request.headers["authorization"], "Bearer faketoken") self.assertIn("HTTP_AUTHORIZATION", request.META) self.assertEqual(request.headers["x-another-header"], "some other value") self.assertIn("HTTP_X_ANOTHER_HEADER", request.META) def test_request_factory_query_string(self): request = self.request_factory.get("/somewhere/", {"example": "data"}) self.assertNotIn("Query-String", request.headers) self.assertEqual(request.GET["example"], "data")
465468544b7e5a879d51e608541345c1e46f9165107a0ab2e0a5b2c383e832dc
from django.test import SimpleTestCase from django.test.client import FakePayload class FakePayloadTests(SimpleTestCase): def test_write_after_read(self): payload = FakePayload() payload.read() msg = "Unable to write a payload after it's been read" with self.assertRaisesMessage(ValueError, msg): payload.write(b"abc")
dbcf5339f6b6a0631bfe672598a5d1f4cc08bab210af172ddb8c8e56783d4aa4
import gzip from django.http import HttpRequest, HttpResponse, StreamingHttpResponse from django.test import SimpleTestCase from django.test.client import conditional_content_removal class ConditionalContentTests(SimpleTestCase): def test_conditional_content_removal(self): """ Content is removed from regular and streaming responses with a status_code of 100-199, 204, 304, or a method of "HEAD". """ req = HttpRequest() # Do nothing for 200 responses. res = HttpResponse("abc") conditional_content_removal(req, res) self.assertEqual(res.content, b"abc") res = StreamingHttpResponse(["abc"]) conditional_content_removal(req, res) self.assertEqual(b"".join(res), b"abc") # Strip content for some status codes. for status_code in (100, 150, 199, 204, 304): res = HttpResponse("abc", status=status_code) conditional_content_removal(req, res) self.assertEqual(res.content, b"") res = StreamingHttpResponse(["abc"], status=status_code) conditional_content_removal(req, res) self.assertEqual(b"".join(res), b"") # Issue #20472 abc = gzip.compress(b"abc") res = HttpResponse(abc, status=304) res["Content-Encoding"] = "gzip" conditional_content_removal(req, res) self.assertEqual(res.content, b"") res = StreamingHttpResponse([abc], status=304) res["Content-Encoding"] = "gzip" conditional_content_removal(req, res) self.assertEqual(b"".join(res), b"") # Strip content for HEAD requests. req.method = "HEAD" res = HttpResponse("abc") conditional_content_removal(req, res) self.assertEqual(res.content, b"") res = StreamingHttpResponse(["abc"]) conditional_content_removal(req, res) self.assertEqual(b"".join(res), b"")
0e45a7c44556ef921b417765050ac04668b56f6e0770dc386d0acda1871efada
from django.contrib.auth import views as auth_views from django.urls import path from django.views.generic import RedirectView from . import views urlpatterns = [ path("upload_view/", views.upload_view, name="upload_view"), path("get_view/", views.get_view, name="get_view"), path("post_view/", views.post_view), path("post_then_get_view/", views.post_then_get_view), path("put_view/", views.put_view), path("trace_view/", views.trace_view), path("header_view/", views.view_with_header), path("raw_post_view/", views.raw_post_view), path("redirect_view/", views.redirect_view), path("redirect_view_307/", views.method_saving_307_redirect_view), path( "redirect_view_307_query_string/", views.method_saving_307_redirect_query_string_view, ), path("redirect_view_308/", views.method_saving_308_redirect_view), path( "redirect_view_308_query_string/", views.method_saving_308_redirect_query_string_view, ), path("secure_view/", views.view_with_secure), path( "permanent_redirect_view/", RedirectView.as_view(url="/get_view/", permanent=True), ), path( "temporary_redirect_view/", RedirectView.as_view(url="/get_view/", permanent=False), ), path("http_redirect_view/", RedirectView.as_view(url="/secure_view/")), path( "https_redirect_view/", RedirectView.as_view(url="https://testserver/secure_view/"), ), path("double_redirect_view/", views.double_redirect_view), path("bad_view/", views.bad_view), path("form_view/", views.form_view), path("form_view_with_template/", views.form_view_with_template), path("formset_view/", views.formset_view), path("json_view/", views.json_view), path("login_protected_view/", views.login_protected_view), path("login_protected_method_view/", views.login_protected_method_view), path( "login_protected_view_custom_redirect/", views.login_protected_view_changed_redirect, ), path("permission_protected_view/", views.permission_protected_view), path( "permission_protected_view_exception/", views.permission_protected_view_exception, ), path("permission_protected_method_view/", views.permission_protected_method_view), path("session_view/", views.session_view), path("broken_view/", views.broken_view), path("mail_sending_view/", views.mail_sending_view), path("mass_mail_sending_view/", views.mass_mail_sending_view), path("nesting_exception_view/", views.nesting_exception_view), path("django_project_redirect/", views.django_project_redirect), path( "no_trailing_slash_external_redirect/", views.no_trailing_slash_external_redirect, ), path( "", views.index_view, name="index" ), # Target for no_trailing_slash_external_redirect/ with follow=True path("two_arg_exception/", views.two_arg_exception), path("accounts/", RedirectView.as_view(url="login/")), path("accounts/no_trailing_slash", RedirectView.as_view(url="login/")), path("accounts/login/", auth_views.LoginView.as_view(template_name="login.html")), path("accounts/logout/", auth_views.LogoutView.as_view()), # Async views. path("async_get_view/", views.async_get_view, name="async_get_view"), ]
bc7d4c47740c61bf6bb6580b1e9f0b69e6ce8daba25254669401890871acd030
import json from urllib.parse import urlencode from xml.dom.minidom import parseString from django.contrib.auth.decorators import login_required, permission_required from django.core import mail from django.core.exceptions import ValidationError from django.forms import fields from django.forms.forms import Form from django.forms.formsets import BaseFormSet, formset_factory from django.http import ( HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseNotFound, HttpResponseRedirect, ) from django.shortcuts import render from django.template import Context, Template from django.test import Client from django.utils.decorators import method_decorator def get_view(request): "A simple view that expects a GET request, and returns a rendered template" t = Template("This is a test. {{ var }} is the value.", name="GET Template") c = Context({"var": request.GET.get("var", 42)}) return HttpResponse(t.render(c)) async def async_get_view(request): return HttpResponse(b"GET content.") def trace_view(request): """ A simple view that expects a TRACE request and echoes its status line. TRACE requests should not have an entity; the view will return a 400 status response if it is present. """ if request.method.upper() != "TRACE": return HttpResponseNotAllowed("TRACE") elif request.body: return HttpResponseBadRequest("TRACE requests MUST NOT include an entity") else: protocol = request.META["SERVER_PROTOCOL"] t = Template( "{{ method }} {{ uri }} {{ version }}", name="TRACE Template", ) c = Context( { "method": request.method, "uri": request.path, "version": protocol, } ) return HttpResponse(t.render(c)) def put_view(request): if request.method == "PUT": t = Template("Data received: {{ data }} is the body.", name="PUT Template") c = Context( { "Content-Length": request.META["CONTENT_LENGTH"], "data": request.body.decode(), } ) else: t = Template("Viewing GET page.", name="Empty GET Template") c = Context() return HttpResponse(t.render(c)) def post_view(request): """A view that expects a POST, and returns a different template depending on whether any POST data is available """ if request.method == "POST": if request.POST: t = Template( "Data received: {{ data }} is the value.", name="POST Template" ) c = Context({"data": request.POST["value"]}) else: t = Template("Viewing POST page.", name="Empty POST Template") c = Context() else: t = Template("Viewing GET page.", name="Empty GET Template") c = Context() return HttpResponse(t.render(c)) def post_then_get_view(request): """ A view that expects a POST request, returns a redirect response to itself providing only a ?success=true querystring, the value of this querystring is then rendered upon GET. """ if request.method == "POST": return HttpResponseRedirect("?success=true") t = Template("The value of success is {{ value }}.", name="GET Template") c = Context({"value": request.GET.get("success", "false")}) return HttpResponse(t.render(c)) def json_view(request): """ A view that expects a request with the header 'application/json' and JSON data, which is deserialized and included in the context. """ if request.META.get("CONTENT_TYPE") != "application/json": return HttpResponse() t = Template("Viewing {} page. With data {{ data }}.".format(request.method)) data = json.loads(request.body.decode("utf-8")) c = Context({"data": data}) return HttpResponse(t.render(c)) def view_with_header(request): "A view that has a custom header" response = HttpResponse() response.headers["X-DJANGO-TEST"] = "Slartibartfast" return response def raw_post_view(request): """A view which expects raw XML to be posted and returns content extracted from the XML""" if request.method == "POST": root = parseString(request.body) first_book = root.firstChild.firstChild title, author = [n.firstChild.nodeValue for n in first_book.childNodes] t = Template("{{ title }} - {{ author }}", name="Book template") c = Context({"title": title, "author": author}) else: t = Template("GET request.", name="Book GET template") c = Context() return HttpResponse(t.render(c)) def redirect_view(request): "A view that redirects all requests to the GET view" if request.GET: query = "?" + urlencode(request.GET, True) else: query = "" return HttpResponseRedirect("/get_view/" + query) def method_saving_307_redirect_query_string_view(request): return HttpResponseRedirect("/post_view/?hello=world", status=307) def method_saving_308_redirect_query_string_view(request): return HttpResponseRedirect("/post_view/?hello=world", status=308) def _post_view_redirect(request, status_code): """Redirect to /post_view/ using the status code.""" redirect_to = request.GET.get("to", "/post_view/") return HttpResponseRedirect(redirect_to, status=status_code) def method_saving_307_redirect_view(request): return _post_view_redirect(request, 307) def method_saving_308_redirect_view(request): return _post_view_redirect(request, 308) def view_with_secure(request): "A view that indicates if the request was secure" response = HttpResponse() response.test_was_secure_request = request.is_secure() response.test_server_port = request.META.get("SERVER_PORT", 80) return response def double_redirect_view(request): "A view that redirects all requests to a redirection view" return HttpResponseRedirect("/permanent_redirect_view/") def bad_view(request): "A view that returns a 404 with some error content" return HttpResponseNotFound("Not found!. This page contains some MAGIC content") TestChoices = ( ("a", "First Choice"), ("b", "Second Choice"), ("c", "Third Choice"), ("d", "Fourth Choice"), ("e", "Fifth Choice"), ) class TestForm(Form): text = fields.CharField() email = fields.EmailField() value = fields.IntegerField() single = fields.ChoiceField(choices=TestChoices) multi = fields.MultipleChoiceField(choices=TestChoices) def clean(self): cleaned_data = self.cleaned_data if cleaned_data.get("text") == "Raise non-field error": raise ValidationError("Non-field error.") return cleaned_data def form_view(request): "A view that tests a simple form" if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): t = Template("Valid POST data.", name="Valid POST Template") c = Context() else: t = Template( "Invalid POST data. {{ form.errors }}", name="Invalid POST Template" ) c = Context({"form": form}) else: form = TestForm(request.GET) t = Template("Viewing base form. {{ form }}.", name="Form GET Template") c = Context({"form": form}) return HttpResponse(t.render(c)) def form_view_with_template(request): "A view that tests a simple form" if request.method == "POST": form = TestForm(request.POST) if form.is_valid(): message = "POST data OK" else: message = "POST data has errors" else: form = TestForm() message = "GET form page" return render( request, "form_view.html", { "form": form, "message": message, }, ) class BaseTestFormSet(BaseFormSet): def clean(self): """No two email addresses are the same.""" if any(self.errors): # Don't bother validating the formset unless each form is valid return emails = [] for form in self.forms: email = form.cleaned_data["email"] if email in emails: raise ValidationError( "Forms in a set must have distinct email addresses." ) emails.append(email) TestFormSet = formset_factory(TestForm, BaseTestFormSet) def formset_view(request): "A view that tests a simple formset" if request.method == "POST": formset = TestFormSet(request.POST) if formset.is_valid(): t = Template("Valid POST data.", name="Valid POST Template") c = Context() else: t = Template( "Invalid POST data. {{ my_formset.errors }}", name="Invalid POST Template", ) c = Context({"my_formset": formset}) else: formset = TestForm(request.GET) t = Template( "Viewing base formset. {{ my_formset }}.", name="Formset GET Template" ) c = Context({"my_formset": formset}) return HttpResponse(t.render(c)) @login_required def login_protected_view(request): "A simple view that is login protected." t = Template( "This is a login protected test. Username is {{ user.username }}.", name="Login Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c)) @login_required(redirect_field_name="redirect_to") def login_protected_view_changed_redirect(request): "A simple view that is login protected with a custom redirect field set" t = Template( "This is a login protected test. Username is {{ user.username }}.", name="Login Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c)) def _permission_protected_view(request): "A simple view that is permission protected." t = Template( "This is a permission protected test. " "Username is {{ user.username }}. " "Permissions are {{ user.get_all_permissions }}.", name="Permissions Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c)) permission_protected_view = permission_required("permission_not_granted")( _permission_protected_view ) permission_protected_view_exception = permission_required( "permission_not_granted", raise_exception=True )(_permission_protected_view) class _ViewManager: @method_decorator(login_required) def login_protected_view(self, request): t = Template( "This is a login protected test using a method. " "Username is {{ user.username }}.", name="Login Method Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c)) @method_decorator(permission_required("permission_not_granted")) def permission_protected_view(self, request): t = Template( "This is a permission protected test using a method. " "Username is {{ user.username }}. " "Permissions are {{ user.get_all_permissions }}.", name="Permissions Template", ) c = Context({"user": request.user}) return HttpResponse(t.render(c)) _view_manager = _ViewManager() login_protected_method_view = _view_manager.login_protected_view permission_protected_method_view = _view_manager.permission_protected_view def session_view(request): "A view that modifies the session" request.session["tobacconist"] = "hovercraft" t = Template( "This is a view that modifies the session.", name="Session Modifying View Template", ) c = Context() return HttpResponse(t.render(c)) def broken_view(request): """A view which just raises an exception, simulating a broken view.""" raise KeyError("Oops! Looks like you wrote some bad code.") def mail_sending_view(request): mail.EmailMessage( "Test message", "This is a test email", "[email protected]", ["[email protected]", "[email protected]"], ).send() return HttpResponse("Mail sent") def mass_mail_sending_view(request): m1 = mail.EmailMessage( "First Test message", "This is the first test email", "[email protected]", ["[email protected]", "[email protected]"], ) m2 = mail.EmailMessage( "Second Test message", "This is the second test email", "[email protected]", ["[email protected]", "[email protected]"], ) c = mail.get_connection() c.send_messages([m1, m2]) return HttpResponse("Mail sent") def nesting_exception_view(request): """ A view that uses a nested client to call another view and then raises an exception. """ client = Client() client.get("/get_view/") raise Exception("exception message") def django_project_redirect(request): return HttpResponseRedirect("https://www.djangoproject.com/") def no_trailing_slash_external_redirect(request): """ RFC 2616 3.2.2: A bare domain without any abs_path element should be treated as having the trailing `/`. Use https://testserver, rather than an external domain, in order to allow use of follow=True, triggering Client._handle_redirects(). """ return HttpResponseRedirect("https://testserver") def index_view(request): """Target for no_trailing_slash_external_redirect with follow=True.""" return HttpResponse("Hello world") def upload_view(request): """Prints keys of request.FILES to the response.""" return HttpResponse(", ".join(request.FILES)) class TwoArgException(Exception): def __init__(self, one, two): pass def two_arg_exception(request): raise TwoArgException("one", "two")
238785de711ba50a87d89914ffe04f3ee9e7e65e5e36ed93c2f338cadacd8664
from django.http import HttpResponse from django.urls import path def empty_response(request): return HttpResponse() urlpatterns = [ path("middleware_urlconf_view/", empty_response, name="middleware_urlconf_view"), ]
25798e740e7354b51ca32095793f910c35e382487ea9f144ffe5c84781a27c63
from django.core.exceptions import PermissionDenied from django.template.response import TemplateResponse from django.test import SimpleTestCase, modify_settings, override_settings from django.urls import path class MiddlewareAccessingContent: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) # Response.content should be available in the middleware even with a # TemplateResponse-based exception response. assert response.content return response def template_response_error_handler(request, exception=None): return TemplateResponse(request, "test_handler.html", status=403) def permission_denied_view(request): raise PermissionDenied urlpatterns = [ path("", permission_denied_view), ] handler403 = template_response_error_handler @override_settings(ROOT_URLCONF="handlers.tests_custom_error_handlers") @modify_settings( MIDDLEWARE={ "append": "handlers.tests_custom_error_handlers.MiddlewareAccessingContent" } ) class CustomErrorHandlerTests(SimpleTestCase): def test_handler_renders_template_response(self): """ BaseHandler should render TemplateResponse if necessary. """ response = self.client.get("/") self.assertContains(response, "Error handler content", status_code=403)
3639af04c5def3cd67e427f14236623e36dd43e19c159ffac6c9c47832cbec3e
from django.core.exceptions import ImproperlyConfigured from django.core.handlers.wsgi import WSGIHandler, WSGIRequest, get_script_name from django.core.signals import request_finished, request_started from django.db import close_old_connections, connection from django.test import ( RequestFactory, SimpleTestCase, TransactionTestCase, override_settings, ) class HandlerTests(SimpleTestCase): request_factory = RequestFactory() def setUp(self): request_started.disconnect(close_old_connections) def tearDown(self): request_started.connect(close_old_connections) def test_middleware_initialized(self): handler = WSGIHandler() self.assertIsNotNone(handler._middleware_chain) def test_bad_path_info(self): """ A non-UTF-8 path populates PATH_INFO with an URL-encoded path and produces a 404. """ environ = self.request_factory.get("/").environ environ["PATH_INFO"] = "\xed" handler = WSGIHandler() response = handler(environ, lambda *a, **k: None) # The path of the request will be encoded to '/%ED'. self.assertEqual(response.status_code, 404) def test_non_ascii_query_string(self): """ Non-ASCII query strings are properly decoded (#20530, #22996). """ environ = self.request_factory.get("/").environ raw_query_strings = [ b"want=caf%C3%A9", # This is the proper way to encode 'café' b"want=caf\xc3\xa9", # UA forgot to quote bytes b"want=caf%E9", # UA quoted, but not in UTF-8 # UA forgot to convert Latin-1 to UTF-8 and to quote (typical of # MSIE). b"want=caf\xe9", ] got = [] for raw_query_string in raw_query_strings: # Simulate http.server.BaseHTTPRequestHandler.parse_request # handling of raw request. environ["QUERY_STRING"] = str(raw_query_string, "iso-8859-1") request = WSGIRequest(environ) got.append(request.GET["want"]) # %E9 is converted to the Unicode replacement character by parse_qsl self.assertEqual(got, ["café", "café", "caf\ufffd", "café"]) def test_non_ascii_cookie(self): """Non-ASCII cookies set in JavaScript are properly decoded (#20557).""" environ = self.request_factory.get("/").environ raw_cookie = 'want="café"'.encode("utf-8").decode("iso-8859-1") environ["HTTP_COOKIE"] = raw_cookie request = WSGIRequest(environ) self.assertEqual(request.COOKIES["want"], "café") def test_invalid_unicode_cookie(self): """ Invalid cookie content should result in an absent cookie, but not in a crash while trying to decode it (#23638). """ environ = self.request_factory.get("/").environ environ["HTTP_COOKIE"] = "x=W\x03c(h]\x8e" request = WSGIRequest(environ) # We don't test COOKIES content, as the result might differ between # Python version because parsing invalid content became stricter in # latest versions. self.assertIsInstance(request.COOKIES, dict) @override_settings(ROOT_URLCONF="handlers.urls") def test_invalid_multipart_boundary(self): """ Invalid boundary string should produce a "Bad Request" response, not a server error (#23887). """ environ = self.request_factory.post("/malformed_post/").environ environ["CONTENT_TYPE"] = "multipart/form-data; boundary=WRONG\x07" handler = WSGIHandler() response = handler(environ, lambda *a, **k: None) # Expect "bad request" response self.assertEqual(response.status_code, 400) @override_settings(ROOT_URLCONF="handlers.urls", MIDDLEWARE=[]) class TransactionsPerRequestTests(TransactionTestCase): available_apps = [] def test_no_transaction(self): response = self.client.get("/in_transaction/") self.assertContains(response, "False") def test_auto_transaction(self): old_atomic_requests = connection.settings_dict["ATOMIC_REQUESTS"] try: connection.settings_dict["ATOMIC_REQUESTS"] = True response = self.client.get("/in_transaction/") finally: connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests self.assertContains(response, "True") async def test_auto_transaction_async_view(self): old_atomic_requests = connection.settings_dict["ATOMIC_REQUESTS"] try: connection.settings_dict["ATOMIC_REQUESTS"] = True msg = "You cannot use ATOMIC_REQUESTS with async views." with self.assertRaisesMessage(RuntimeError, msg): await self.async_client.get("/async_regular/") finally: connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests def test_no_auto_transaction(self): old_atomic_requests = connection.settings_dict["ATOMIC_REQUESTS"] try: connection.settings_dict["ATOMIC_REQUESTS"] = True response = self.client.get("/not_in_transaction/") finally: connection.settings_dict["ATOMIC_REQUESTS"] = old_atomic_requests self.assertContains(response, "False") @override_settings(ROOT_URLCONF="handlers.urls") class SignalsTests(SimpleTestCase): def setUp(self): self.signals = [] self.signaled_environ = None request_started.connect(self.register_started) request_finished.connect(self.register_finished) def tearDown(self): request_started.disconnect(self.register_started) request_finished.disconnect(self.register_finished) def register_started(self, **kwargs): self.signals.append("started") self.signaled_environ = kwargs.get("environ") def register_finished(self, **kwargs): self.signals.append("finished") def test_request_signals(self): response = self.client.get("/regular/") self.assertEqual(self.signals, ["started", "finished"]) self.assertEqual(response.content, b"regular content") self.assertEqual(self.signaled_environ, response.wsgi_request.environ) def test_request_signals_streaming_response(self): response = self.client.get("/streaming/") self.assertEqual(self.signals, ["started"]) self.assertEqual(b"".join(response.streaming_content), b"streaming content") self.assertEqual(self.signals, ["started", "finished"]) def empty_middleware(get_response): pass @override_settings(ROOT_URLCONF="handlers.urls") class HandlerRequestTests(SimpleTestCase): request_factory = RequestFactory() def test_async_view(self): """Calling an async view down the normal synchronous path.""" response = self.client.get("/async_regular/") self.assertEqual(response.status_code, 200) def test_suspiciousop_in_view_returns_400(self): response = self.client.get("/suspicious/") self.assertEqual(response.status_code, 400) def test_bad_request_in_view_returns_400(self): response = self.client.get("/bad_request/") self.assertEqual(response.status_code, 400) def test_invalid_urls(self): response = self.client.get("~%A9helloworld") self.assertEqual(response.status_code, 404) self.assertEqual(response.context["request_path"], "/~%25A9helloworld") response = self.client.get("d%aao%aaw%aan%aal%aao%aaa%aad%aa/") self.assertEqual( response.context["request_path"], "/d%25AAo%25AAw%25AAn%25AAl%25AAo%25AAa%25AAd%25AA", ) response = self.client.get("/%E2%99%E2%99%A5/") self.assertEqual(response.context["request_path"], "/%25E2%2599%E2%99%A5/") response = self.client.get("/%E2%98%8E%E2%A9%E2%99%A5/") self.assertEqual( response.context["request_path"], "/%E2%98%8E%25E2%25A9%E2%99%A5/" ) def test_environ_path_info_type(self): environ = self.request_factory.get("/%E2%A8%87%87%A5%E2%A8%A0").environ self.assertIsInstance(environ["PATH_INFO"], str) def test_handle_accepts_httpstatus_enum_value(self): def start_response(status, headers): start_response.status = status environ = self.request_factory.get("/httpstatus_enum/").environ WSGIHandler()(environ, start_response) self.assertEqual(start_response.status, "200 OK") @override_settings(MIDDLEWARE=["handlers.tests.empty_middleware"]) def test_middleware_returns_none(self): msg = "Middleware factory handlers.tests.empty_middleware returned None." with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get("/") def test_no_response(self): msg = ( "The view %s didn't return an HttpResponse object. It returned None " "instead." ) tests = ( ("/no_response_fbv/", "handlers.views.no_response"), ("/no_response_cbv/", "handlers.views.NoResponse.__call__"), ) for url, view in tests: with self.subTest(url=url), self.assertRaisesMessage( ValueError, msg % view ): self.client.get(url) class ScriptNameTests(SimpleTestCase): def test_get_script_name(self): # Regression test for #23173 # Test first without PATH_INFO script_name = get_script_name({"SCRIPT_URL": "/foobar/"}) self.assertEqual(script_name, "/foobar/") script_name = get_script_name({"SCRIPT_URL": "/foobar/", "PATH_INFO": "/"}) self.assertEqual(script_name, "/foobar") def test_get_script_name_double_slashes(self): """ WSGI squashes multiple successive slashes in PATH_INFO, get_script_name should take that into account when forming SCRIPT_NAME (#17133). """ script_name = get_script_name( { "SCRIPT_URL": "/mst/milestones//accounts/login//help", "PATH_INFO": "/milestones/accounts/login/help", } ) self.assertEqual(script_name, "/mst") @override_settings(ROOT_URLCONF="handlers.urls") class AsyncHandlerRequestTests(SimpleTestCase): """Async variants of the normal handler request tests.""" async def test_sync_view(self): """Calling a sync view down the asynchronous path.""" response = await self.async_client.get("/regular/") self.assertEqual(response.status_code, 200) async def test_async_view(self): """Calling an async view down the asynchronous path.""" response = await self.async_client.get("/async_regular/") self.assertEqual(response.status_code, 200) async def test_suspiciousop_in_view_returns_400(self): response = await self.async_client.get("/suspicious/") self.assertEqual(response.status_code, 400) async def test_bad_request_in_view_returns_400(self): response = await self.async_client.get("/bad_request/") self.assertEqual(response.status_code, 400) async def test_no_response(self): msg = ( "The view handlers.views.no_response didn't return an " "HttpResponse object. It returned None instead." ) with self.assertRaisesMessage(ValueError, msg): await self.async_client.get("/no_response_fbv/") async def test_unawaited_response(self): msg = ( "The view handlers.views.CoroutineClearingView.__call__ didn't" " return an HttpResponse object. It returned an unawaited" " coroutine instead. You may need to add an 'await'" " into your view." ) with self.assertRaisesMessage(ValueError, msg): await self.async_client.get("/unawaited/")
811d15e9f80576f6b8e6a7a93ea0843f72528fe576653e56a697d98949fadafe
from django.core.handlers.wsgi import WSGIHandler from django.test import SimpleTestCase, override_settings from django.test.client import FakePayload class ExceptionHandlerTests(SimpleTestCase): def get_suspicious_environ(self): payload = FakePayload("a=1&a=2&a=3\r\n") return { "REQUEST_METHOD": "POST", "CONTENT_TYPE": "application/x-www-form-urlencoded", "CONTENT_LENGTH": len(payload), "wsgi.input": payload, "SERVER_NAME": "test", "SERVER_PORT": "8000", } @override_settings(DATA_UPLOAD_MAX_MEMORY_SIZE=12) def test_data_upload_max_memory_size_exceeded(self): response = WSGIHandler()(self.get_suspicious_environ(), lambda *a, **k: None) self.assertEqual(response.status_code, 400) @override_settings(DATA_UPLOAD_MAX_NUMBER_FIELDS=2) def test_data_upload_max_number_fields_exceeded(self): response = WSGIHandler()(self.get_suspicious_environ(), lambda *a, **k: None) self.assertEqual(response.status_code, 400)
d2acc9954cf717321aa67f5124d2435a38a3d1df4f41cc042b082bd4623c6acc
from django.urls import path from . import views urlpatterns = [ path("regular/", views.regular), path("async_regular/", views.async_regular), path("no_response_fbv/", views.no_response), path("no_response_cbv/", views.NoResponse()), path("streaming/", views.streaming), path("in_transaction/", views.in_transaction), path("not_in_transaction/", views.not_in_transaction), path("bad_request/", views.bad_request), path("suspicious/", views.suspicious), path("malformed_post/", views.malformed_post), path("httpstatus_enum/", views.httpstatus_enum), path("unawaited/", views.async_unawaited), ]
3c41fe8c5fae3c8cf09ef7bd8998b4ff174418ffc53c5dc8978d697910cce6f2
import asyncio from http import HTTPStatus from django.core.exceptions import BadRequest, SuspiciousOperation from django.db import connection, transaction from django.http import HttpResponse, StreamingHttpResponse from django.views.decorators.csrf import csrf_exempt def regular(request): return HttpResponse(b"regular content") def no_response(request): pass class NoResponse: def __call__(self, request): pass def streaming(request): return StreamingHttpResponse([b"streaming", b" ", b"content"]) def in_transaction(request): return HttpResponse(str(connection.in_atomic_block)) @transaction.non_atomic_requests def not_in_transaction(request): return HttpResponse(str(connection.in_atomic_block)) def bad_request(request): raise BadRequest() def suspicious(request): raise SuspiciousOperation("dubious") @csrf_exempt def malformed_post(request): request.POST return HttpResponse() def httpstatus_enum(request): return HttpResponse(status=HTTPStatus.OK) async def async_regular(request): return HttpResponse(b"regular content") class CoroutineClearingView: def __call__(self, request): """Return an unawaited coroutine (common error for async views).""" # Store coroutine to suppress 'unawaited' warning message self._unawaited_coroutine = asyncio.sleep(0) return self._unawaited_coroutine def __del__(self): try: self._unawaited_coroutine.close() except AttributeError: # View was never called. pass async_unawaited = CoroutineClearingView()
63a1e3086e76293bf0ac3ab699422f735a7e95ba4a4cb03d905c342122633b16
from django.core.exceptions import ImproperlyConfigured from django.core.servers.basehttp import get_internal_wsgi_application from django.core.signals import request_started from django.core.wsgi import get_wsgi_application from django.db import close_old_connections from django.http import FileResponse from django.test import SimpleTestCase, override_settings from django.test.client import RequestFactory @override_settings(ROOT_URLCONF="wsgi.urls") class WSGITest(SimpleTestCase): request_factory = RequestFactory() def setUp(self): request_started.disconnect(close_old_connections) def tearDown(self): request_started.connect(close_old_connections) def test_get_wsgi_application(self): """ get_wsgi_application() returns a functioning WSGI callable. """ application = get_wsgi_application() environ = self.request_factory._base_environ( PATH_INFO="/", CONTENT_TYPE="text/html; charset=utf-8", REQUEST_METHOD="GET" ) response_data = {} def start_response(status, headers): response_data["status"] = status response_data["headers"] = headers response = application(environ, start_response) self.assertEqual(response_data["status"], "200 OK") self.assertEqual( set(response_data["headers"]), {("Content-Length", "12"), ("Content-Type", "text/html; charset=utf-8")}, ) self.assertIn( bytes(response), [ b"Content-Length: 12\r\nContent-Type: text/html; " b"charset=utf-8\r\n\r\nHello World!", b"Content-Type: text/html; " b"charset=utf-8\r\nContent-Length: 12\r\n\r\nHello World!", ], ) def test_file_wrapper(self): """ FileResponse uses wsgi.file_wrapper. """ class FileWrapper: def __init__(self, filelike, block_size=None): self.block_size = block_size filelike.close() application = get_wsgi_application() environ = self.request_factory._base_environ( PATH_INFO="/file/", REQUEST_METHOD="GET", **{"wsgi.file_wrapper": FileWrapper}, ) response_data = {} def start_response(status, headers): response_data["status"] = status response_data["headers"] = headers response = application(environ, start_response) self.assertEqual(response_data["status"], "200 OK") self.assertIsInstance(response, FileWrapper) self.assertEqual(response.block_size, FileResponse.block_size) class GetInternalWSGIApplicationTest(SimpleTestCase): @override_settings(WSGI_APPLICATION="wsgi.wsgi.application") def test_success(self): """ If ``WSGI_APPLICATION`` is a dotted path, the referenced object is returned. """ app = get_internal_wsgi_application() from .wsgi import application self.assertIs(app, application) @override_settings(WSGI_APPLICATION=None) def test_default(self): """ If ``WSGI_APPLICATION`` is ``None``, the return value of ``get_wsgi_application`` is returned. """ # Mock out get_wsgi_application so we know its return value is used fake_app = object() def mock_get_wsgi_app(): return fake_app from django.core.servers import basehttp _orig_get_wsgi_app = basehttp.get_wsgi_application basehttp.get_wsgi_application = mock_get_wsgi_app try: app = get_internal_wsgi_application() self.assertIs(app, fake_app) finally: basehttp.get_wsgi_application = _orig_get_wsgi_app @override_settings(WSGI_APPLICATION="wsgi.noexist.app") def test_bad_module(self): msg = "WSGI application 'wsgi.noexist.app' could not be loaded; Error importing" with self.assertRaisesMessage(ImproperlyConfigured, msg): get_internal_wsgi_application() @override_settings(WSGI_APPLICATION="wsgi.wsgi.noexist") def test_bad_name(self): msg = ( "WSGI application 'wsgi.wsgi.noexist' could not be loaded; Error importing" ) with self.assertRaisesMessage(ImproperlyConfigured, msg): get_internal_wsgi_application()
921d6c37d98ddcc1d7b4d7ba931db5a5b061f3f5747cc475e0283545f2a5bc46
from django.http import FileResponse, HttpResponse from django.urls import path def helloworld(request): return HttpResponse("Hello World!") urlpatterns = [ path("", helloworld), path("file/", lambda x: FileResponse(open(__file__, "rb"))), ]
92bf41f9d1a70cdb72128a0b1e5c1ba25cdceb53d7a0c1bcd5d9c846a301457c
from django.db import connection from django.db.backends.ddl_references import ( Columns, Expressions, ForeignKeyName, IndexName, Statement, Table, ) from django.db.models import ExpressionList, F from django.db.models.functions import Upper from django.db.models.indexes import IndexExpression from django.db.models.sql import Query from django.test import SimpleTestCase, TransactionTestCase from .models import Person class TableTests(SimpleTestCase): def setUp(self): self.reference = Table("table", lambda table: table.upper()) def test_references_table(self): self.assertIs(self.reference.references_table("table"), True) self.assertIs(self.reference.references_table("other"), False) def test_rename_table_references(self): self.reference.rename_table_references("other", "table") self.assertIs(self.reference.references_table("table"), True) self.assertIs(self.reference.references_table("other"), False) self.reference.rename_table_references("table", "other") self.assertIs(self.reference.references_table("table"), False) self.assertIs(self.reference.references_table("other"), True) def test_repr(self): self.assertEqual(repr(self.reference), "<Table 'TABLE'>") def test_str(self): self.assertEqual(str(self.reference), "TABLE") class ColumnsTests(TableTests): def setUp(self): self.reference = Columns( "table", ["first_column", "second_column"], lambda column: column.upper() ) def test_references_column(self): self.assertIs(self.reference.references_column("other", "first_column"), False) self.assertIs(self.reference.references_column("table", "third_column"), False) self.assertIs(self.reference.references_column("table", "first_column"), True) def test_rename_column_references(self): self.reference.rename_column_references("other", "first_column", "third_column") self.assertIs(self.reference.references_column("table", "first_column"), True) self.assertIs(self.reference.references_column("table", "third_column"), False) self.assertIs(self.reference.references_column("other", "third_column"), False) self.reference.rename_column_references("table", "third_column", "first_column") self.assertIs(self.reference.references_column("table", "first_column"), True) self.assertIs(self.reference.references_column("table", "third_column"), False) self.reference.rename_column_references("table", "first_column", "third_column") self.assertIs(self.reference.references_column("table", "first_column"), False) self.assertIs(self.reference.references_column("table", "third_column"), True) def test_repr(self): self.assertEqual( repr(self.reference), "<Columns 'FIRST_COLUMN, SECOND_COLUMN'>" ) def test_str(self): self.assertEqual(str(self.reference), "FIRST_COLUMN, SECOND_COLUMN") class IndexNameTests(ColumnsTests): def setUp(self): def create_index_name(table_name, column_names, suffix): return ", ".join( "%s_%s_%s" % (table_name, column_name, suffix) for column_name in column_names ) self.reference = IndexName( "table", ["first_column", "second_column"], "suffix", create_index_name ) def test_repr(self): self.assertEqual( repr(self.reference), "<IndexName 'table_first_column_suffix, table_second_column_suffix'>", ) def test_str(self): self.assertEqual( str(self.reference), "table_first_column_suffix, table_second_column_suffix" ) class ForeignKeyNameTests(IndexNameTests): def setUp(self): def create_foreign_key_name(table_name, column_names, suffix): return ", ".join( "%s_%s_%s" % (table_name, column_name, suffix) for column_name in column_names ) self.reference = ForeignKeyName( "table", ["first_column", "second_column"], "to_table", ["to_first_column", "to_second_column"], "%(to_table)s_%(to_column)s_fk", create_foreign_key_name, ) def test_references_table(self): super().test_references_table() self.assertIs(self.reference.references_table("to_table"), True) def test_references_column(self): super().test_references_column() self.assertIs( self.reference.references_column("to_table", "second_column"), False ) self.assertIs( self.reference.references_column("to_table", "to_second_column"), True ) def test_rename_table_references(self): super().test_rename_table_references() self.reference.rename_table_references("to_table", "other_to_table") self.assertIs(self.reference.references_table("other_to_table"), True) self.assertIs(self.reference.references_table("to_table"), False) def test_rename_column_references(self): super().test_rename_column_references() self.reference.rename_column_references( "to_table", "second_column", "third_column" ) self.assertIs(self.reference.references_column("table", "second_column"), True) self.assertIs( self.reference.references_column("to_table", "to_second_column"), True ) self.reference.rename_column_references( "to_table", "to_first_column", "to_third_column" ) self.assertIs( self.reference.references_column("to_table", "to_first_column"), False ) self.assertIs( self.reference.references_column("to_table", "to_third_column"), True ) def test_repr(self): self.assertEqual( repr(self.reference), "<ForeignKeyName 'table_first_column_to_table_to_first_column_fk, " "table_second_column_to_table_to_first_column_fk'>", ) def test_str(self): self.assertEqual( str(self.reference), "table_first_column_to_table_to_first_column_fk, " "table_second_column_to_table_to_first_column_fk", ) class MockReference: def __init__(self, representation, referenced_tables, referenced_columns): self.representation = representation self.referenced_tables = referenced_tables self.referenced_columns = referenced_columns def references_table(self, table): return table in self.referenced_tables def references_column(self, table, column): return (table, column) in self.referenced_columns def rename_table_references(self, old_table, new_table): if old_table in self.referenced_tables: self.referenced_tables.remove(old_table) self.referenced_tables.add(new_table) def rename_column_references(self, table, old_column, new_column): column = (table, old_column) if column in self.referenced_columns: self.referenced_columns.remove(column) self.referenced_columns.add((table, new_column)) def __str__(self): return self.representation class StatementTests(SimpleTestCase): def test_references_table(self): statement = Statement( "", reference=MockReference("", {"table"}, {}), non_reference="" ) self.assertIs(statement.references_table("table"), True) self.assertIs(statement.references_table("other"), False) def test_references_column(self): statement = Statement( "", reference=MockReference("", {}, {("table", "column")}), non_reference="" ) self.assertIs(statement.references_column("table", "column"), True) self.assertIs(statement.references_column("other", "column"), False) def test_rename_table_references(self): reference = MockReference("", {"table"}, {}) statement = Statement("", reference=reference, non_reference="") statement.rename_table_references("table", "other") self.assertEqual(reference.referenced_tables, {"other"}) def test_rename_column_references(self): reference = MockReference("", {}, {("table", "column")}) statement = Statement("", reference=reference, non_reference="") statement.rename_column_references("table", "column", "other") self.assertEqual(reference.referenced_columns, {("table", "other")}) def test_repr(self): reference = MockReference("reference", {}, {}) statement = Statement( "%(reference)s - %(non_reference)s", reference=reference, non_reference="non_reference", ) self.assertEqual(repr(statement), "<Statement 'reference - non_reference'>") def test_str(self): reference = MockReference("reference", {}, {}) statement = Statement( "%(reference)s - %(non_reference)s", reference=reference, non_reference="non_reference", ) self.assertEqual(str(statement), "reference - non_reference") class ExpressionsTests(TransactionTestCase): available_apps = [] def setUp(self): compiler = Person.objects.all().query.get_compiler(connection.alias) self.editor = connection.schema_editor() self.expressions = Expressions( table=Person._meta.db_table, expressions=ExpressionList( IndexExpression(F("first_name")), IndexExpression(F("last_name").desc()), IndexExpression(Upper("last_name")), ).resolve_expression(compiler.query), compiler=compiler, quote_value=self.editor.quote_value, ) def test_references_table(self): self.assertIs(self.expressions.references_table(Person._meta.db_table), True) self.assertIs(self.expressions.references_table("other"), False) def test_references_column(self): table = Person._meta.db_table self.assertIs(self.expressions.references_column(table, "first_name"), True) self.assertIs(self.expressions.references_column(table, "last_name"), True) self.assertIs(self.expressions.references_column(table, "other"), False) def test_rename_table_references(self): table = Person._meta.db_table self.expressions.rename_table_references(table, "other") self.assertIs(self.expressions.references_table(table), False) self.assertIs(self.expressions.references_table("other"), True) self.assertIn( "%s.%s" % ( self.editor.quote_name("other"), self.editor.quote_name("first_name"), ), str(self.expressions), ) def test_rename_table_references_without_alias(self): compiler = Query(Person, alias_cols=False).get_compiler(connection=connection) table = Person._meta.db_table expressions = Expressions( table=table, expressions=ExpressionList( IndexExpression(Upper("last_name")), IndexExpression(F("first_name")), ).resolve_expression(compiler.query), compiler=compiler, quote_value=self.editor.quote_value, ) expressions.rename_table_references(table, "other") self.assertIs(expressions.references_table(table), False) self.assertIs(expressions.references_table("other"), True) expected_str = "(UPPER(%s)), %s" % ( self.editor.quote_name("last_name"), self.editor.quote_name("first_name"), ) self.assertEqual(str(expressions), expected_str) def test_rename_column_references(self): table = Person._meta.db_table self.expressions.rename_column_references(table, "first_name", "other") self.assertIs(self.expressions.references_column(table, "other"), True) self.assertIs(self.expressions.references_column(table, "first_name"), False) self.assertIn( "%s.%s" % (self.editor.quote_name(table), self.editor.quote_name("other")), str(self.expressions), ) def test_str(self): table_name = self.editor.quote_name(Person._meta.db_table) expected_str = "%s.%s, %s.%s DESC, (UPPER(%s.%s))" % ( table_name, self.editor.quote_name("first_name"), table_name, self.editor.quote_name("last_name"), table_name, self.editor.quote_name("last_name"), ) self.assertEqual(str(self.expressions), expected_str)
dde677423ab49b8b8ec70bafa4b2d74501385d2c9883648b163b5c21f2374642
"""Tests for django.db.backends.utils""" from decimal import Decimal, Rounded from django.db import NotSupportedError, connection from django.db.backends.utils import ( format_number, split_identifier, split_tzname_delta, truncate_name, ) from django.test import ( SimpleTestCase, TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature, ) class TestUtils(SimpleTestCase): def test_truncate_name(self): self.assertEqual(truncate_name("some_table", 10), "some_table") self.assertEqual(truncate_name("some_long_table", 10), "some_la38a") self.assertEqual(truncate_name("some_long_table", 10, 3), "some_loa38") self.assertEqual(truncate_name("some_long_table"), "some_long_table") # "user"."table" syntax self.assertEqual( truncate_name('username"."some_table', 10), 'username"."some_table' ) self.assertEqual( truncate_name('username"."some_long_table', 10), 'username"."some_la38a' ) self.assertEqual( truncate_name('username"."some_long_table', 10, 3), 'username"."some_loa38' ) def test_split_identifier(self): self.assertEqual(split_identifier("some_table"), ("", "some_table")) self.assertEqual(split_identifier('"some_table"'), ("", "some_table")) self.assertEqual( split_identifier('namespace"."some_table'), ("namespace", "some_table") ) self.assertEqual( split_identifier('"namespace"."some_table"'), ("namespace", "some_table") ) def test_format_number(self): def equal(value, max_d, places, result): self.assertEqual(format_number(Decimal(value), max_d, places), result) equal("0", 12, 3, "0.000") equal("0", 12, 8, "0.00000000") equal("1", 12, 9, "1.000000000") equal("0.00000000", 12, 8, "0.00000000") equal("0.000000004", 12, 8, "0.00000000") equal("0.000000008", 12, 8, "0.00000001") equal("0.000000000000000000999", 10, 8, "0.00000000") equal("0.1234567890", 12, 10, "0.1234567890") equal("0.1234567890", 12, 9, "0.123456789") equal("0.1234567890", 12, 8, "0.12345679") equal("0.1234567890", 12, 5, "0.12346") equal("0.1234567890", 12, 3, "0.123") equal("0.1234567890", 12, 1, "0.1") equal("0.1234567890", 12, 0, "0") equal("0.1234567890", None, 0, "0") equal("1234567890.1234567890", None, 0, "1234567890") equal("1234567890.1234567890", None, 2, "1234567890.12") equal("0.1234", 5, None, "0.1234") equal("123.12", 5, None, "123.12") with self.assertRaises(Rounded): equal("0.1234567890", 5, None, "0.12346") with self.assertRaises(Rounded): equal("1234567890.1234", 5, None, "1234600000") def test_split_tzname_delta(self): tests = [ ("Asia/Ust+Nera", ("Asia/Ust+Nera", None, None)), ("Asia/Ust-Nera", ("Asia/Ust-Nera", None, None)), ("Asia/Ust+Nera-02:00", ("Asia/Ust+Nera", "-", "02:00")), ("Asia/Ust-Nera+05:00", ("Asia/Ust-Nera", "+", "05:00")), ("America/Coral_Harbour-01:00", ("America/Coral_Harbour", "-", "01:00")), ("America/Coral_Harbour+02:30", ("America/Coral_Harbour", "+", "02:30")), ("UTC+15:00", ("UTC", "+", "15:00")), ("UTC-04:43", ("UTC", "-", "04:43")), ("UTC", ("UTC", None, None)), ("UTC+1", ("UTC+1", None, None)), ] for tzname, expected in tests: with self.subTest(tzname=tzname): self.assertEqual(split_tzname_delta(tzname), expected) class CursorWrapperTests(TransactionTestCase): available_apps = [] def _test_procedure(self, procedure_sql, params, param_types, kparams=None): with connection.cursor() as cursor: cursor.execute(procedure_sql) # Use a new cursor because in MySQL a procedure can't be used in the # same cursor in which it was created. with connection.cursor() as cursor: cursor.callproc("test_procedure", params, kparams) with connection.schema_editor() as editor: editor.remove_procedure("test_procedure", param_types) @skipUnlessDBFeature("create_test_procedure_without_params_sql") def test_callproc_without_params(self): self._test_procedure( connection.features.create_test_procedure_without_params_sql, [], [] ) @skipUnlessDBFeature("create_test_procedure_with_int_param_sql") def test_callproc_with_int_params(self): self._test_procedure( connection.features.create_test_procedure_with_int_param_sql, [1], ["INTEGER"], ) @skipUnlessDBFeature( "create_test_procedure_with_int_param_sql", "supports_callproc_kwargs" ) def test_callproc_kparams(self): self._test_procedure( connection.features.create_test_procedure_with_int_param_sql, [], ["INTEGER"], {"P_I": 1}, ) @skipIfDBFeature("supports_callproc_kwargs") def test_unsupported_callproc_kparams_raises_error(self): msg = ( "Keyword parameters for callproc are not supported on this database " "backend." ) with self.assertRaisesMessage(NotSupportedError, msg): with connection.cursor() as cursor: cursor.callproc("test_procedure", [], {"P_I": 1})
4fa88d31cf578f6768a1e9eaff9592468bf75e6de6af31b5a086e3f34a1a20a2
"""Tests related to django.db.backends that haven't been organized.""" import datetime import threading import unittest import warnings from unittest import mock from django.core.management.color import no_style from django.db import ( DEFAULT_DB_ALIAS, DatabaseError, IntegrityError, connection, connections, reset_queries, transaction, ) from django.db.backends.base.base import BaseDatabaseWrapper from django.db.backends.signals import connection_created from django.db.backends.utils import CursorWrapper from django.db.models.sql.constants import CURSOR from django.test import ( TestCase, TransactionTestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from .models import ( Article, Object, ObjectReference, Person, Post, RawData, Reporter, ReporterProxy, SchoolClass, SQLKeywordsModel, Square, VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ, ) class DateQuotingTest(TestCase): def test_django_date_trunc(self): """ Test the custom ``django_date_trunc method``, in particular against fields which clash with strings passed to it (e.g. 'year') (#12818). """ updated = datetime.datetime(2010, 2, 20) SchoolClass.objects.create(year=2009, last_updated=updated) years = SchoolClass.objects.dates("last_updated", "year") self.assertEqual(list(years), [datetime.date(2010, 1, 1)]) def test_django_date_extract(self): """ Test the custom ``django_date_extract method``, in particular against fields which clash with strings passed to it (e.g. 'day') (#12818). """ updated = datetime.datetime(2010, 2, 20) SchoolClass.objects.create(year=2009, last_updated=updated) classes = SchoolClass.objects.filter(last_updated__day=20) self.assertEqual(len(classes), 1) @override_settings(DEBUG=True) class LastExecutedQueryTest(TestCase): def test_last_executed_query_without_previous_query(self): """ last_executed_query should not raise an exception even if no previous query has been run. """ with connection.cursor() as cursor: connection.ops.last_executed_query(cursor, "", ()) def test_debug_sql(self): list(Reporter.objects.filter(first_name="test")) sql = connection.queries[-1]["sql"].lower() self.assertIn("select", sql) self.assertIn(Reporter._meta.db_table, sql) def test_query_encoding(self): """last_executed_query() returns a string.""" data = RawData.objects.filter(raw_data=b"\x00\x46 \xFE").extra( select={"föö": 1} ) sql, params = data.query.sql_with_params() with data.query.get_compiler("default").execute_sql(CURSOR) as cursor: last_sql = cursor.db.ops.last_executed_query(cursor, sql, params) self.assertIsInstance(last_sql, str) def test_last_executed_query(self): # last_executed_query() interpolate all parameters, in most cases it is # not equal to QuerySet.query. for qs in ( Article.objects.filter(pk=1), Article.objects.filter(pk__in=(1, 2), reporter__pk=3), Article.objects.filter( pk=1, reporter__pk=9, ).exclude(reporter__pk__in=[2, 1]), ): sql, params = qs.query.sql_with_params() with qs.query.get_compiler(DEFAULT_DB_ALIAS).execute_sql(CURSOR) as cursor: self.assertEqual( cursor.db.ops.last_executed_query(cursor, sql, params), str(qs.query), ) @skipUnlessDBFeature("supports_paramstyle_pyformat") def test_last_executed_query_dict(self): square_opts = Square._meta sql = "INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)" % ( connection.introspection.identifier_converter(square_opts.db_table), connection.ops.quote_name(square_opts.get_field("root").column), connection.ops.quote_name(square_opts.get_field("square").column), ) with connection.cursor() as cursor: params = {"root": 2, "square": 4} cursor.execute(sql, params) self.assertEqual( cursor.db.ops.last_executed_query(cursor, sql, params), sql % params, ) class ParameterHandlingTest(TestCase): def test_bad_parameter_count(self): """ An executemany call with too many/not enough parameters will raise an exception. """ with connection.cursor() as cursor: query = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % ( connection.introspection.identifier_converter("backends_square"), connection.ops.quote_name("root"), connection.ops.quote_name("square"), ) with self.assertRaises(Exception): cursor.executemany(query, [(1, 2, 3)]) with self.assertRaises(Exception): cursor.executemany(query, [(1,)]) class LongNameTest(TransactionTestCase): """Long primary keys and model names can result in a sequence name that exceeds the database limits, which will result in truncation on certain databases (e.g., Postgres). The backend needs to use the correct sequence name in last_insert_id and other places, so check it is. Refs #8901. """ available_apps = ["backends"] def test_sequence_name_length_limits_create(self): """Creation of model with long name and long pk name doesn't error.""" VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() def test_sequence_name_length_limits_m2m(self): """ An m2m save of a model with a long name and a long m2m field name doesn't error (#8901). """ obj = ( VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ.objects.create() ) rel_obj = Person.objects.create(first_name="Django", last_name="Reinhardt") obj.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.add(rel_obj) def test_sequence_name_length_limits_flush(self): """ Sequence resetting as part of a flush with model with long name and long pk name doesn't error (#8901). """ # A full flush is expensive to the full test, so we dig into the # internals to generate the likely offending SQL and run it manually # Some convenience aliases VLM = VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ VLM_m2m = ( VLM.m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz.through ) tables = [ VLM._meta.db_table, VLM_m2m._meta.db_table, ] sql_list = connection.ops.sql_flush(no_style(), tables, reset_sequences=True) connection.ops.execute_sql_flush(sql_list) class SequenceResetTest(TestCase): def test_generic_relation(self): "Sequence names are correct when resetting generic relations (Ref #13941)" # Create an object with a manually specified PK Post.objects.create(id=10, name="1st post", text="hello world") # Reset the sequences for the database commands = connections[DEFAULT_DB_ALIAS].ops.sequence_reset_sql( no_style(), [Post] ) with connection.cursor() as cursor: for sql in commands: cursor.execute(sql) # If we create a new object now, it should have a PK greater # than the PK we specified manually. obj = Post.objects.create(name="New post", text="goodbye world") self.assertGreater(obj.pk, 10) # This test needs to run outside of a transaction, otherwise closing the # connection would implicitly rollback and cause problems during teardown. class ConnectionCreatedSignalTest(TransactionTestCase): available_apps = [] # Unfortunately with sqlite3 the in-memory test database cannot be closed, # and so it cannot be re-opened during testing. @skipUnlessDBFeature("test_db_allows_multiple_connections") def test_signal(self): data = {} def receiver(sender, connection, **kwargs): data["connection"] = connection connection_created.connect(receiver) connection.close() with connection.cursor(): pass self.assertIs(data["connection"].connection, connection.connection) connection_created.disconnect(receiver) data.clear() with connection.cursor(): pass self.assertEqual(data, {}) class EscapingChecks(TestCase): """ All tests in this test case are also run with settings.DEBUG=True in EscapingChecksDebug test case, to also test CursorDebugWrapper. """ bare_select_suffix = connection.features.bare_select_suffix def test_paramless_no_escaping(self): with connection.cursor() as cursor: cursor.execute("SELECT '%s'" + self.bare_select_suffix) self.assertEqual(cursor.fetchall()[0][0], "%s") def test_parameter_escaping(self): with connection.cursor() as cursor: cursor.execute("SELECT '%%', %s" + self.bare_select_suffix, ("%d",)) self.assertEqual(cursor.fetchall()[0], ("%", "%d")) @override_settings(DEBUG=True) class EscapingChecksDebug(EscapingChecks): pass class BackendTestCase(TransactionTestCase): available_apps = ["backends"] def create_squares_with_executemany(self, args): self.create_squares(args, "format", True) def create_squares(self, args, paramstyle, multiple): opts = Square._meta tbl = connection.introspection.identifier_converter(opts.db_table) f1 = connection.ops.quote_name(opts.get_field("root").column) f2 = connection.ops.quote_name(opts.get_field("square").column) if paramstyle == "format": query = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % (tbl, f1, f2) elif paramstyle == "pyformat": query = "INSERT INTO %s (%s, %s) VALUES (%%(root)s, %%(square)s)" % ( tbl, f1, f2, ) else: raise ValueError("unsupported paramstyle in test") with connection.cursor() as cursor: if multiple: cursor.executemany(query, args) else: cursor.execute(query, args) def test_cursor_executemany(self): # Test cursor.executemany #4896 args = [(i, i**2) for i in range(-5, 6)] self.create_squares_with_executemany(args) self.assertEqual(Square.objects.count(), 11) for i in range(-5, 6): square = Square.objects.get(root=i) self.assertEqual(square.square, i**2) def test_cursor_executemany_with_empty_params_list(self): # Test executemany with params=[] does nothing #4765 args = [] self.create_squares_with_executemany(args) self.assertEqual(Square.objects.count(), 0) def test_cursor_executemany_with_iterator(self): # Test executemany accepts iterators #10320 args = ((i, i**2) for i in range(-3, 2)) self.create_squares_with_executemany(args) self.assertEqual(Square.objects.count(), 5) args = ((i, i**2) for i in range(3, 7)) with override_settings(DEBUG=True): # same test for DebugCursorWrapper self.create_squares_with_executemany(args) self.assertEqual(Square.objects.count(), 9) @skipUnlessDBFeature("supports_paramstyle_pyformat") def test_cursor_execute_with_pyformat(self): # Support pyformat style passing of parameters #10070 args = {"root": 3, "square": 9} self.create_squares(args, "pyformat", multiple=False) self.assertEqual(Square.objects.count(), 1) @skipUnlessDBFeature("supports_paramstyle_pyformat") def test_cursor_executemany_with_pyformat(self): # Support pyformat style passing of parameters #10070 args = [{"root": i, "square": i**2} for i in range(-5, 6)] self.create_squares(args, "pyformat", multiple=True) self.assertEqual(Square.objects.count(), 11) for i in range(-5, 6): square = Square.objects.get(root=i) self.assertEqual(square.square, i**2) @skipUnlessDBFeature("supports_paramstyle_pyformat") def test_cursor_executemany_with_pyformat_iterator(self): args = ({"root": i, "square": i**2} for i in range(-3, 2)) self.create_squares(args, "pyformat", multiple=True) self.assertEqual(Square.objects.count(), 5) args = ({"root": i, "square": i**2} for i in range(3, 7)) with override_settings(DEBUG=True): # same test for DebugCursorWrapper self.create_squares(args, "pyformat", multiple=True) self.assertEqual(Square.objects.count(), 9) def test_unicode_fetches(self): # fetchone, fetchmany, fetchall return strings as Unicode objects. qn = connection.ops.quote_name Person(first_name="John", last_name="Doe").save() Person(first_name="Jane", last_name="Doe").save() Person(first_name="Mary", last_name="Agnelline").save() Person(first_name="Peter", last_name="Parker").save() Person(first_name="Clark", last_name="Kent").save() opts2 = Person._meta f3, f4 = opts2.get_field("first_name"), opts2.get_field("last_name") with connection.cursor() as cursor: cursor.execute( "SELECT %s, %s FROM %s ORDER BY %s" % ( qn(f3.column), qn(f4.column), connection.introspection.identifier_converter(opts2.db_table), qn(f3.column), ) ) self.assertEqual(cursor.fetchone(), ("Clark", "Kent")) self.assertEqual( list(cursor.fetchmany(2)), [("Jane", "Doe"), ("John", "Doe")] ) self.assertEqual( list(cursor.fetchall()), [("Mary", "Agnelline"), ("Peter", "Parker")] ) def test_unicode_password(self): old_password = connection.settings_dict["PASSWORD"] connection.settings_dict["PASSWORD"] = "françois" try: with connection.cursor(): pass except DatabaseError: # As password is probably wrong, a database exception is expected pass except Exception as e: self.fail("Unexpected error raised with Unicode password: %s" % e) finally: connection.settings_dict["PASSWORD"] = old_password def test_database_operations_helper_class(self): # Ticket #13630 self.assertTrue(hasattr(connection, "ops")) self.assertTrue(hasattr(connection.ops, "connection")) self.assertEqual(connection, connection.ops.connection) def test_database_operations_init(self): """ DatabaseOperations initialization doesn't query the database. See #17656. """ with self.assertNumQueries(0): connection.ops.__class__(connection) def test_cached_db_features(self): self.assertIn(connection.features.supports_transactions, (True, False)) self.assertIn(connection.features.can_introspect_foreign_keys, (True, False)) def test_duplicate_table_error(self): """Creating an existing table returns a DatabaseError""" query = "CREATE TABLE %s (id INTEGER);" % Article._meta.db_table with connection.cursor() as cursor: with self.assertRaises(DatabaseError): cursor.execute(query) def test_cursor_contextmanager(self): """ Cursors can be used as a context manager """ with connection.cursor() as cursor: self.assertIsInstance(cursor, CursorWrapper) # Both InterfaceError and ProgrammingError seem to be used when # accessing closed cursor (psycopg2 has InterfaceError, rest seem # to use ProgrammingError). with self.assertRaises(connection.features.closed_cursor_error_class): # cursor should be closed, so no queries should be possible. cursor.execute("SELECT 1" + connection.features.bare_select_suffix) @unittest.skipUnless( connection.vendor == "postgresql", "Psycopg2 specific cursor.closed attribute needed", ) def test_cursor_contextmanager_closing(self): # There isn't a generic way to test that cursors are closed, but # psycopg2 offers us a way to check that by closed attribute. # So, run only on psycopg2 for that reason. with connection.cursor() as cursor: self.assertIsInstance(cursor, CursorWrapper) self.assertTrue(cursor.closed) # Unfortunately with sqlite3 the in-memory test database cannot be closed. @skipUnlessDBFeature("test_db_allows_multiple_connections") def test_is_usable_after_database_disconnects(self): """ is_usable() doesn't crash when the database disconnects (#21553). """ # Open a connection to the database. with connection.cursor(): pass # Emulate a connection close by the database. connection._close() # Even then is_usable() should not raise an exception. try: self.assertFalse(connection.is_usable()) finally: # Clean up the mess created by connection._close(). Since the # connection is already closed, this crashes on some backends. try: connection.close() except Exception: pass @override_settings(DEBUG=True) def test_queries(self): """ Test the documented API of connection.queries. """ sql = "SELECT 1" + connection.features.bare_select_suffix with connection.cursor() as cursor: reset_queries() cursor.execute(sql) self.assertEqual(1, len(connection.queries)) self.assertIsInstance(connection.queries, list) self.assertIsInstance(connection.queries[0], dict) self.assertEqual(list(connection.queries[0]), ["sql", "time"]) self.assertEqual(connection.queries[0]["sql"], sql) reset_queries() self.assertEqual(0, len(connection.queries)) sql = "INSERT INTO %s (%s, %s) VALUES (%%s, %%s)" % ( connection.introspection.identifier_converter("backends_square"), connection.ops.quote_name("root"), connection.ops.quote_name("square"), ) with connection.cursor() as cursor: cursor.executemany(sql, [(1, 1), (2, 4)]) self.assertEqual(1, len(connection.queries)) self.assertIsInstance(connection.queries, list) self.assertIsInstance(connection.queries[0], dict) self.assertEqual(list(connection.queries[0]), ["sql", "time"]) self.assertEqual(connection.queries[0]["sql"], "2 times: %s" % sql) # Unfortunately with sqlite3 the in-memory test database cannot be closed. @skipUnlessDBFeature("test_db_allows_multiple_connections") @override_settings(DEBUG=True) def test_queries_limit(self): """ The backend doesn't store an unlimited number of queries (#12581). """ old_queries_limit = BaseDatabaseWrapper.queries_limit BaseDatabaseWrapper.queries_limit = 3 new_connection = connection.copy() # Initialize the connection and clear initialization statements. with new_connection.cursor(): pass new_connection.queries_log.clear() try: with new_connection.cursor() as cursor: cursor.execute("SELECT 1" + new_connection.features.bare_select_suffix) cursor.execute("SELECT 2" + new_connection.features.bare_select_suffix) with warnings.catch_warnings(record=True) as w: self.assertEqual(2, len(new_connection.queries)) self.assertEqual(0, len(w)) with new_connection.cursor() as cursor: cursor.execute("SELECT 3" + new_connection.features.bare_select_suffix) cursor.execute("SELECT 4" + new_connection.features.bare_select_suffix) msg = ( "Limit for query logging exceeded, only the last 3 queries will be " "returned." ) with self.assertWarnsMessage(UserWarning, msg): self.assertEqual(3, len(new_connection.queries)) finally: BaseDatabaseWrapper.queries_limit = old_queries_limit new_connection.close() @mock.patch("django.db.backends.utils.logger") @override_settings(DEBUG=True) def test_queries_logger(self, mocked_logger): sql = "SELECT 1" + connection.features.bare_select_suffix with connection.cursor() as cursor: cursor.execute(sql) params, kwargs = mocked_logger.debug.call_args self.assertIn("; alias=%s", params[0]) self.assertEqual(params[2], sql) self.assertIsNone(params[3]) self.assertEqual(params[4], connection.alias) self.assertEqual( list(kwargs["extra"]), ["duration", "sql", "params", "alias"], ) self.assertEqual(tuple(kwargs["extra"].values()), params[1:]) def test_timezone_none_use_tz_false(self): connection.ensure_connection() with self.settings(TIME_ZONE=None, USE_TZ=False): connection.init_connection_state() # These tests aren't conditional because it would require differentiating # between MySQL+InnoDB and MySQL+MYISAM (something we currently can't do). class FkConstraintsTests(TransactionTestCase): available_apps = ["backends"] def setUp(self): # Create a Reporter. self.r = Reporter.objects.create(first_name="John", last_name="Smith") def test_integrity_checks_on_creation(self): """ Try to create a model instance that violates a FK constraint. If it fails it should fail with IntegrityError. """ a1 = Article( headline="This is a test", pub_date=datetime.datetime(2005, 7, 27), reporter_id=30, ) try: a1.save() except IntegrityError: pass else: self.skipTest("This backend does not support integrity checks.") # Now that we know this backend supports integrity checks we make sure # constraints are also enforced for proxy Refs #17519 a2 = Article( headline="This is another test", reporter=self.r, pub_date=datetime.datetime(2012, 8, 3), reporter_proxy_id=30, ) with self.assertRaises(IntegrityError): a2.save() def test_integrity_checks_on_update(self): """ Try to update a model instance introducing a FK constraint violation. If it fails it should fail with IntegrityError. """ # Create an Article. Article.objects.create( headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r, ) # Retrieve it from the DB a1 = Article.objects.get(headline="Test article") a1.reporter_id = 30 try: a1.save() except IntegrityError: pass else: self.skipTest("This backend does not support integrity checks.") # Now that we know this backend supports integrity checks we make sure # constraints are also enforced for proxy Refs #17519 # Create another article r_proxy = ReporterProxy.objects.get(pk=self.r.pk) Article.objects.create( headline="Another article", pub_date=datetime.datetime(1988, 5, 15), reporter=self.r, reporter_proxy=r_proxy, ) # Retrieve the second article from the DB a2 = Article.objects.get(headline="Another article") a2.reporter_proxy_id = 30 with self.assertRaises(IntegrityError): a2.save() def test_disable_constraint_checks_manually(self): """ When constraint checks are disabled, should be able to write bad data without IntegrityErrors. """ with transaction.atomic(): # Create an Article. Article.objects.create( headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r, ) # Retrieve it from the DB a = Article.objects.get(headline="Test article") a.reporter_id = 30 try: connection.disable_constraint_checking() a.save() connection.enable_constraint_checking() except IntegrityError: self.fail("IntegrityError should not have occurred.") transaction.set_rollback(True) def test_disable_constraint_checks_context_manager(self): """ When constraint checks are disabled (using context manager), should be able to write bad data without IntegrityErrors. """ with transaction.atomic(): # Create an Article. Article.objects.create( headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r, ) # Retrieve it from the DB a = Article.objects.get(headline="Test article") a.reporter_id = 30 try: with connection.constraint_checks_disabled(): a.save() except IntegrityError: self.fail("IntegrityError should not have occurred.") transaction.set_rollback(True) def test_check_constraints(self): """ Constraint checks should raise an IntegrityError when bad data is in the DB. """ with transaction.atomic(): # Create an Article. Article.objects.create( headline="Test article", pub_date=datetime.datetime(2010, 9, 4), reporter=self.r, ) # Retrieve it from the DB a = Article.objects.get(headline="Test article") a.reporter_id = 30 with connection.constraint_checks_disabled(): a.save() with self.assertRaises(IntegrityError): connection.check_constraints(table_names=[Article._meta.db_table]) transaction.set_rollback(True) def test_check_constraints_sql_keywords(self): with transaction.atomic(): obj = SQLKeywordsModel.objects.create(reporter=self.r) obj.refresh_from_db() obj.reporter_id = 30 with connection.constraint_checks_disabled(): obj.save() with self.assertRaises(IntegrityError): connection.check_constraints(table_names=["order"]) transaction.set_rollback(True) class ThreadTests(TransactionTestCase): available_apps = ["backends"] def test_default_connection_thread_local(self): """ The default connection (i.e. django.db.connection) is different for each thread (#17258). """ # Map connections by id because connections with identical aliases # have the same hash. connections_dict = {} with connection.cursor(): pass connections_dict[id(connection)] = connection def runner(): # Passing django.db.connection between threads doesn't work while # connections[DEFAULT_DB_ALIAS] does. from django.db import connections connection = connections[DEFAULT_DB_ALIAS] # Allow thread sharing so the connection can be closed by the # main thread. connection.inc_thread_sharing() with connection.cursor(): pass connections_dict[id(connection)] = connection try: for x in range(2): t = threading.Thread(target=runner) t.start() t.join() # Each created connection got different inner connection. self.assertEqual( len({conn.connection for conn in connections_dict.values()}), 3 ) finally: # Finish by closing the connections opened by the other threads # (the connection opened in the main thread will automatically be # closed on teardown). for conn in connections_dict.values(): if conn is not connection and conn.allow_thread_sharing: conn.close() conn.dec_thread_sharing() def test_connections_thread_local(self): """ The connections are different for each thread (#17258). """ # Map connections by id because connections with identical aliases # have the same hash. connections_dict = {} for conn in connections.all(): connections_dict[id(conn)] = conn def runner(): from django.db import connections for conn in connections.all(): # Allow thread sharing so the connection can be closed by the # main thread. conn.inc_thread_sharing() connections_dict[id(conn)] = conn try: num_new_threads = 2 for x in range(num_new_threads): t = threading.Thread(target=runner) t.start() t.join() self.assertEqual( len(connections_dict), len(connections.all()) * (num_new_threads + 1), ) finally: # Finish by closing the connections opened by the other threads # (the connection opened in the main thread will automatically be # closed on teardown). for conn in connections_dict.values(): if conn is not connection and conn.allow_thread_sharing: conn.close() conn.dec_thread_sharing() def test_pass_connection_between_threads(self): """ A connection can be passed from one thread to the other (#17258). """ Person.objects.create(first_name="John", last_name="Doe") def do_thread(): def runner(main_thread_connection): from django.db import connections connections["default"] = main_thread_connection try: Person.objects.get(first_name="John", last_name="Doe") except Exception as e: exceptions.append(e) t = threading.Thread(target=runner, args=[connections["default"]]) t.start() t.join() # Without touching thread sharing, which should be False by default. exceptions = [] do_thread() # Forbidden! self.assertIsInstance(exceptions[0], DatabaseError) connections["default"].close() # After calling inc_thread_sharing() on the connection. connections["default"].inc_thread_sharing() try: exceptions = [] do_thread() # All good self.assertEqual(exceptions, []) finally: connections["default"].dec_thread_sharing() def test_closing_non_shared_connections(self): """ A connection that is not explicitly shareable cannot be closed by another thread (#17258). """ # First, without explicitly enabling the connection for sharing. exceptions = set() def runner1(): def runner2(other_thread_connection): try: other_thread_connection.close() except DatabaseError as e: exceptions.add(e) t2 = threading.Thread(target=runner2, args=[connections["default"]]) t2.start() t2.join() t1 = threading.Thread(target=runner1) t1.start() t1.join() # The exception was raised self.assertEqual(len(exceptions), 1) # Then, with explicitly enabling the connection for sharing. exceptions = set() def runner1(): def runner2(other_thread_connection): try: other_thread_connection.close() except DatabaseError as e: exceptions.add(e) # Enable thread sharing connections["default"].inc_thread_sharing() try: t2 = threading.Thread(target=runner2, args=[connections["default"]]) t2.start() t2.join() finally: connections["default"].dec_thread_sharing() t1 = threading.Thread(target=runner1) t1.start() t1.join() # No exception was raised self.assertEqual(len(exceptions), 0) def test_thread_sharing_count(self): self.assertIs(connection.allow_thread_sharing, False) connection.inc_thread_sharing() self.assertIs(connection.allow_thread_sharing, True) connection.inc_thread_sharing() self.assertIs(connection.allow_thread_sharing, True) connection.dec_thread_sharing() self.assertIs(connection.allow_thread_sharing, True) connection.dec_thread_sharing() self.assertIs(connection.allow_thread_sharing, False) msg = "Cannot decrement the thread sharing count below zero." with self.assertRaisesMessage(RuntimeError, msg): connection.dec_thread_sharing() class MySQLPKZeroTests(TestCase): """ Zero as id for AutoField should raise exception in MySQL, because MySQL does not allow zero for autoincrement primary key if the NO_AUTO_VALUE_ON_ZERO SQL mode is not enabled. """ @skipIfDBFeature("allows_auto_pk_0") def test_zero_as_autoval(self): with self.assertRaises(ValueError): Square.objects.create(id=0, root=0, square=1) class DBConstraintTestCase(TestCase): def test_can_reference_existent(self): obj = Object.objects.create() ref = ObjectReference.objects.create(obj=obj) self.assertEqual(ref.obj, obj) ref = ObjectReference.objects.get(obj=obj) self.assertEqual(ref.obj, obj) def test_can_reference_non_existent(self): self.assertFalse(Object.objects.filter(id=12345).exists()) ref = ObjectReference.objects.create(obj_id=12345) ref_new = ObjectReference.objects.get(obj_id=12345) self.assertEqual(ref, ref_new) with self.assertRaises(Object.DoesNotExist): ref.obj def test_many_to_many(self): obj = Object.objects.create() obj.related_objects.create() self.assertEqual(Object.objects.count(), 2) self.assertEqual(obj.related_objects.count(), 1) intermediary_model = Object._meta.get_field( "related_objects" ).remote_field.through intermediary_model.objects.create(from_object_id=obj.id, to_object_id=12345) self.assertEqual(obj.related_objects.count(), 1) self.assertEqual(intermediary_model.objects.count(), 2)
5efae2603192c251ce6c8db298cb15acfba28ddc5f11a9edb30f0b149afc2885
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class Square(models.Model): root = models.IntegerField() square = models.PositiveIntegerField() def __str__(self): return "%s ** 2 == %s" % (self.root, self.square) class Person(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) def __str__(self): return "%s %s" % (self.first_name, self.last_name) class SchoolClassManager(models.Manager): def get_queryset(self): return super().get_queryset().exclude(year=1000) class SchoolClass(models.Model): year = models.PositiveIntegerField() day = models.CharField(max_length=9, blank=True) last_updated = models.DateTimeField() objects = SchoolClassManager() class VeryLongModelNameZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ(models.Model): primary_key_is_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models.AutoField( primary_key=True ) charfield_is_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = models.CharField( max_length=100 ) m2m_also_quite_long_zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz = ( models.ManyToManyField(Person, blank=True) ) class Tag(models.Model): name = models.CharField(max_length=30) content_type = models.ForeignKey( ContentType, models.CASCADE, related_name="backend_tags" ) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") class Post(models.Model): name = models.CharField(max_length=30) text = models.TextField() tags = GenericRelation("Tag") class Meta: db_table = "CaseSensitive_Post" class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) def __str__(self): return "%s %s" % (self.first_name, self.last_name) class ReporterProxy(Reporter): class Meta: proxy = True class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, models.CASCADE) reporter_proxy = models.ForeignKey( ReporterProxy, models.SET_NULL, null=True, related_name="reporter_proxy", ) def __str__(self): return self.headline class Item(models.Model): name = models.CharField(max_length=30) date = models.DateField() time = models.TimeField() last_modified = models.DateTimeField() def __str__(self): return self.name class Object(models.Model): related_objects = models.ManyToManyField( "self", db_constraint=False, symmetrical=False ) obj_ref = models.ForeignKey("ObjectReference", models.CASCADE, null=True) def __str__(self): return str(self.id) class ObjectReference(models.Model): obj = models.ForeignKey(Object, models.CASCADE, db_constraint=False) def __str__(self): return str(self.obj_id) class ObjectSelfReference(models.Model): key = models.CharField(max_length=3, unique=True) obj = models.ForeignKey("ObjectSelfReference", models.SET_NULL, null=True) class CircularA(models.Model): key = models.CharField(max_length=3, unique=True) obj = models.ForeignKey("CircularB", models.SET_NULL, null=True) def natural_key(self): return (self.key,) class CircularB(models.Model): key = models.CharField(max_length=3, unique=True) obj = models.ForeignKey("CircularA", models.SET_NULL, null=True) def natural_key(self): return (self.key,) class RawData(models.Model): raw_data = models.BinaryField() class Author(models.Model): name = models.CharField(max_length=255, unique=True) class Book(models.Model): author = models.ForeignKey(Author, models.CASCADE, to_field="name") class SQLKeywordsModel(models.Model): id = models.AutoField(primary_key=True, db_column="select") reporter = models.ForeignKey(Reporter, models.CASCADE, db_column="where") class Meta: db_table = "order"
82b4965c27a6977e201dec3ddfd8991be5be95e68081dd917485a5c89b0b50b0
from django.db.migrations.operations.base import Operation class TestOperation(Operation): def __init__(self): pass def deconstruct(self): return (self.__class__.__name__, [], {}) @property def reversible(self): return True def state_forwards(self, app_label, state): pass def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def state_backwards(self, app_label, state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass
a17a1861ec14f02ee5bb6d302cc606f25e8b7472e8582b103b9f7454330d8600
from django.db.migrations.operations.base import Operation class TestOperation(Operation): def __init__(self): pass def deconstruct(self): return (self.__class__.__name__, [], {}) @property def reversible(self): return True def state_forwards(self, app_label, state): pass def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def state_backwards(self, app_label, state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass class CreateModel(TestOperation): pass class ArgsOperation(TestOperation): def __init__(self, arg1, arg2): self.arg1, self.arg2 = arg1, arg2 def deconstruct(self): return (self.__class__.__name__, [self.arg1, self.arg2], {}) class KwargsOperation(TestOperation): def __init__(self, kwarg1=None, kwarg2=None): self.kwarg1, self.kwarg2 = kwarg1, kwarg2 def deconstruct(self): kwargs = {} if self.kwarg1 is not None: kwargs["kwarg1"] = self.kwarg1 if self.kwarg2 is not None: kwargs["kwarg2"] = self.kwarg2 return (self.__class__.__name__, [], kwargs) class ArgsKwargsOperation(TestOperation): def __init__(self, arg1, arg2, kwarg1=None, kwarg2=None): self.arg1, self.arg2 = arg1, arg2 self.kwarg1, self.kwarg2 = kwarg1, kwarg2 def deconstruct(self): kwargs = {} if self.kwarg1 is not None: kwargs["kwarg1"] = self.kwarg1 if self.kwarg2 is not None: kwargs["kwarg2"] = self.kwarg2 return ( self.__class__.__name__, [self.arg1, self.arg2], kwargs, ) class ExpandArgsOperation(TestOperation): serialization_expand_args = ["arg"] def __init__(self, arg): self.arg = arg def deconstruct(self): return (self.__class__.__name__, [self.arg], {})
48402690ca01b3d0506db8d11c8b41f0adc8aec9a25c1fc562d5b7497ea9b370
from django.db import models from django.template import Context, Template from django.test import SimpleTestCase, TestCase, override_settings from django.test.utils import isolate_apps from .models import ( AbstractBase1, AbstractBase2, AbstractBase3, Child1, Child2, Child3, Child4, Child5, Child6, Child7, RelatedModel, RelationModel, ) class ManagersRegressionTests(TestCase): def test_managers(self): a1 = Child1.objects.create(name="fred", data="a1") a2 = Child1.objects.create(name="barney", data="a2") b1 = Child2.objects.create(name="fred", data="b1", value=1) b2 = Child2.objects.create(name="barney", data="b2", value=42) c1 = Child3.objects.create(name="fred", data="c1", comment="yes") c2 = Child3.objects.create(name="barney", data="c2", comment="no") d1 = Child4.objects.create(name="fred", data="d1") d2 = Child4.objects.create(name="barney", data="d2") fred1 = Child5.objects.create(name="fred", comment="yes") Child5.objects.create(name="barney", comment="no") f1 = Child6.objects.create(name="fred", data="f1", value=42) f2 = Child6.objects.create(name="barney", data="f2", value=42) fred2 = Child7.objects.create(name="fred") barney = Child7.objects.create(name="barney") self.assertSequenceEqual(Child1.manager1.all(), [a1]) self.assertSequenceEqual(Child1.manager2.all(), [a2]) self.assertSequenceEqual(Child1._default_manager.all(), [a1]) self.assertSequenceEqual(Child2._default_manager.all(), [b1]) self.assertSequenceEqual(Child2.restricted.all(), [b2]) self.assertSequenceEqual(Child3._default_manager.all(), [c1]) self.assertSequenceEqual(Child3.manager1.all(), [c1]) self.assertSequenceEqual(Child3.manager2.all(), [c2]) # Since Child6 inherits from Child4, the corresponding rows from f1 and # f2 also appear here. This is the expected result. self.assertSequenceEqual( Child4._default_manager.order_by("data"), [d1, d2, f1.child4_ptr, f2.child4_ptr], ) self.assertCountEqual(Child4.manager1.all(), [d1, f1.child4_ptr]) self.assertCountEqual(Child5._default_manager.all(), [fred1]) self.assertCountEqual(Child6._default_manager.all(), [f1, f2]) self.assertSequenceEqual( Child7._default_manager.order_by("name"), [barney, fred2], ) def test_abstract_manager(self): # Accessing the manager on an abstract model should # raise an attribute error with an appropriate message. # This error message isn't ideal, but if the model is abstract and # a lot of the class instantiation logic isn't invoked; if the # manager is implied, then we don't get a hook to install the # error-raising manager. msg = "type object 'AbstractBase3' has no attribute 'objects'" with self.assertRaisesMessage(AttributeError, msg): AbstractBase3.objects.all() def test_custom_abstract_manager(self): # Accessing the manager on an abstract model with a custom # manager should raise an attribute error with an appropriate # message. msg = "Manager isn't available; AbstractBase2 is abstract" with self.assertRaisesMessage(AttributeError, msg): AbstractBase2.restricted.all() def test_explicit_abstract_manager(self): # Accessing the manager on an abstract model with an explicit # manager should raise an attribute error with an appropriate # message. msg = "Manager isn't available; AbstractBase1 is abstract" with self.assertRaisesMessage(AttributeError, msg): AbstractBase1.objects.all() @override_settings(TEST_SWAPPABLE_MODEL="managers_regress.Parent") @isolate_apps("managers_regress") def test_swappable_manager(self): class SwappableModel(models.Model): class Meta: swappable = "TEST_SWAPPABLE_MODEL" # Accessing the manager on a swappable model should # raise an attribute error with a helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'" ) with self.assertRaisesMessage(AttributeError, msg): SwappableModel.objects.all() @override_settings(TEST_SWAPPABLE_MODEL="managers_regress.Parent") @isolate_apps("managers_regress") def test_custom_swappable_manager(self): class SwappableModel(models.Model): stuff = models.Manager() class Meta: swappable = "TEST_SWAPPABLE_MODEL" # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'" ) with self.assertRaisesMessage(AttributeError, msg): SwappableModel.stuff.all() @override_settings(TEST_SWAPPABLE_MODEL="managers_regress.Parent") @isolate_apps("managers_regress") def test_explicit_swappable_manager(self): class SwappableModel(models.Model): objects = models.Manager() class Meta: swappable = "TEST_SWAPPABLE_MODEL" # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'" ) with self.assertRaisesMessage(AttributeError, msg): SwappableModel.objects.all() def test_regress_3871(self): related = RelatedModel.objects.create() relation = RelationModel() relation.fk = related relation.gfk = related relation.save() relation.m2m.add(related) t = Template( "{{ related.test_fk.all.0 }}{{ related.test_gfk.all.0 }}" "{{ related.test_m2m.all.0 }}" ) self.assertEqual( t.render(Context({"related": related})), "".join([str(relation.pk)] * 3), ) def test_field_can_be_called_exact(self): # Make sure related managers core filters don't include an # explicit `__exact` lookup that could be interpreted as a # reference to a foreign `exact` field. refs #23940. related = RelatedModel.objects.create(exact=False) relation = related.test_fk.create() self.assertEqual(related.test_fk.get(), relation) @isolate_apps("managers_regress") class TestManagerInheritance(SimpleTestCase): def test_implicit_inheritance(self): class CustomManager(models.Manager): pass class AbstractModel(models.Model): custom_manager = CustomManager() class Meta: abstract = True class PlainModel(models.Model): custom_manager = CustomManager() self.assertIsInstance(PlainModel._base_manager, models.Manager) self.assertIsInstance(PlainModel._default_manager, CustomManager) class ModelWithAbstractParent(AbstractModel): pass self.assertIsInstance(ModelWithAbstractParent._base_manager, models.Manager) self.assertIsInstance(ModelWithAbstractParent._default_manager, CustomManager) class ProxyModel(PlainModel): class Meta: proxy = True self.assertIsInstance(ProxyModel._base_manager, models.Manager) self.assertIsInstance(ProxyModel._default_manager, CustomManager) class MTIModel(PlainModel): pass self.assertIsInstance(MTIModel._base_manager, models.Manager) self.assertIsInstance(MTIModel._default_manager, CustomManager) def test_default_manager_inheritance(self): class CustomManager(models.Manager): pass class AbstractModel(models.Model): another_manager = models.Manager() custom_manager = CustomManager() class Meta: default_manager_name = "custom_manager" abstract = True class PlainModel(models.Model): another_manager = models.Manager() custom_manager = CustomManager() class Meta: default_manager_name = "custom_manager" self.assertIsInstance(PlainModel._default_manager, CustomManager) class ModelWithAbstractParent(AbstractModel): pass self.assertIsInstance(ModelWithAbstractParent._default_manager, CustomManager) class ProxyModel(PlainModel): class Meta: proxy = True self.assertIsInstance(ProxyModel._default_manager, CustomManager) class MTIModel(PlainModel): pass self.assertIsInstance(MTIModel._default_manager, CustomManager) def test_base_manager_inheritance(self): class CustomManager(models.Manager): pass class AbstractModel(models.Model): another_manager = models.Manager() custom_manager = CustomManager() class Meta: base_manager_name = "custom_manager" abstract = True class PlainModel(models.Model): another_manager = models.Manager() custom_manager = CustomManager() class Meta: base_manager_name = "custom_manager" self.assertIsInstance(PlainModel._base_manager, CustomManager) class ModelWithAbstractParent(AbstractModel): pass self.assertIsInstance(ModelWithAbstractParent._base_manager, CustomManager) class ProxyModel(PlainModel): class Meta: proxy = True self.assertIsInstance(ProxyModel._base_manager, CustomManager) class MTIModel(PlainModel): pass self.assertIsInstance(MTIModel._base_manager, CustomManager) def test_manager_no_duplicates(self): class CustomManager(models.Manager): pass class AbstractModel(models.Model): custom_manager = models.Manager() class Meta: abstract = True class TestModel(AbstractModel): custom_manager = CustomManager() self.assertEqual(TestModel._meta.managers, (TestModel.custom_manager,)) self.assertEqual( TestModel._meta.managers_map, {"custom_manager": TestModel.custom_manager} ) def test_manager_class_getitem(self): self.assertIs(models.Manager[Child1], models.Manager)
55637416288a8720a65b9fa4aab77d3d68abafda3ebf59cd2b676fd7fae9cc8c
""" Various edge-cases for model managers. """ from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from django.db import models class OnlyFred(models.Manager): def get_queryset(self): return super().get_queryset().filter(name="fred") class OnlyBarney(models.Manager): def get_queryset(self): return super().get_queryset().filter(name="barney") class Value42(models.Manager): def get_queryset(self): return super().get_queryset().filter(value=42) class AbstractBase1(models.Model): name = models.CharField(max_length=50) class Meta: abstract = True # Custom managers manager1 = OnlyFred() manager2 = OnlyBarney() objects = models.Manager() class AbstractBase2(models.Model): value = models.IntegerField() class Meta: abstract = True # Custom manager restricted = Value42() # No custom manager on this class to make sure the default case doesn't break. class AbstractBase3(models.Model): comment = models.CharField(max_length=50) class Meta: abstract = True class Parent(models.Model): name = models.CharField(max_length=50) manager = OnlyFred() def __str__(self): return self.name # Managers from base classes are inherited and, if no manager is specified # *and* the parent has a manager specified, the first one (in the MRO) will # become the default. class Child1(AbstractBase1): data = models.CharField(max_length=25) def __str__(self): return self.data class Child2(AbstractBase1, AbstractBase2): data = models.CharField(max_length=25) def __str__(self): return self.data class Child3(AbstractBase1, AbstractBase3): data = models.CharField(max_length=25) def __str__(self): return self.data class Child4(AbstractBase1): data = models.CharField(max_length=25) # Should be the default manager, although the parent managers are # inherited. default = models.Manager() def __str__(self): return self.data class Child5(AbstractBase3): name = models.CharField(max_length=25) default = OnlyFred() objects = models.Manager() def __str__(self): return self.name class Child6(Child4): value = models.IntegerField() class Child7(Parent): objects = models.Manager() # RelatedManagers class RelatedModel(models.Model): test_gfk = GenericRelation( "RelationModel", content_type_field="gfk_ctype", object_id_field="gfk_id" ) exact = models.BooleanField(null=True) def __str__(self): return str(self.pk) class RelationModel(models.Model): fk = models.ForeignKey(RelatedModel, models.CASCADE, related_name="test_fk") m2m = models.ManyToManyField(RelatedModel, related_name="test_m2m") gfk_ctype = models.ForeignKey(ContentType, models.SET_NULL, null=True) gfk_id = models.IntegerField(null=True) gfk = GenericForeignKey(ct_field="gfk_ctype", fk_field="gfk_id") def __str__(self): return str(self.pk)
2e5c1a29e97d368a1a6f8f4cb0e62faee01fc971420f40802fce8396d5c0a049
import datetime import itertools import unittest from copy import copy from unittest import mock from django.core.exceptions import FieldError from django.core.management.color import no_style from django.db import ( DatabaseError, DataError, IntegrityError, OperationalError, connection, ) from django.db.models import ( CASCADE, PROTECT, AutoField, BigAutoField, BigIntegerField, BinaryField, BooleanField, CharField, CheckConstraint, DateField, DateTimeField, DecimalField, DurationField, F, FloatField, ForeignKey, ForeignObject, Index, IntegerField, JSONField, ManyToManyField, Model, OneToOneField, OrderBy, PositiveIntegerField, Q, SlugField, SmallAutoField, SmallIntegerField, TextField, TimeField, UniqueConstraint, UUIDField, Value, ) from django.db.models.fields.json import KeyTextTransform from django.db.models.functions import Abs, Cast, Collate, Lower, Random, Upper from django.db.models.indexes import IndexExpression from django.db.transaction import TransactionManagementError, atomic from django.test import TransactionTestCase, skipIfDBFeature, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext, isolate_apps, register_lookup from django.utils import timezone from .fields import CustomManyToManyField, InheritedManyToManyField, MediumBlobField from .models import ( Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex, AuthorWithDefaultHeight, AuthorWithEvenLongerName, AuthorWithIndexedName, AuthorWithIndexedNameAndBirthday, AuthorWithUniqueName, AuthorWithUniqueNameAndBirthday, Book, BookForeignObj, BookWeak, BookWithLongName, BookWithO2O, BookWithoutAuthor, BookWithSlug, IntegerPK, Node, Note, NoteRename, Tag, TagIndexed, TagM2MTest, TagUniqueRename, Thing, UniqueTest, new_apps, ) class SchemaTests(TransactionTestCase): """ Tests for the schema-alteration code. Be aware that these tests are more liable than most to false results, as sometimes the code to check if a test has worked is almost as complex as the code it is testing. """ available_apps = [] models = [ Author, AuthorCharFieldWithIndex, AuthorTextFieldWithIndex, AuthorWithDefaultHeight, AuthorWithEvenLongerName, Book, BookWeak, BookWithLongName, BookWithO2O, BookWithSlug, IntegerPK, Node, Note, Tag, TagIndexed, TagM2MTest, TagUniqueRename, Thing, UniqueTest, ] # Utility functions def setUp(self): # local_models should contain test dependent model classes that will be # automatically removed from the app cache on test tear down. self.local_models = [] # isolated_local_models contains models that are in test methods # decorated with @isolate_apps. self.isolated_local_models = [] def tearDown(self): # Delete any tables made for our models self.delete_tables() new_apps.clear_cache() for model in new_apps.get_models(): model._meta._expire_cache() if "schema" in new_apps.all_models: for model in self.local_models: for many_to_many in model._meta.many_to_many: through = many_to_many.remote_field.through if through and through._meta.auto_created: del new_apps.all_models["schema"][through._meta.model_name] del new_apps.all_models["schema"][model._meta.model_name] if self.isolated_local_models: with connection.schema_editor() as editor: for model in self.isolated_local_models: editor.delete_model(model) def delete_tables(self): "Deletes all model tables for our models for a clean test environment" converter = connection.introspection.identifier_converter with connection.schema_editor() as editor: connection.disable_constraint_checking() table_names = connection.introspection.table_names() if connection.features.ignores_table_name_case: table_names = [table_name.lower() for table_name in table_names] for model in itertools.chain(SchemaTests.models, self.local_models): tbl = converter(model._meta.db_table) if connection.features.ignores_table_name_case: tbl = tbl.lower() if tbl in table_names: editor.delete_model(model) table_names.remove(tbl) connection.enable_constraint_checking() def column_classes(self, model): with connection.cursor() as cursor: columns = { d[0]: (connection.introspection.get_field_type(d[1], d), d) for d in connection.introspection.get_table_description( cursor, model._meta.db_table, ) } # SQLite has a different format for field_type for name, (type, desc) in columns.items(): if isinstance(type, tuple): columns[name] = (type[0], desc) return columns def get_primary_key(self, table): with connection.cursor() as cursor: return connection.introspection.get_primary_key_column(cursor, table) def get_indexes(self, table): """ Get the indexes on the table using a new cursor. """ with connection.cursor() as cursor: return [ c["columns"][0] for c in connection.introspection.get_constraints( cursor, table ).values() if c["index"] and len(c["columns"]) == 1 ] def get_uniques(self, table): with connection.cursor() as cursor: return [ c["columns"][0] for c in connection.introspection.get_constraints( cursor, table ).values() if c["unique"] and len(c["columns"]) == 1 ] def get_constraints(self, table): """ Get the constraints on a table using a new cursor. """ with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def get_constraints_for_column(self, model, column_name): constraints = self.get_constraints(model._meta.db_table) constraints_for_column = [] for name, details in constraints.items(): if details["columns"] == [column_name]: constraints_for_column.append(name) return sorted(constraints_for_column) def check_added_field_default( self, schema_editor, model, field, field_name, expected_default, cast_function=None, ): with connection.cursor() as cursor: schema_editor.add_field(model, field) cursor.execute( "SELECT {} FROM {};".format(field_name, model._meta.db_table) ) database_default = cursor.fetchall()[0][0] if cast_function and type(database_default) != type(expected_default): database_default = cast_function(database_default) self.assertEqual(database_default, expected_default) def get_constraints_count(self, table, column, fk_to): """ Return a dict with keys 'fks', 'uniques, and 'indexes' indicating the number of foreign keys, unique constraints, and indexes on `table`.`column`. The `fk_to` argument is a 2-tuple specifying the expected foreign key relationship's (table, column). """ with connection.cursor() as cursor: constraints = connection.introspection.get_constraints(cursor, table) counts = {"fks": 0, "uniques": 0, "indexes": 0} for c in constraints.values(): if c["columns"] == [column]: if c["foreign_key"] == fk_to: counts["fks"] += 1 if c["unique"]: counts["uniques"] += 1 elif c["index"]: counts["indexes"] += 1 return counts def get_column_collation(self, table, column): with connection.cursor() as cursor: return next( f.collation for f in connection.introspection.get_table_description(cursor, table) if f.name == column ) def assertIndexOrder(self, table, index, order): constraints = self.get_constraints(table) self.assertIn(index, constraints) index_orders = constraints[index]["orders"] self.assertTrue( all(val == expected for val, expected in zip(index_orders, order)) ) def assertForeignKeyExists(self, model, column, expected_fk_table, field="id"): """ Fail if the FK constraint on `model.Meta.db_table`.`column` to `expected_fk_table`.id doesn't exist. """ constraints = self.get_constraints(model._meta.db_table) constraint_fk = None for details in constraints.values(): if details["columns"] == [column] and details["foreign_key"]: constraint_fk = details["foreign_key"] break self.assertEqual(constraint_fk, (expected_fk_table, field)) def assertForeignKeyNotExists(self, model, column, expected_fk_table): with self.assertRaises(AssertionError): self.assertForeignKeyExists(model, column, expected_fk_table) # Tests def test_creation_deletion(self): """ Tries creating a model's table, and then deleting it. """ with connection.schema_editor() as editor: # Create the table editor.create_model(Author) # The table is there list(Author.objects.all()) # Clean up that table editor.delete_model(Author) # No deferred SQL should be left over. self.assertEqual(editor.deferred_sql, []) # The table is gone with self.assertRaises(DatabaseError): list(Author.objects.all()) @skipUnlessDBFeature("supports_foreign_keys") def test_fk(self): "Creating tables out of FK order, then repointing, works" # Create the table with connection.schema_editor() as editor: editor.create_model(Book) editor.create_model(Author) editor.create_model(Tag) # Initial tables are there list(Author.objects.all()) list(Book.objects.all()) # Make sure the FK constraint is present with self.assertRaises(IntegrityError): Book.objects.create( author_id=1, title="Much Ado About Foreign Keys", pub_date=datetime.datetime.now(), ) # Repoint the FK constraint old_field = Book._meta.get_field("author") new_field = ForeignKey(Tag, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) self.assertForeignKeyExists(Book, "author_id", "schema_tag") @skipUnlessDBFeature("can_create_inline_fk") def test_inline_fk(self): # Create some tables. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) editor.create_model(Note) self.assertForeignKeyNotExists(Note, "book_id", "schema_book") # Add a foreign key from one to the other. with connection.schema_editor() as editor: new_field = ForeignKey(Book, CASCADE) new_field.set_attributes_from_name("book") editor.add_field(Note, new_field) self.assertForeignKeyExists(Note, "book_id", "schema_book") # Creating a FK field with a constraint uses a single statement without # a deferred ALTER TABLE. self.assertFalse( [ sql for sql in (str(statement) for statement in editor.deferred_sql) if sql.startswith("ALTER TABLE") and "ADD CONSTRAINT" in sql ] ) @skipUnlessDBFeature("can_create_inline_fk") def test_add_inline_fk_update_data(self): with connection.schema_editor() as editor: editor.create_model(Node) # Add an inline foreign key and update data in the same transaction. new_field = ForeignKey(Node, CASCADE, related_name="new_fk", null=True) new_field.set_attributes_from_name("new_parent_fk") parent = Node.objects.create() with connection.schema_editor() as editor: editor.add_field(Node, new_field) editor.execute("UPDATE schema_node SET new_parent_fk_id = %s;", [parent.pk]) assertIndex = ( self.assertIn if connection.features.indexes_foreign_keys else self.assertNotIn ) assertIndex("new_parent_fk_id", self.get_indexes(Node._meta.db_table)) @skipUnlessDBFeature( "can_create_inline_fk", "allows_multiple_constraints_on_same_fields", ) @isolate_apps("schema") def test_add_inline_fk_index_update_data(self): class Node(Model): class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Node) # Add an inline foreign key, update data, and an index in the same # transaction. new_field = ForeignKey(Node, CASCADE, related_name="new_fk", null=True) new_field.set_attributes_from_name("new_parent_fk") parent = Node.objects.create() with connection.schema_editor() as editor: editor.add_field(Node, new_field) Node._meta.add_field(new_field) editor.execute("UPDATE schema_node SET new_parent_fk_id = %s;", [parent.pk]) editor.add_index( Node, Index(fields=["new_parent_fk"], name="new_parent_inline_fk_idx") ) self.assertIn("new_parent_fk_id", self.get_indexes(Node._meta.db_table)) @skipUnlessDBFeature("supports_foreign_keys") def test_char_field_with_db_index_to_fk(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorCharFieldWithIndex) # Change CharField to FK old_field = AuthorCharFieldWithIndex._meta.get_field("char_field") new_field = ForeignKey(Author, CASCADE, blank=True) new_field.set_attributes_from_name("char_field") with connection.schema_editor() as editor: editor.alter_field( AuthorCharFieldWithIndex, old_field, new_field, strict=True ) self.assertForeignKeyExists( AuthorCharFieldWithIndex, "char_field_id", "schema_author" ) @skipUnlessDBFeature("supports_foreign_keys") @skipUnlessDBFeature("supports_index_on_text_field") def test_text_field_with_db_index_to_fk(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorTextFieldWithIndex) # Change TextField to FK old_field = AuthorTextFieldWithIndex._meta.get_field("text_field") new_field = ForeignKey(Author, CASCADE, blank=True) new_field.set_attributes_from_name("text_field") with connection.schema_editor() as editor: editor.alter_field( AuthorTextFieldWithIndex, old_field, new_field, strict=True ) self.assertForeignKeyExists( AuthorTextFieldWithIndex, "text_field_id", "schema_author" ) @isolate_apps("schema") def test_char_field_pk_to_auto_field(self): class Foo(Model): id = CharField(max_length=255, primary_key=True) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Foo with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) @skipUnlessDBFeature("supports_foreign_keys") def test_fk_to_proxy(self): "Creating a FK to a proxy model creates database constraints." class AuthorProxy(Author): class Meta: app_label = "schema" apps = new_apps proxy = True class AuthorRef(Model): author = ForeignKey(AuthorProxy, on_delete=CASCADE) class Meta: app_label = "schema" apps = new_apps self.local_models = [AuthorProxy, AuthorRef] # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(AuthorRef) self.assertForeignKeyExists(AuthorRef, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys") def test_fk_db_constraint(self): "The db_constraint parameter is respected" # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Author) editor.create_model(BookWeak) # Initial tables are there list(Author.objects.all()) list(Tag.objects.all()) list(BookWeak.objects.all()) self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author") # Make a db_constraint=False FK new_field = ForeignKey(Tag, CASCADE, db_constraint=False) new_field.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.add_field(Author, new_field) self.assertForeignKeyNotExists(Author, "tag_id", "schema_tag") # Alter to one with a constraint new_field2 = ForeignKey(Tag, CASCADE) new_field2.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) self.assertForeignKeyExists(Author, "tag_id", "schema_tag") # Alter to one without a constraint again new_field2 = ForeignKey(Tag, CASCADE) new_field2.set_attributes_from_name("tag") with connection.schema_editor() as editor: editor.alter_field(Author, new_field2, new_field, strict=True) self.assertForeignKeyNotExists(Author, "tag_id", "schema_tag") @isolate_apps("schema") def test_no_db_constraint_added_during_primary_key_change(self): """ When a primary key that's pointed to by a ForeignKey with db_constraint=False is altered, a foreign key constraint isn't added. """ class Author(Model): class Meta: app_label = "schema" class BookWeak(Model): author = ForeignKey(Author, CASCADE, db_constraint=False) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWeak) self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author") old_field = Author._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.model = Author new_field.set_attributes_from_name("id") # @isolate_apps() and inner models are needed to have the model # relations populated, otherwise this doesn't act as a regression test. self.assertEqual(len(new_field.model._meta.related_objects), 1) with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertForeignKeyNotExists(BookWeak, "author_id", "schema_author") def _test_m2m_db_constraint(self, M2MFieldClass): class LocalAuthorWithM2M(Model): name = CharField(max_length=255) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorWithM2M] # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(LocalAuthorWithM2M) # Initial tables are there list(LocalAuthorWithM2M.objects.all()) list(Tag.objects.all()) # Make a db_constraint=False FK new_field = M2MFieldClass(Tag, related_name="authors", db_constraint=False) new_field.contribute_to_class(LocalAuthorWithM2M, "tags") # Add the field with connection.schema_editor() as editor: editor.add_field(LocalAuthorWithM2M, new_field) self.assertForeignKeyNotExists( new_field.remote_field.through, "tag_id", "schema_tag" ) @skipUnlessDBFeature("supports_foreign_keys") def test_m2m_db_constraint(self): self._test_m2m_db_constraint(ManyToManyField) @skipUnlessDBFeature("supports_foreign_keys") def test_m2m_db_constraint_custom(self): self._test_m2m_db_constraint(CustomManyToManyField) @skipUnlessDBFeature("supports_foreign_keys") def test_m2m_db_constraint_inherited(self): self._test_m2m_db_constraint(InheritedManyToManyField) def test_add_field(self): """ Tests adding fields to models """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add the new field new_field = IntegerField(null=True) new_field.set_attributes_from_name("age") with CaptureQueriesContext( connection ) as ctx, connection.schema_editor() as editor: editor.add_field(Author, new_field) drop_default_sql = editor.sql_alter_column_no_default % { "column": editor.quote_name(new_field.name), } self.assertFalse( any(drop_default_sql in query["sql"] for query in ctx.captured_queries) ) # Table is not rebuilt. self.assertIs( any("CREATE TABLE" in query["sql"] for query in ctx.captured_queries), False ) self.assertIs( any("DROP TABLE" in query["sql"] for query in ctx.captured_queries), False ) columns = self.column_classes(Author) self.assertEqual( columns["age"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertTrue(columns["age"][1][6]) def test_add_field_remove_field(self): """ Adding a field and removing it removes all deferred sql referring to it. """ with connection.schema_editor() as editor: # Create a table with a unique constraint on the slug field. editor.create_model(Tag) # Remove the slug column. editor.remove_field(Tag, Tag._meta.get_field("slug")) self.assertEqual(editor.deferred_sql, []) def test_add_field_temp_default(self): """ Tests adding fields to models with a temporary default """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = CharField(max_length=30, default="Godwin") new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertEqual( columns["surname"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual( columns["surname"][1][6], connection.features.interprets_empty_strings_as_nulls, ) def test_add_field_temp_default_boolean(self): """ Tests adding fields to models with a temporary default where the default is False. (#21783) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no age field columns = self.column_classes(Author) self.assertNotIn("age", columns) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add a not-null field new_field = BooleanField(default=False) new_field.set_attributes_from_name("awesome") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) # BooleanField are stored as TINYINT(1) on MySQL. field_type = columns["awesome"][0] self.assertEqual( field_type, connection.features.introspected_field_types["BooleanField"] ) def test_add_field_default_transform(self): """ Tests adding fields to models with a default that is not directly valid in the database (#22581) """ class TestTransformField(IntegerField): # Weird field that saves the count of items in its value def get_default(self): return self.default def get_prep_value(self, value): if value is None: return 0 return len(value) # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add some rows of data Author.objects.create(name="Andrew", height=30) Author.objects.create(name="Andrea") # Add the field with a default it needs to cast (to string in this case) new_field = TestTransformField(default={1: 2}) new_field.set_attributes_from_name("thing") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure the field is there columns = self.column_classes(Author) field_type, field_info = columns["thing"] self.assertEqual( field_type, connection.features.introspected_field_types["IntegerField"] ) # Make sure the values were transformed correctly self.assertEqual(Author.objects.extra(where=["thing = 1"]).count(), 2) def test_add_field_o2o_nullable(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Note) new_field = OneToOneField(Note, CASCADE, null=True) new_field.set_attributes_from_name("note") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertIn("note_id", columns) self.assertTrue(columns["note_id"][1][6]) def test_add_field_binary(self): """ Tests binary fields get a sane default (#22851) """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add the new field new_field = BinaryField(blank=True) new_field.set_attributes_from_name("bits") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) # MySQL annoyingly uses the same backend, so it'll come back as one of # these two types. self.assertIn(columns["bits"][0], ("BinaryField", "TextField")) def test_add_field_durationfield_with_default(self): with connection.schema_editor() as editor: editor.create_model(Author) new_field = DurationField(default=datetime.timedelta(minutes=10)) new_field.set_attributes_from_name("duration") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertEqual( columns["duration"][0], connection.features.introspected_field_types["DurationField"], ) @unittest.skipUnless(connection.vendor == "mysql", "MySQL specific") def test_add_binaryfield_mediumblob(self): """ Test adding a custom-sized binary field on MySQL (#24846). """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Add the new field with default new_field = MediumBlobField(blank=True, default=b"123") new_field.set_attributes_from_name("bits") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) # Introspection treats BLOBs as TextFields self.assertEqual(columns["bits"][0], "TextField") def test_remove_field(self): with connection.schema_editor() as editor: editor.create_model(Author) with CaptureQueriesContext(connection) as ctx: editor.remove_field(Author, Author._meta.get_field("name")) columns = self.column_classes(Author) self.assertNotIn("name", columns) if getattr(connection.features, "can_alter_table_drop_column", True): # Table is not rebuilt. self.assertIs( any("CREATE TABLE" in query["sql"] for query in ctx.captured_queries), False, ) self.assertIs( any("DROP TABLE" in query["sql"] for query in ctx.captured_queries), False, ) def test_alter(self): """ Tests simple altering of fields """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual( bool(columns["name"][1][6]), bool(connection.features.interprets_empty_strings_as_nulls), ) # Alter the name field to a TextField old_field = Author._meta.get_field("name") new_field = TextField(null=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) self.assertEqual(columns["name"][0], "TextField") self.assertTrue(columns["name"][1][6]) # Change nullability again new_field2 = TextField(null=False) new_field2.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) columns = self.column_classes(Author) self.assertEqual(columns["name"][0], "TextField") self.assertEqual( bool(columns["name"][1][6]), bool(connection.features.interprets_empty_strings_as_nulls), ) def test_alter_auto_field_to_integer_field(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change AutoField to IntegerField old_field = Author._meta.get_field("id") new_field = IntegerField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # Now that ID is an IntegerField, the database raises an error if it # isn't provided. if not connection.features.supports_unspecified_pk: with self.assertRaises(DatabaseError): Author.objects.create() def test_alter_auto_field_to_char_field(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change AutoField to CharField old_field = Author._meta.get_field("id") new_field = CharField(primary_key=True, max_length=50) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) @isolate_apps("schema") def test_alter_auto_field_quoted_db_column(self): class Foo(Model): id = AutoField(primary_key=True, db_column='"quoted_id"') class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.model = Foo new_field.db_column = '"quoted_id"' new_field.set_attributes_from_name("id") with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) Foo.objects.create() def test_alter_not_unique_field_to_primary_key(self): # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) # Change UUIDField to primary key. old_field = Author._meta.get_field("uuid") new_field = UUIDField(primary_key=True) new_field.set_attributes_from_name("uuid") new_field.model = Author with connection.schema_editor() as editor: editor.remove_field(Author, Author._meta.get_field("id")) editor.alter_field(Author, old_field, new_field, strict=True) # Redundant unique constraint is not added. count = self.get_constraints_count( Author._meta.db_table, Author._meta.get_field("uuid").column, None, ) self.assertLessEqual(count["uniques"], 1) @isolate_apps("schema") def test_alter_primary_key_quoted_db_table(self): class Foo(Model): class Meta: app_label = "schema" db_table = '"foo"' with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.model = Foo new_field.set_attributes_from_name("id") with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) Foo.objects.create() def test_alter_text_field(self): # Regression for "BLOB/TEXT column 'info' can't have a default value") # on MySQL. # Create the table with connection.schema_editor() as editor: editor.create_model(Note) old_field = Note._meta.get_field("info") new_field = TextField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) def test_alter_text_field_to_not_null_with_default_value(self): with connection.schema_editor() as editor: editor.create_model(Note) old_field = Note._meta.get_field("address") new_field = TextField(blank=True, default="", null=False) new_field.set_attributes_from_name("address") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) @skipUnlessDBFeature("can_defer_constraint_checks", "can_rollback_ddl") def test_alter_fk_checks_deferred_constraints(self): """ #25492 - Altering a foreign key's structure and data in the same transaction. """ with connection.schema_editor() as editor: editor.create_model(Node) old_field = Node._meta.get_field("parent") new_field = ForeignKey(Node, CASCADE) new_field.set_attributes_from_name("parent") parent = Node.objects.create() with connection.schema_editor() as editor: # Update the parent FK to create a deferred constraint check. Node.objects.update(parent=parent) editor.alter_field(Node, old_field, new_field, strict=True) def test_alter_text_field_to_date_field(self): """ #25002 - Test conversion of text field to date field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info="1988-05-05") old_field = Note._meta.get_field("info") new_field = DateField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns["info"][1][6]) def test_alter_text_field_to_datetime_field(self): """ #25002 - Test conversion of text field to datetime field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info="1988-05-05 3:16:17.4567") old_field = Note._meta.get_field("info") new_field = DateTimeField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns["info"][1][6]) def test_alter_text_field_to_time_field(self): """ #25002 - Test conversion of text field to time field. """ with connection.schema_editor() as editor: editor.create_model(Note) Note.objects.create(info="3:16:17.4567") old_field = Note._meta.get_field("info") new_field = TimeField(blank=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) # Make sure the field isn't nullable columns = self.column_classes(Note) self.assertFalse(columns["info"][1][6]) @skipIfDBFeature("interprets_empty_strings_as_nulls") def test_alter_textual_field_keep_null_status(self): """ Changing a field type shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(Note) with self.assertRaises(IntegrityError): Note.objects.create(info=None) old_field = Note._meta.get_field("info") new_field = CharField(max_length=50) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) with self.assertRaises(IntegrityError): Note.objects.create(info=None) @skipUnlessDBFeature("interprets_empty_strings_as_nulls") def test_alter_textual_field_not_null_to_null(self): """ Nullability for textual fields is preserved on databases that interpret empty strings as NULLs. """ with connection.schema_editor() as editor: editor.create_model(Author) columns = self.column_classes(Author) # Field is nullable. self.assertTrue(columns["uuid"][1][6]) # Change to NOT NULL. old_field = Author._meta.get_field("uuid") new_field = SlugField(null=False, blank=True) new_field.set_attributes_from_name("uuid") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) # Nullability is preserved. self.assertTrue(columns["uuid"][1][6]) def test_alter_numeric_field_keep_null_status(self): """ Changing a field type shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(UniqueTest) with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=None, slug="aaa") old_field = UniqueTest._meta.get_field("year") new_field = BigIntegerField() new_field.set_attributes_from_name("year") with connection.schema_editor() as editor: editor.alter_field(UniqueTest, old_field, new_field, strict=True) with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=None, slug="bbb") def test_alter_null_to_not_null(self): """ #23609 - Tests handling of default values when altering from NULL to NOT NULL. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertTrue(columns["height"][1][6]) # Create some test data Author.objects.create(name="Not null author", height=12) Author.objects.create(name="Null author") # Verify null value self.assertEqual(Author.objects.get(name="Not null author").height, 12) self.assertIsNone(Author.objects.get(name="Null author").height) # Alter the height field to NOT NULL with default old_field = Author._meta.get_field("height") new_field = PositiveIntegerField(default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) self.assertFalse(columns["height"][1][6]) # Verify default value self.assertEqual(Author.objects.get(name="Not null author").height, 12) self.assertEqual(Author.objects.get(name="Null author").height, 42) def test_alter_charfield_to_null(self): """ #24307 - Should skip an alter statement on databases with interprets_empty_strings_as_nulls when changing a CharField to null. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Change the CharField to null old_field = Author._meta.get_field("name") new_field = copy(old_field) new_field.null = True with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_char_field_decrease_length(self): # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) Author.objects.create(name="x" * 255) # Change max_length of CharField. old_field = Author._meta.get_field("name") new_field = CharField(max_length=254) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: msg = "value too long for type character varying(254)" with self.assertRaisesMessage(DataError, msg): editor.alter_field(Author, old_field, new_field, strict=True) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_with_custom_db_type(self): from django.contrib.postgres.fields import ArrayField class Foo(Model): field = ArrayField(CharField(max_length=255)) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Foo) self.isolated_local_models = [Foo] old_field = Foo._meta.get_field("field") new_field = ArrayField(CharField(max_length=16)) new_field.set_attributes_from_name("field") new_field.model = Foo with connection.schema_editor() as editor: editor.alter_field(Foo, old_field, new_field, strict=True) @isolate_apps("schema") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_array_field_decrease_base_field_length(self): from django.contrib.postgres.fields import ArrayField class ArrayModel(Model): field = ArrayField(CharField(max_length=16)) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(ArrayModel) self.isolated_local_models = [ArrayModel] ArrayModel.objects.create(field=["x" * 16]) old_field = ArrayModel._meta.get_field("field") new_field = ArrayField(CharField(max_length=15)) new_field.set_attributes_from_name("field") new_field.model = ArrayModel with connection.schema_editor() as editor: msg = "value too long for type character varying(15)" with self.assertRaisesMessage(DataError, msg): editor.alter_field(ArrayModel, old_field, new_field, strict=True) @isolate_apps("schema") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_array_field_decrease_nested_base_field_length(self): from django.contrib.postgres.fields import ArrayField class ArrayModel(Model): field = ArrayField(ArrayField(CharField(max_length=16))) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(ArrayModel) self.isolated_local_models = [ArrayModel] ArrayModel.objects.create(field=[["x" * 16]]) old_field = ArrayModel._meta.get_field("field") new_field = ArrayField(ArrayField(CharField(max_length=15))) new_field.set_attributes_from_name("field") new_field.model = ArrayModel with connection.schema_editor() as editor: msg = "value too long for type character varying(15)" with self.assertRaisesMessage(DataError, msg): editor.alter_field(ArrayModel, old_field, new_field, strict=True) def test_alter_textfield_to_null(self): """ #24307 - Should skip an alter statement on databases with interprets_empty_strings_as_nulls when changing a TextField to null. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Note) # Change the TextField to null old_field = Note._meta.get_field("info") new_field = copy(old_field) new_field.null = True with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) def test_alter_null_to_not_null_keeping_default(self): """ #23738 - Can change a nullable field with default to non-nullable with the same default. """ # Create the table with connection.schema_editor() as editor: editor.create_model(AuthorWithDefaultHeight) # Ensure the field is right to begin with columns = self.column_classes(AuthorWithDefaultHeight) self.assertTrue(columns["height"][1][6]) # Alter the height field to NOT NULL keeping the previous default old_field = AuthorWithDefaultHeight._meta.get_field("height") new_field = PositiveIntegerField(default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field( AuthorWithDefaultHeight, old_field, new_field, strict=True ) columns = self.column_classes(AuthorWithDefaultHeight) self.assertFalse(columns["height"][1][6]) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_fk(self): """ Tests altering of FKs """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the field is right to begin with columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertForeignKeyExists(Book, "author_id", "schema_author") # Alter the FK old_field = Book._meta.get_field("author") new_field = ForeignKey(Author, CASCADE, editable=False) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertForeignKeyExists(Book, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys") def test_alter_to_fk(self): """ #24447 - Tests adding a FK constraint for an existing column """ class LocalBook(Model): author = IntegerField() title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalBook] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalBook) # Ensure no FK constraint exists constraints = self.get_constraints(LocalBook._meta.db_table) for details in constraints.values(): if details["foreign_key"]: self.fail( "Found an unexpected FK constraint to %s" % details["columns"] ) old_field = LocalBook._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(LocalBook, old_field, new_field, strict=True) self.assertForeignKeyExists(LocalBook, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys") def test_alter_o2o_to_fk(self): """ #24163 - Tests altering of OneToOneField to ForeignKey """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) # Ensure the field is right to begin with columns = self.column_classes(BookWithO2O) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is unique author = Author.objects.create(name="Joe") BookWithO2O.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) with self.assertRaises(IntegrityError): BookWithO2O.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) BookWithO2O.objects.all().delete() self.assertForeignKeyExists(BookWithO2O, "author_id", "schema_author") # Alter the OneToOneField to ForeignKey old_field = BookWithO2O._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is not unique anymore Book.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) Book.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) self.assertForeignKeyExists(Book, "author_id", "schema_author") @skipUnlessDBFeature("supports_foreign_keys") def test_alter_fk_to_o2o(self): """ #24163 - Tests altering of ForeignKey to OneToOneField """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the field is right to begin with columns = self.column_classes(Book) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is not unique author = Author.objects.create(name="Joe") Book.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) Book.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) Book.objects.all().delete() self.assertForeignKeyExists(Book, "author_id", "schema_author") # Alter the ForeignKey to OneToOneField old_field = Book._meta.get_field("author") new_field = OneToOneField(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) columns = self.column_classes(BookWithO2O) self.assertEqual( columns["author_id"][0], connection.features.introspected_field_types["IntegerField"], ) # Ensure the field is unique now BookWithO2O.objects.create( author=author, title="Django 1", pub_date=datetime.datetime.now() ) with self.assertRaises(IntegrityError): BookWithO2O.objects.create( author=author, title="Django 2", pub_date=datetime.datetime.now() ) self.assertForeignKeyExists(BookWithO2O, "author_id", "schema_author") def test_alter_field_fk_to_o2o(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) expected_fks = 1 if connection.features.supports_foreign_keys else 0 expected_indexes = 1 if connection.features.indexes_foreign_keys else 0 # Check the index is right to begin with. counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual( counts, {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes}, ) old_field = Book._meta.get_field("author") new_field = OneToOneField(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The index on ForeignKey is replaced with a unique constraint for # OneToOneField. self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) def test_alter_field_fk_keeps_index(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) expected_fks = 1 if connection.features.supports_foreign_keys else 0 expected_indexes = 1 if connection.features.indexes_foreign_keys else 0 # Check the index is right to begin with. counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual( counts, {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes}, ) old_field = Book._meta.get_field("author") # on_delete changed from CASCADE. new_field = ForeignKey(Author, PROTECT) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) counts = self.get_constraints_count( Book._meta.db_table, Book._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The index remains. self.assertEqual( counts, {"fks": expected_fks, "uniques": 0, "indexes": expected_indexes}, ) def test_alter_field_o2o_to_fk(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) expected_fks = 1 if connection.features.supports_foreign_keys else 0 # Check the unique constraint is right to begin with. counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) old_field = BookWithO2O._meta.get_field("author") new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The unique constraint on OneToOneField is replaced with an index for # ForeignKey. self.assertEqual(counts, {"fks": expected_fks, "uniques": 0, "indexes": 1}) def test_alter_field_o2o_keeps_unique(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithO2O) expected_fks = 1 if connection.features.supports_foreign_keys else 0 # Check the unique constraint is right to begin with. counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) old_field = BookWithO2O._meta.get_field("author") # on_delete changed from CASCADE. new_field = OneToOneField(Author, PROTECT) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.alter_field(BookWithO2O, old_field, new_field, strict=True) counts = self.get_constraints_count( BookWithO2O._meta.db_table, BookWithO2O._meta.get_field("author").column, (Author._meta.db_table, Author._meta.pk.column), ) # The unique constraint remains. self.assertEqual(counts, {"fks": expected_fks, "uniques": 1, "indexes": 0}) @skipUnlessDBFeature("ignores_table_name_case") def test_alter_db_table_case(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Alter the case of the table old_table_name = Author._meta.db_table with connection.schema_editor() as editor: editor.alter_db_table(Author, old_table_name, old_table_name.upper()) def test_alter_implicit_id_to_explicit(self): """ Should be able to convert an implicit "id" field to an explicit "id" primary key field. """ with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) # This will fail if DROP DEFAULT is inadvertently executed on this # field which drops the id sequence, at least on PostgreSQL. Author.objects.create(name="Foo") Author.objects.create(name="Bar") def test_alter_autofield_pk_to_bigautofield_pk_sequence_owner(self): """ Converting an implicit PK to BigAutoField(primary_key=True) should keep a sequence owner on PostgreSQL. """ with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("id") new_field = BigAutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) Author.objects.create(name="Foo", pk=1) with connection.cursor() as cursor: sequence_reset_sqls = connection.ops.sequence_reset_sql( no_style(), [Author] ) if sequence_reset_sqls: cursor.execute(sequence_reset_sqls[0]) # Fail on PostgreSQL if sequence is missing an owner. self.assertIsNotNone(Author.objects.create(name="Bar")) def test_alter_autofield_pk_to_smallautofield_pk_sequence_owner(self): """ Converting an implicit PK to SmallAutoField(primary_key=True) should keep a sequence owner on PostgreSQL. """ with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("id") new_field = SmallAutoField(primary_key=True) new_field.set_attributes_from_name("id") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) Author.objects.create(name="Foo", pk=1) with connection.cursor() as cursor: sequence_reset_sqls = connection.ops.sequence_reset_sql( no_style(), [Author] ) if sequence_reset_sqls: cursor.execute(sequence_reset_sqls[0]) # Fail on PostgreSQL if sequence is missing an owner. self.assertIsNotNone(Author.objects.create(name="Bar")) def test_alter_int_pk_to_autofield_pk(self): """ Should be able to rename an IntegerField(primary_key=True) to AutoField(primary_key=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) old_field = IntegerPK._meta.get_field("i") new_field = AutoField(primary_key=True) new_field.model = IntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) # A model representing the updated model. class IntegerPKToAutoField(Model): i = AutoField(primary_key=True) j = IntegerField(unique=True) class Meta: app_label = "schema" apps = new_apps db_table = IntegerPK._meta.db_table # An id (i) is generated by the database. obj = IntegerPKToAutoField.objects.create(j=1) self.assertIsNotNone(obj.i) def test_alter_int_pk_to_bigautofield_pk(self): """ Should be able to rename an IntegerField(primary_key=True) to BigAutoField(primary_key=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) old_field = IntegerPK._meta.get_field("i") new_field = BigAutoField(primary_key=True) new_field.model = IntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) # A model representing the updated model. class IntegerPKToBigAutoField(Model): i = BigAutoField(primary_key=True) j = IntegerField(unique=True) class Meta: app_label = "schema" apps = new_apps db_table = IntegerPK._meta.db_table # An id (i) is generated by the database. obj = IntegerPKToBigAutoField.objects.create(j=1) self.assertIsNotNone(obj.i) @isolate_apps("schema") def test_alter_smallint_pk_to_smallautofield_pk(self): """ Should be able to rename an SmallIntegerField(primary_key=True) to SmallAutoField(primary_key=True). """ class SmallIntegerPK(Model): i = SmallIntegerField(primary_key=True) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(SmallIntegerPK) self.isolated_local_models = [SmallIntegerPK] old_field = SmallIntegerPK._meta.get_field("i") new_field = SmallAutoField(primary_key=True) new_field.model = SmallIntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(SmallIntegerPK, old_field, new_field, strict=True) def test_alter_int_pk_to_int_unique(self): """ Should be able to rename an IntegerField(primary_key=True) to IntegerField(unique=True). """ with connection.schema_editor() as editor: editor.create_model(IntegerPK) # Delete the old PK old_field = IntegerPK._meta.get_field("i") new_field = IntegerField(unique=True) new_field.model = IntegerPK new_field.set_attributes_from_name("i") with connection.schema_editor() as editor: editor.alter_field(IntegerPK, old_field, new_field, strict=True) # The primary key constraint is gone. Result depends on database: # 'id' for SQLite, None for others (must not be 'i'). self.assertIn(self.get_primary_key(IntegerPK._meta.db_table), ("id", None)) # Set up a model class as it currently stands. The original IntegerPK # class is now out of date and some backends make use of the whole # model class when modifying a field (such as sqlite3 when remaking a # table) so an outdated model class leads to incorrect results. class Transitional(Model): i = IntegerField(unique=True) j = IntegerField(unique=True) class Meta: app_label = "schema" apps = new_apps db_table = "INTEGERPK" # model requires a new PK old_field = Transitional._meta.get_field("j") new_field = IntegerField(primary_key=True) new_field.model = Transitional new_field.set_attributes_from_name("j") with connection.schema_editor() as editor: editor.alter_field(Transitional, old_field, new_field, strict=True) # Create a model class representing the updated model. class IntegerUnique(Model): i = IntegerField(unique=True) j = IntegerField(primary_key=True) class Meta: app_label = "schema" apps = new_apps db_table = "INTEGERPK" # Ensure unique constraint works. IntegerUnique.objects.create(i=1, j=1) with self.assertRaises(IntegrityError): IntegerUnique.objects.create(i=1, j=2) def test_rename(self): """ Tests simple altering of fields """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the field is right to begin with columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) self.assertNotIn("display_name", columns) # Alter the name field's name old_field = Author._meta.get_field("name") new_field = CharField(max_length=254) new_field.set_attributes_from_name("display_name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) columns = self.column_classes(Author) self.assertEqual( columns["display_name"][0], connection.features.introspected_field_types["CharField"], ) self.assertNotIn("name", columns) @isolate_apps("schema") def test_rename_referenced_field(self): class Author(Model): name = CharField(max_length=255, unique=True) class Meta: app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE, to_field="name") class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("renamed") with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: editor.alter_field(Author, Author._meta.get_field("name"), new_field) # Ensure the foreign key reference was updated. self.assertForeignKeyExists(Book, "author_id", "schema_author", "renamed") @skipIfDBFeature("interprets_empty_strings_as_nulls") def test_rename_keep_null_status(self): """ Renaming a field shouldn't affect the not null status. """ with connection.schema_editor() as editor: editor.create_model(Note) with self.assertRaises(IntegrityError): Note.objects.create(info=None) old_field = Note._meta.get_field("info") new_field = TextField() new_field.set_attributes_from_name("detail_info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) columns = self.column_classes(Note) self.assertEqual(columns["detail_info"][0], "TextField") self.assertNotIn("info", columns) with self.assertRaises(IntegrityError): NoteRename.objects.create(detail_info=None) def _test_m2m_create(self, M2MFieldClass): """ Tests M2M fields on models during creation """ class LocalBookWithM2M(Model): author = ForeignKey(Author, CASCADE) title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() tags = M2MFieldClass("TagM2MTest", related_name="books") class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalBookWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(TagM2MTest) editor.create_model(LocalBookWithM2M) # Ensure there is now an m2m table there columns = self.column_classes( LocalBookWithM2M._meta.get_field("tags").remote_field.through ) self.assertEqual( columns["tagm2mtest_id"][0], connection.features.introspected_field_types["IntegerField"], ) def test_m2m_create(self): self._test_m2m_create(ManyToManyField) def test_m2m_create_custom(self): self._test_m2m_create(CustomManyToManyField) def test_m2m_create_inherited(self): self._test_m2m_create(InheritedManyToManyField) def _test_m2m_create_through(self, M2MFieldClass): """ Tests M2M fields on models during creation with through models """ class LocalTagThrough(Model): book = ForeignKey("schema.LocalBookWithM2MThrough", CASCADE) tag = ForeignKey("schema.TagM2MTest", CASCADE) class Meta: app_label = "schema" apps = new_apps class LocalBookWithM2MThrough(Model): tags = M2MFieldClass( "TagM2MTest", related_name="books", through=LocalTagThrough ) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalTagThrough, LocalBookWithM2MThrough] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalTagThrough) editor.create_model(TagM2MTest) editor.create_model(LocalBookWithM2MThrough) # Ensure there is now an m2m table there columns = self.column_classes(LocalTagThrough) self.assertEqual( columns["book_id"][0], connection.features.introspected_field_types["IntegerField"], ) self.assertEqual( columns["tag_id"][0], connection.features.introspected_field_types["IntegerField"], ) def test_m2m_create_through(self): self._test_m2m_create_through(ManyToManyField) def test_m2m_create_through_custom(self): self._test_m2m_create_through(CustomManyToManyField) def test_m2m_create_through_inherited(self): self._test_m2m_create_through(InheritedManyToManyField) def test_m2m_through_remove(self): class LocalAuthorNoteThrough(Model): book = ForeignKey("schema.Author", CASCADE) tag = ForeignKey("self", CASCADE) class Meta: app_label = "schema" apps = new_apps class LocalNoteWithM2MThrough(Model): authors = ManyToManyField("schema.Author", through=LocalAuthorNoteThrough) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorNoteThrough, LocalNoteWithM2MThrough] # Create the tables. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalAuthorNoteThrough) editor.create_model(LocalNoteWithM2MThrough) # Remove the through parameter. old_field = LocalNoteWithM2MThrough._meta.get_field("authors") new_field = ManyToManyField("Author") new_field.set_attributes_from_name("authors") msg = ( f"Cannot alter field {old_field} into {new_field} - they are not " f"compatible types (you cannot alter to or from M2M fields, or add or " f"remove through= on M2M fields)" ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): editor.alter_field(LocalNoteWithM2MThrough, old_field, new_field) def _test_m2m(self, M2MFieldClass): """ Tests adding/removing M2M fields on models """ class LocalAuthorWithM2M(Model): name = CharField(max_length=255) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalAuthorWithM2M) editor.create_model(TagM2MTest) # Create an M2M field new_field = M2MFieldClass("schema.TagM2MTest", related_name="authors") new_field.contribute_to_class(LocalAuthorWithM2M, "tags") # Ensure there's no m2m table there with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Add the field with connection.schema_editor() as editor: editor.add_field(LocalAuthorWithM2M, new_field) # Ensure there is now an m2m table there columns = self.column_classes(new_field.remote_field.through) self.assertEqual( columns["tagm2mtest_id"][0], connection.features.introspected_field_types["IntegerField"], ) # "Alter" the field. This should not rename the DB table to itself. with connection.schema_editor() as editor: editor.alter_field(LocalAuthorWithM2M, new_field, new_field, strict=True) # Remove the M2M table again with connection.schema_editor() as editor: editor.remove_field(LocalAuthorWithM2M, new_field) # Ensure there's no m2m table there with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Make sure the model state is coherent with the table one now that # we've removed the tags field. opts = LocalAuthorWithM2M._meta opts.local_many_to_many.remove(new_field) del new_apps.all_models["schema"][ new_field.remote_field.through._meta.model_name ] opts._expire_cache() def test_m2m(self): self._test_m2m(ManyToManyField) def test_m2m_custom(self): self._test_m2m(CustomManyToManyField) def test_m2m_inherited(self): self._test_m2m(InheritedManyToManyField) def _test_m2m_through_alter(self, M2MFieldClass): """ Tests altering M2Ms with explicit through models (should no-op) """ class LocalAuthorTag(Model): author = ForeignKey("schema.LocalAuthorWithM2MThrough", CASCADE) tag = ForeignKey("schema.TagM2MTest", CASCADE) class Meta: app_label = "schema" apps = new_apps class LocalAuthorWithM2MThrough(Model): name = CharField(max_length=255) tags = M2MFieldClass( "schema.TagM2MTest", related_name="authors", through=LocalAuthorTag ) class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalAuthorTag, LocalAuthorWithM2MThrough] # Create the tables with connection.schema_editor() as editor: editor.create_model(LocalAuthorTag) editor.create_model(LocalAuthorWithM2MThrough) editor.create_model(TagM2MTest) # Ensure the m2m table is there self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3) # "Alter" the field's blankness. This should not actually do anything. old_field = LocalAuthorWithM2MThrough._meta.get_field("tags") new_field = M2MFieldClass( "schema.TagM2MTest", related_name="authors", through=LocalAuthorTag ) new_field.contribute_to_class(LocalAuthorWithM2MThrough, "tags") with connection.schema_editor() as editor: editor.alter_field( LocalAuthorWithM2MThrough, old_field, new_field, strict=True ) # Ensure the m2m table is still there self.assertEqual(len(self.column_classes(LocalAuthorTag)), 3) def test_m2m_through_alter(self): self._test_m2m_through_alter(ManyToManyField) def test_m2m_through_alter_custom(self): self._test_m2m_through_alter(CustomManyToManyField) def test_m2m_through_alter_inherited(self): self._test_m2m_through_alter(InheritedManyToManyField) def _test_m2m_repoint(self, M2MFieldClass): """ Tests repointing M2M fields """ class LocalBookWithM2M(Model): author = ForeignKey(Author, CASCADE) title = CharField(max_length=100, db_index=True) pub_date = DateTimeField() tags = M2MFieldClass("TagM2MTest", related_name="books") class Meta: app_label = "schema" apps = new_apps self.local_models = [LocalBookWithM2M] # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(LocalBookWithM2M) editor.create_model(TagM2MTest) editor.create_model(UniqueTest) # Ensure the M2M exists and points to TagM2MTest if connection.features.supports_foreign_keys: self.assertForeignKeyExists( LocalBookWithM2M._meta.get_field("tags").remote_field.through, "tagm2mtest_id", "schema_tagm2mtest", ) # Repoint the M2M old_field = LocalBookWithM2M._meta.get_field("tags") new_field = M2MFieldClass(UniqueTest) new_field.contribute_to_class(LocalBookWithM2M, "uniques") with connection.schema_editor() as editor: editor.alter_field(LocalBookWithM2M, old_field, new_field, strict=True) # Ensure old M2M is gone with self.assertRaises(DatabaseError): self.column_classes( LocalBookWithM2M._meta.get_field("tags").remote_field.through ) # This model looks like the new model and is used for teardown. opts = LocalBookWithM2M._meta opts.local_many_to_many.remove(old_field) # Ensure the new M2M exists and points to UniqueTest if connection.features.supports_foreign_keys: self.assertForeignKeyExists( new_field.remote_field.through, "uniquetest_id", "schema_uniquetest" ) def test_m2m_repoint(self): self._test_m2m_repoint(ManyToManyField) def test_m2m_repoint_custom(self): self._test_m2m_repoint(CustomManyToManyField) def test_m2m_repoint_inherited(self): self._test_m2m_repoint(InheritedManyToManyField) @isolate_apps("schema") def test_m2m_rename_field_in_target_model(self): class LocalTagM2MTest(Model): title = CharField(max_length=255) class Meta: app_label = "schema" class LocalM2M(Model): tags = ManyToManyField(LocalTagM2MTest) class Meta: app_label = "schema" # Create the tables. with connection.schema_editor() as editor: editor.create_model(LocalM2M) editor.create_model(LocalTagM2MTest) self.isolated_local_models = [LocalM2M, LocalTagM2MTest] # Ensure the m2m table is there. self.assertEqual(len(self.column_classes(LocalM2M)), 1) # Alter a field in LocalTagM2MTest. old_field = LocalTagM2MTest._meta.get_field("title") new_field = CharField(max_length=254) new_field.contribute_to_class(LocalTagM2MTest, "title1") # @isolate_apps() and inner models are needed to have the model # relations populated, otherwise this doesn't act as a regression test. self.assertEqual(len(new_field.model._meta.related_objects), 1) with connection.schema_editor() as editor: editor.alter_field(LocalTagM2MTest, old_field, new_field, strict=True) # Ensure the m2m table is still there. self.assertEqual(len(self.column_classes(LocalM2M)), 1) @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) def test_check_constraints(self): """ Tests creating/deleting CHECK constraints """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the constraint exists constraints = self.get_constraints(Author._meta.db_table) if not any( details["columns"] == ["height"] and details["check"] for details in constraints.values() ): self.fail("No check constraint for height found") # Alter the column to remove it old_field = Author._meta.get_field("height") new_field = IntegerField(null=True, blank=True) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) constraints = self.get_constraints(Author._meta.db_table) for details in constraints.values(): if details["columns"] == ["height"] and details["check"]: self.fail("Check constraint for height found") # Alter the column to re-add it new_field2 = Author._meta.get_field("height") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) constraints = self.get_constraints(Author._meta.db_table) if not any( details["columns"] == ["height"] and details["check"] for details in constraints.values() ): self.fail("No check constraint for height found") @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) @isolate_apps("schema") def test_check_constraint_timedelta_param(self): class DurationModel(Model): duration = DurationField() class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(DurationModel) self.isolated_local_models = [DurationModel] constraint_name = "duration_gte_5_minutes" constraint = CheckConstraint( check=Q(duration__gt=datetime.timedelta(minutes=5)), name=constraint_name, ) DurationModel._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(DurationModel, constraint) constraints = self.get_constraints(DurationModel._meta.db_table) self.assertIn(constraint_name, constraints) with self.assertRaises(IntegrityError), atomic(): DurationModel.objects.create(duration=datetime.timedelta(minutes=4)) DurationModel.objects.create(duration=datetime.timedelta(minutes=10)) @skipUnlessDBFeature( "supports_column_check_constraints", "can_introspect_check_constraints" ) def test_remove_field_check_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add the custom check constraint constraint = CheckConstraint( check=Q(height__gte=0), name="author_height_gte_0_check" ) custom_constraint_name = constraint.name Author._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) # Ensure the constraints exist constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["height"] and details["check"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Alter the column to remove field check old_field = Author._meta.get_field("height") new_field = IntegerField(null=True, blank=True) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["height"] and details["check"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Alter the column to re-add field check new_field2 = Author._meta.get_field("height") with connection.schema_editor() as editor: editor.alter_field(Author, new_field, new_field2, strict=True) constraints = self.get_constraints(Author._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["height"] and details["check"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the check constraint with connection.schema_editor() as editor: Author._meta.constraints = [] editor.remove_constraint(Author, constraint) def test_unique(self): """ Tests removing and adding unique constraints to a single column. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure the field is unique to begin with Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Alter the slug field to be non-unique old_field = Tag._meta.get_field("slug") new_field = SlugField(unique=False) new_field.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, old_field, new_field, strict=True) # Ensure the field is no longer unique Tag.objects.create(title="foo", slug="foo") Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Alter the slug field to be unique new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field, new_field2, strict=True) # Ensure the field is unique again Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") Tag.objects.all().delete() # Rename the field new_field3 = SlugField(unique=True) new_field3.set_attributes_from_name("slug2") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field2, new_field3, strict=True) # Ensure the field is still unique TagUniqueRename.objects.create(title="foo", slug2="foo") with self.assertRaises(IntegrityError): TagUniqueRename.objects.create(title="bar", slug2="foo") Tag.objects.all().delete() def test_unique_name_quoting(self): old_table_name = TagUniqueRename._meta.db_table try: with connection.schema_editor() as editor: editor.create_model(TagUniqueRename) editor.alter_db_table(TagUniqueRename, old_table_name, "unique-table") TagUniqueRename._meta.db_table = "unique-table" # This fails if the unique index name isn't quoted. editor.alter_unique_together(TagUniqueRename, [], (("title", "slug2"),)) finally: TagUniqueRename._meta.db_table = old_table_name @isolate_apps("schema") @skipUnlessDBFeature("supports_foreign_keys") def test_unique_no_unnecessary_fk_drops(self): """ If AlterField isn't selective about dropping foreign key constraints when modifying a field with a unique constraint, the AlterField incorrectly drops and recreates the Book.author foreign key even though it doesn't restrict the field being changed (#29193). """ class Author(Model): name = CharField(max_length=254, unique=True) class Meta: app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) new_field = CharField(max_length=255, unique=True) new_field.model = Author new_field.set_attributes_from_name("name") with self.assertLogs("django.db.backends.schema", "DEBUG") as cm: with connection.schema_editor() as editor: editor.alter_field(Author, Author._meta.get_field("name"), new_field) # One SQL statement is executed to alter the field. self.assertEqual(len(cm.records), 1) @isolate_apps("schema") def test_unique_and_reverse_m2m(self): """ AlterField can modify a unique field when there's a reverse M2M relation on the model. """ class Tag(Model): title = CharField(max_length=255) slug = SlugField(unique=True) class Meta: app_label = "schema" class Book(Model): tags = ManyToManyField(Tag, related_name="books") class Meta: app_label = "schema" self.isolated_local_models = [Book._meta.get_field("tags").remote_field.through] with connection.schema_editor() as editor: editor.create_model(Tag) editor.create_model(Book) new_field = SlugField(max_length=75, unique=True) new_field.model = Tag new_field.set_attributes_from_name("slug") with self.assertLogs("django.db.backends.schema", "DEBUG") as cm: with connection.schema_editor() as editor: editor.alter_field(Tag, Tag._meta.get_field("slug"), new_field) # One SQL statement is executed to alter the field. self.assertEqual(len(cm.records), 1) # Ensure that the field is still unique. Tag.objects.create(title="foo", slug="foo") with self.assertRaises(IntegrityError): Tag.objects.create(title="bar", slug="foo") @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_field_unique_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithUniqueName) # Add the custom unique constraint constraint = UniqueConstraint(fields=["name"], name="author_name_uniq") custom_constraint_name = constraint.name AuthorWithUniqueName._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(AuthorWithUniqueName, constraint) # Ensure the constraints exist constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Alter the column to remove field uniqueness old_field = AuthorWithUniqueName._meta.get_field("name") new_field = CharField(max_length=255) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(AuthorWithUniqueName, old_field, new_field, strict=True) constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Alter the column to re-add field uniqueness new_field2 = AuthorWithUniqueName._meta.get_field("name") with connection.schema_editor() as editor: editor.alter_field(AuthorWithUniqueName, new_field, new_field2, strict=True) constraints = self.get_constraints(AuthorWithUniqueName._meta.db_table) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the unique constraint with connection.schema_editor() as editor: AuthorWithUniqueName._meta.constraints = [] editor.remove_constraint(AuthorWithUniqueName, constraint) def test_unique_together(self): """ Tests removing and adding unique_together constraints on a model. """ # Create the table with connection.schema_editor() as editor: editor.create_model(UniqueTest) # Ensure the fields are unique to begin with UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2011, slug="foo") UniqueTest.objects.create(year=2011, slug="bar") with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() # Alter the model to its non-unique-together companion with connection.schema_editor() as editor: editor.alter_unique_together( UniqueTest, UniqueTest._meta.unique_together, [] ) # Ensure the fields are no longer unique UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() # Alter it back new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_unique_together( UniqueTest, [], UniqueTest._meta.unique_together ) # Ensure the fields are unique again UniqueTest.objects.create(year=2012, slug="foo") with self.assertRaises(IntegrityError): UniqueTest.objects.create(year=2012, slug="foo") UniqueTest.objects.all().delete() def test_unique_together_with_fk(self): """ Tests removing and adding unique_together constraints that include a foreign key. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the fields are unique to begin with self.assertEqual(Book._meta.unique_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_unique_together(Book, [], [["author", "title"]]) # Alter it back with connection.schema_editor() as editor: editor.alter_unique_together(Book, [["author", "title"]], []) def test_unique_together_with_fk_with_existing_index(self): """ Tests removing and adding unique_together constraints that include a foreign key, where the foreign key is added after the model is created. """ # Create the tables with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithoutAuthor) new_field = ForeignKey(Author, CASCADE) new_field.set_attributes_from_name("author") editor.add_field(BookWithoutAuthor, new_field) # Ensure the fields aren't unique to begin with self.assertEqual(Book._meta.unique_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_unique_together(Book, [], [["author", "title"]]) # Alter it back with connection.schema_editor() as editor: editor.alter_unique_together(Book, [["author", "title"]], []) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_unique_together_does_not_remove_meta_constraints(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithUniqueNameAndBirthday) # Add the custom unique constraint constraint = UniqueConstraint( fields=["name", "birthday"], name="author_name_birthday_uniq" ) custom_constraint_name = constraint.name AuthorWithUniqueNameAndBirthday._meta.constraints = [constraint] with connection.schema_editor() as editor: editor.add_constraint(AuthorWithUniqueNameAndBirthday, constraint) # Ensure the constraints exist constraints = self.get_constraints( AuthorWithUniqueNameAndBirthday._meta.db_table ) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Remove unique together unique_together = AuthorWithUniqueNameAndBirthday._meta.unique_together with connection.schema_editor() as editor: editor.alter_unique_together( AuthorWithUniqueNameAndBirthday, unique_together, [] ) constraints = self.get_constraints( AuthorWithUniqueNameAndBirthday._meta.db_table ) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 0) # Re-add unique together with connection.schema_editor() as editor: editor.alter_unique_together( AuthorWithUniqueNameAndBirthday, [], unique_together ) constraints = self.get_constraints( AuthorWithUniqueNameAndBirthday._meta.db_table ) self.assertIn(custom_constraint_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["unique"] and name != custom_constraint_name ] self.assertEqual(len(other_constraints), 1) # Drop the unique constraint with connection.schema_editor() as editor: AuthorWithUniqueNameAndBirthday._meta.constraints = [] editor.remove_constraint(AuthorWithUniqueNameAndBirthday, constraint) def test_unique_constraint(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(fields=["name"], name="name_uq") # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table self.assertIs(sql.references_table(table), True) self.assertIs(sql.references_column(table, "name"), True) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(Upper("name").desc(), name="func_upper_uq") # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, constraint.name, ["DESC"]) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) # SQL contains a database function. self.assertIs(sql.references_column(table, "name"), True) self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql)) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_composite_func_unique_constraint(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithSlug) constraint = UniqueConstraint( Upper("title"), Lower("slug"), name="func_upper_lower_unq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(BookWithSlug, constraint) sql = constraint.create_sql(BookWithSlug, editor) table = BookWithSlug._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) # SQL contains database functions. self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "slug"), True) sql = str(sql) self.assertIn("UPPER(%s)" % editor.quote_name("title"), sql) self.assertIn("LOWER(%s)" % editor.quote_name("slug"), sql) self.assertLess(sql.index("UPPER"), sql.index("LOWER")) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(BookWithSlug, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_unique_constraint_field_and_expression(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint( F("height").desc(), "uuid", Lower("name").asc(), name="func_f_lower_field_unq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, constraint.name, ["DESC", "ASC", "ASC"]) constraints = self.get_constraints(table) self.assertIs(constraints[constraint.name]["unique"], True) self.assertEqual(len(constraints[constraint.name]["columns"]), 3) self.assertEqual(constraints[constraint.name]["columns"][1], "uuid") # SQL contains database functions and columns. self.assertIs(sql.references_column(table, "height"), True) self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "uuid"), True) self.assertIn("LOWER(%s)" % editor.quote_name("name"), str(sql)) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_partial_indexes") def test_func_unique_constraint_partial(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint( Upper("name"), name="func_upper_cond_weight_uq", condition=Q(weight__isnull=False), ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) self.assertIs(sql.references_column(table, "name"), True) self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql)) self.assertIn( "WHERE %s IS NOT NULL" % editor.quote_name("weight"), str(sql), ) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_covering_indexes") def test_func_unique_constraint_covering(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint( Upper("name"), name="func_upper_covering_uq", include=["weight", "height"], ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) self.assertEqual( constraints[constraint.name]["columns"], [None, "weight", "height"], ) self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "weight"), True) self.assertIs(sql.references_column(table, "height"), True) self.assertIn("UPPER(%s)" % editor.quote_name("name"), str(sql)) self.assertIn( "INCLUDE (%s, %s)" % ( editor.quote_name("weight"), editor.quote_name("height"), ), str(sql), ) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_lookups(self): with connection.schema_editor() as editor: editor.create_model(Author) with register_lookup(CharField, Lower), register_lookup(IntegerField, Abs): constraint = UniqueConstraint( F("name__lower"), F("weight__abs"), name="func_lower_abs_lookup_uq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) sql = constraint.create_sql(Author, editor) table = Author._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) # SQL contains columns. self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "weight"), True) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(Author, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_collate(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("This backend does not support case-insensitive collations.") with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithSlug) constraint = UniqueConstraint( Collate(F("title"), collation=collation).desc(), Collate("slug", collation=collation), name="func_collate_uq", ) # Add constraint. with connection.schema_editor() as editor: editor.add_constraint(BookWithSlug, constraint) sql = constraint.create_sql(BookWithSlug, editor) table = BookWithSlug._meta.db_table constraints = self.get_constraints(table) self.assertIn(constraint.name, constraints) self.assertIs(constraints[constraint.name]["unique"], True) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, constraint.name, ["DESC", "ASC"]) # SQL contains columns and a collation. self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "slug"), True) self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql)) # Remove constraint. with connection.schema_editor() as editor: editor.remove_constraint(BookWithSlug, constraint) self.assertNotIn(constraint.name, self.get_constraints(table)) @skipIfDBFeature("supports_expression_indexes") def test_func_unique_constraint_unsupported(self): # UniqueConstraint is ignored on databases that don't support indexes on # expressions. with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(F("name"), name="func_name_uq") with connection.schema_editor() as editor, self.assertNumQueries(0): self.assertIsNone(editor.add_constraint(Author, constraint)) self.assertIsNone(editor.remove_constraint(Author, constraint)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_nonexistent_field(self): constraint = UniqueConstraint(Lower("nonexistent"), name="func_nonexistent_uq") msg = ( "Cannot resolve keyword 'nonexistent' into field. Choices are: " "height, id, name, uuid, weight" ) with self.assertRaisesMessage(FieldError, msg): with connection.schema_editor() as editor: editor.add_constraint(Author, constraint) @skipUnlessDBFeature("supports_expression_indexes") def test_func_unique_constraint_nondeterministic(self): with connection.schema_editor() as editor: editor.create_model(Author) constraint = UniqueConstraint(Random(), name="func_random_uq") with connection.schema_editor() as editor: with self.assertRaises(DatabaseError): editor.add_constraint(Author, constraint) def test_index_together(self): """ Tests removing and adding index_together constraints on a model. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure there's no index on the year/slug columns first self.assertIs( any( c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"] ), False, ) # Alter the model to add an index with connection.schema_editor() as editor: editor.alter_index_together(Tag, [], [("slug", "title")]) # Ensure there is now an index self.assertIs( any( c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"] ), True, ) # Alter it back new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_index_together(Tag, [("slug", "title")], []) # Ensure there's no index self.assertIs( any( c["index"] for c in self.get_constraints("schema_tag").values() if c["columns"] == ["slug", "title"] ), False, ) def test_index_together_with_fk(self): """ Tests removing and adding index_together constraints that include a foreign key. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the fields are unique to begin with self.assertEqual(Book._meta.index_together, ()) # Add the unique_together constraint with connection.schema_editor() as editor: editor.alter_index_together(Book, [], [["author", "title"]]) # Alter it back with connection.schema_editor() as editor: editor.alter_index_together(Book, [["author", "title"]], []) def test_create_index_together(self): """ Tests creating models with index_together already defined """ # Create the table with connection.schema_editor() as editor: editor.create_model(TagIndexed) # Ensure there is an index self.assertIs( any( c["index"] for c in self.get_constraints("schema_tagindexed").values() if c["columns"] == ["slug", "title"] ), True, ) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_index_together_does_not_remove_meta_indexes(self): with connection.schema_editor() as editor: editor.create_model(AuthorWithIndexedNameAndBirthday) # Add the custom index index = Index(fields=["name", "birthday"], name="author_name_birthday_idx") custom_index_name = index.name AuthorWithIndexedNameAndBirthday._meta.indexes = [index] with connection.schema_editor() as editor: editor.add_index(AuthorWithIndexedNameAndBirthday, index) # Ensure the indexes exist constraints = self.get_constraints( AuthorWithIndexedNameAndBirthday._meta.db_table ) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["index"] and name != custom_index_name ] self.assertEqual(len(other_constraints), 1) # Remove index together index_together = AuthorWithIndexedNameAndBirthday._meta.index_together with connection.schema_editor() as editor: editor.alter_index_together( AuthorWithIndexedNameAndBirthday, index_together, [] ) constraints = self.get_constraints( AuthorWithIndexedNameAndBirthday._meta.db_table ) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["index"] and name != custom_index_name ] self.assertEqual(len(other_constraints), 0) # Re-add index together with connection.schema_editor() as editor: editor.alter_index_together( AuthorWithIndexedNameAndBirthday, [], index_together ) constraints = self.get_constraints( AuthorWithIndexedNameAndBirthday._meta.db_table ) self.assertIn(custom_index_name, constraints) other_constraints = [ name for name, details in constraints.items() if details["columns"] == ["name", "birthday"] and details["index"] and name != custom_index_name ] self.assertEqual(len(other_constraints), 1) # Drop the index with connection.schema_editor() as editor: AuthorWithIndexedNameAndBirthday._meta.indexes = [] editor.remove_index(AuthorWithIndexedNameAndBirthday, index) @isolate_apps("schema") def test_db_table(self): """ Tests renaming of the table """ class Author(Model): name = CharField(max_length=255) class Meta: app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = "schema" # Create the table and one referring it. with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the table is there to begin with columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) # Alter the table with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: editor.alter_db_table(Author, "schema_author", "schema_otherauthor") Author._meta.db_table = "schema_otherauthor" columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) # Ensure the foreign key reference was updated self.assertForeignKeyExists(Book, "author_id", "schema_otherauthor") # Alter the table again with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: editor.alter_db_table(Author, "schema_otherauthor", "schema_author") # Ensure the table is still there Author._meta.db_table = "schema_author" columns = self.column_classes(Author) self.assertEqual( columns["name"][0], connection.features.introspected_field_types["CharField"], ) def test_add_remove_index(self): """ Tests index addition and removal """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure the table is there and has no index self.assertNotIn("title", self.get_indexes(Author._meta.db_table)) # Add the index index = Index(fields=["name"], name="author_title_idx") with connection.schema_editor() as editor: editor.add_index(Author, index) self.assertIn("name", self.get_indexes(Author._meta.db_table)) # Drop the index with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn("name", self.get_indexes(Author._meta.db_table)) def test_remove_db_index_doesnt_remove_custom_indexes(self): """ Changing db_index to False doesn't remove indexes from Meta.indexes. """ with connection.schema_editor() as editor: editor.create_model(AuthorWithIndexedName) # Ensure the table has its index self.assertIn("name", self.get_indexes(AuthorWithIndexedName._meta.db_table)) # Add the custom index index = Index(fields=["-name"], name="author_name_idx") author_index_name = index.name with connection.schema_editor() as editor: db_index_name = editor._create_index_name( table_name=AuthorWithIndexedName._meta.db_table, column_names=("name",), ) try: AuthorWithIndexedName._meta.indexes = [index] with connection.schema_editor() as editor: editor.add_index(AuthorWithIndexedName, index) old_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table) self.assertIn(author_index_name, old_constraints) self.assertIn(db_index_name, old_constraints) # Change name field to db_index=False old_field = AuthorWithIndexedName._meta.get_field("name") new_field = CharField(max_length=255) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field( AuthorWithIndexedName, old_field, new_field, strict=True ) new_constraints = self.get_constraints(AuthorWithIndexedName._meta.db_table) self.assertNotIn(db_index_name, new_constraints) # The index from Meta.indexes is still in the database. self.assertIn(author_index_name, new_constraints) # Drop the index with connection.schema_editor() as editor: editor.remove_index(AuthorWithIndexedName, index) finally: AuthorWithIndexedName._meta.indexes = [] def test_order_index(self): """ Indexes defined with ordering (ASC/DESC) defined on column """ with connection.schema_editor() as editor: editor.create_model(Author) # The table doesn't have an index self.assertNotIn("title", self.get_indexes(Author._meta.db_table)) index_name = "author_name_idx" # Add the index index = Index(fields=["name", "-weight"], name=index_name) with connection.schema_editor() as editor: editor.add_index(Author, index) if connection.features.supports_index_column_ordering: self.assertIndexOrder(Author._meta.db_table, index_name, ["ASC", "DESC"]) # Drop the index with connection.schema_editor() as editor: editor.remove_index(Author, index) def test_indexes(self): """ Tests creation/altering of indexes """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) # Ensure the table is there and has the right index self.assertIn( "title", self.get_indexes(Book._meta.db_table), ) # Alter to remove the index old_field = Book._meta.get_field("title") new_field = CharField(max_length=100, db_index=False) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(Book, old_field, new_field, strict=True) # Ensure the table is there and has no index self.assertNotIn( "title", self.get_indexes(Book._meta.db_table), ) # Alter to re-add the index new_field2 = Book._meta.get_field("title") with connection.schema_editor() as editor: editor.alter_field(Book, new_field, new_field2, strict=True) # Ensure the table is there and has the index again self.assertIn( "title", self.get_indexes(Book._meta.db_table), ) # Add a unique column, verify that creates an implicit index new_field3 = BookWithSlug._meta.get_field("slug") with connection.schema_editor() as editor: editor.add_field(Book, new_field3) self.assertIn( "slug", self.get_uniques(Book._meta.db_table), ) # Remove the unique, check the index goes with it new_field4 = CharField(max_length=20, unique=False) new_field4.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(BookWithSlug, new_field3, new_field4, strict=True) self.assertNotIn( "slug", self.get_uniques(Book._meta.db_table), ) def test_text_field_with_db_index(self): with connection.schema_editor() as editor: editor.create_model(AuthorTextFieldWithIndex) # The text_field index is present if the database supports it. assertion = ( self.assertIn if connection.features.supports_index_on_text_field else self.assertNotIn ) assertion( "text_field", self.get_indexes(AuthorTextFieldWithIndex._meta.db_table) ) def _index_expressions_wrappers(self): index_expression = IndexExpression() index_expression.set_wrapper_classes(connection) return ", ".join( [ wrapper_cls.__qualname__ for wrapper_cls in index_expression.wrapper_classes ] ) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_multiple_wrapper_references(self): index = Index(OrderBy(F("name").desc(), descending=True), name="name") msg = ( "Multiple references to %s can't be used in an indexed expression." % self._index_expressions_wrappers() ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): editor.add_index(Author, index) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_invalid_topmost_expressions(self): index = Index(Upper(F("name").desc()), name="name") msg = ( "%s must be topmost expressions in an indexed expression." % self._index_expressions_wrappers() ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): editor.add_index(Author, index) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Lower("name").desc(), name="func_lower_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC"]) # SQL contains a database function. self.assertIs(sql.references_column(table, "name"), True) self.assertIn("LOWER(%s)" % editor.quote_name("name"), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_f(self): with connection.schema_editor() as editor: editor.create_model(Tag) index = Index("slug", F("title").desc(), name="func_f_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Tag, index) sql = index.create_sql(Tag, editor) table = Tag._meta.db_table self.assertIn(index.name, self.get_constraints(table)) if connection.features.supports_index_column_ordering: self.assertIndexOrder(Tag._meta.db_table, index.name, ["ASC", "DESC"]) # SQL contains columns. self.assertIs(sql.references_column(table, "slug"), True) self.assertIs(sql.references_column(table, "title"), True) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Tag, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_lookups(self): with connection.schema_editor() as editor: editor.create_model(Author) with register_lookup(CharField, Lower), register_lookup(IntegerField, Abs): index = Index( F("name__lower"), F("weight__abs"), name="func_lower_abs_lookup_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) # SQL contains columns. self.assertIs(sql.references_column(table, "name"), True) self.assertIs(sql.references_column(table, "weight"), True) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_composite_func_index(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Lower("name"), Upper("name"), name="func_lower_upper_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) # SQL contains database functions. self.assertIs(sql.references_column(table, "name"), True) sql = str(sql) self.assertIn("LOWER(%s)" % editor.quote_name("name"), sql) self.assertIn("UPPER(%s)" % editor.quote_name("name"), sql) self.assertLess(sql.index("LOWER"), sql.index("UPPER")) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_composite_func_index_field_and_expression(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) index = Index( F("author").desc(), Lower("title").asc(), "pub_date", name="func_f_lower_field_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(Book, index) sql = index.create_sql(Book, editor) table = Book._meta.db_table constraints = self.get_constraints(table) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC", "ASC", "ASC"]) self.assertEqual(len(constraints[index.name]["columns"]), 3) self.assertEqual(constraints[index.name]["columns"][2], "pub_date") # SQL contains database functions and columns. self.assertIs(sql.references_column(table, "author_id"), True) self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "pub_date"), True) self.assertIn("LOWER(%s)" % editor.quote_name("title"), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Book, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") @isolate_apps("schema") def test_func_index_f_decimalfield(self): class Node(Model): value = DecimalField(max_digits=5, decimal_places=2) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Node) index = Index(F("value"), name="func_f_decimalfield_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Node, index) sql = index.create_sql(Node, editor) table = Node._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "value"), True) # SQL doesn't contain casting. self.assertNotIn("CAST", str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Node, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_cast(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Cast("weight", FloatField()), name="func_cast_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "weight"), True) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_collate(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("This backend does not support case-insensitive collations.") with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(BookWithSlug) index = Index( Collate(F("title"), collation=collation).desc(), Collate("slug", collation=collation), name="func_collate_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(BookWithSlug, index) sql = index.create_sql(BookWithSlug, editor) table = Book._meta.db_table self.assertIn(index.name, self.get_constraints(table)) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC", "ASC"]) # SQL contains columns and a collation. self.assertIs(sql.references_column(table, "title"), True) self.assertIs(sql.references_column(table, "slug"), True) self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Book, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") @skipIfDBFeature("collate_as_index_expression") def test_func_index_collate_f_ordered(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("This backend does not support case-insensitive collations.") with connection.schema_editor() as editor: editor.create_model(Author) index = Index( Collate(F("name").desc(), collation=collation), name="func_collate_f_desc_idx", ) # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) if connection.features.supports_index_column_ordering: self.assertIndexOrder(table, index.name, ["DESC"]) # SQL contains columns and a collation. self.assertIs(sql.references_column(table, "name"), True) self.assertIn("COLLATE %s" % editor.quote_name(collation), str(sql)) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_calc(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(F("height") / (F("weight") + Value(5)), name="func_calc_idx") # Add index. with connection.schema_editor() as editor: editor.add_index(Author, index) sql = index.create_sql(Author, editor) table = Author._meta.db_table self.assertIn(index.name, self.get_constraints(table)) # SQL contains columns and expressions. self.assertIs(sql.references_column(table, "height"), True) self.assertIs(sql.references_column(table, "weight"), True) sql = str(sql) self.assertIs( sql.index(editor.quote_name("height")) < sql.index("/") < sql.index(editor.quote_name("weight")) < sql.index("+") < sql.index("5"), True, ) # Remove index. with connection.schema_editor() as editor: editor.remove_index(Author, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_json_field") @isolate_apps("schema") def test_func_index_json_key_transform(self): class JSONModel(Model): field = JSONField() class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(JSONModel) self.isolated_local_models = [JSONModel] index = Index("field__some_key", name="func_json_key_idx") with connection.schema_editor() as editor: editor.add_index(JSONModel, index) sql = index.create_sql(JSONModel, editor) table = JSONModel._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "field"), True) with connection.schema_editor() as editor: editor.remove_index(JSONModel, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipUnlessDBFeature("supports_expression_indexes", "supports_json_field") @isolate_apps("schema") def test_func_index_json_key_transform_cast(self): class JSONModel(Model): field = JSONField() class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(JSONModel) self.isolated_local_models = [JSONModel] index = Index( Cast(KeyTextTransform("some_key", "field"), IntegerField()), name="func_json_key_cast_idx", ) with connection.schema_editor() as editor: editor.add_index(JSONModel, index) sql = index.create_sql(JSONModel, editor) table = JSONModel._meta.db_table self.assertIn(index.name, self.get_constraints(table)) self.assertIs(sql.references_column(table, "field"), True) with connection.schema_editor() as editor: editor.remove_index(JSONModel, index) self.assertNotIn(index.name, self.get_constraints(table)) @skipIfDBFeature("supports_expression_indexes") def test_func_index_unsupported(self): # Index is ignored on databases that don't support indexes on # expressions. with connection.schema_editor() as editor: editor.create_model(Author) index = Index(F("name"), name="random_idx") with connection.schema_editor() as editor, self.assertNumQueries(0): self.assertIsNone(editor.add_index(Author, index)) self.assertIsNone(editor.remove_index(Author, index)) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_nonexistent_field(self): index = Index(Lower("nonexistent"), name="func_nonexistent_idx") msg = ( "Cannot resolve keyword 'nonexistent' into field. Choices are: " "height, id, name, uuid, weight" ) with self.assertRaisesMessage(FieldError, msg): with connection.schema_editor() as editor: editor.add_index(Author, index) @skipUnlessDBFeature("supports_expression_indexes") def test_func_index_nondeterministic(self): with connection.schema_editor() as editor: editor.create_model(Author) index = Index(Random(), name="func_random_idx") with connection.schema_editor() as editor: with self.assertRaises(DatabaseError): editor.add_index(Author, index) def test_primary_key(self): """ Tests altering of the primary key """ # Create the table with connection.schema_editor() as editor: editor.create_model(Tag) # Ensure the table is there and has the right PK self.assertEqual(self.get_primary_key(Tag._meta.db_table), "id") # Alter to change the PK id_field = Tag._meta.get_field("id") old_field = Tag._meta.get_field("slug") new_field = SlugField(primary_key=True) new_field.set_attributes_from_name("slug") new_field.model = Tag with connection.schema_editor() as editor: editor.remove_field(Tag, id_field) editor.alter_field(Tag, old_field, new_field) # Ensure the PK changed self.assertNotIn( "id", self.get_indexes(Tag._meta.db_table), ) self.assertEqual(self.get_primary_key(Tag._meta.db_table), "slug") def test_context_manager_exit(self): """ Ensures transaction is correctly closed when an error occurs inside a SchemaEditor context. """ class SomeError(Exception): pass try: with connection.schema_editor(): raise SomeError except SomeError: self.assertFalse(connection.in_atomic_block) @skipIfDBFeature("can_rollback_ddl") def test_unsupported_transactional_ddl_disallowed(self): message = ( "Executing DDL statements while in a transaction on databases " "that can't perform a rollback is prohibited." ) with atomic(), connection.schema_editor() as editor: with self.assertRaisesMessage(TransactionManagementError, message): editor.execute( editor.sql_create_table % {"table": "foo", "definition": ""} ) @skipUnlessDBFeature("supports_foreign_keys", "indexes_foreign_keys") def test_foreign_key_index_long_names_regression(self): """ Regression test for #21497. Only affects databases that supports foreign keys. """ # Create the table with connection.schema_editor() as editor: editor.create_model(AuthorWithEvenLongerName) editor.create_model(BookWithLongName) # Find the properly shortened column name column_name = connection.ops.quote_name( "author_foreign_key_with_really_long_field_name_id" ) column_name = column_name[1:-1].lower() # unquote, and, for Oracle, un-upcase # Ensure the table is there and has an index on the column self.assertIn( column_name, self.get_indexes(BookWithLongName._meta.db_table), ) @skipUnlessDBFeature("supports_foreign_keys") def test_add_foreign_key_long_names(self): """ Regression test for #23009. Only affects databases that supports foreign keys. """ # Create the initial tables with connection.schema_editor() as editor: editor.create_model(AuthorWithEvenLongerName) editor.create_model(BookWithLongName) # Add a second FK, this would fail due to long ref name before the fix new_field = ForeignKey( AuthorWithEvenLongerName, CASCADE, related_name="something" ) new_field.set_attributes_from_name( "author_other_really_long_named_i_mean_so_long_fk" ) with connection.schema_editor() as editor: editor.add_field(BookWithLongName, new_field) @isolate_apps("schema") @skipUnlessDBFeature("supports_foreign_keys") def test_add_foreign_key_quoted_db_table(self): class Author(Model): class Meta: db_table = '"table_author_double_quoted"' app_label = "schema" class Book(Model): author = ForeignKey(Author, CASCADE) class Meta: app_label = "schema" with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) if connection.vendor == "mysql": self.assertForeignKeyExists( Book, "author_id", '"table_author_double_quoted"' ) else: self.assertForeignKeyExists(Book, "author_id", "table_author_double_quoted") def test_add_foreign_object(self): with connection.schema_editor() as editor: editor.create_model(BookForeignObj) new_field = ForeignObject( Author, on_delete=CASCADE, from_fields=["author_id"], to_fields=["id"] ) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.add_field(BookForeignObj, new_field) def test_creation_deletion_reserved_names(self): """ Tries creating a model's table, and then deleting it when it has a SQL reserved name. """ # Create the table with connection.schema_editor() as editor: try: editor.create_model(Thing) except OperationalError as e: self.fail( "Errors when applying initial migration for a model " "with a table named after an SQL reserved word: %s" % e ) # The table is there list(Thing.objects.all()) # Clean up that table with connection.schema_editor() as editor: editor.delete_model(Thing) # The table is gone with self.assertRaises(DatabaseError): list(Thing.objects.all()) def test_remove_constraints_capital_letters(self): """ #23065 - Constraint names must be quoted if they contain capital letters. """ def get_field(*args, field_class=IntegerField, **kwargs): kwargs["db_column"] = "CamelCase" field = field_class(*args, **kwargs) field.set_attributes_from_name("CamelCase") return field model = Author field = get_field() table = model._meta.db_table column = field.column identifier_converter = connection.introspection.identifier_converter with connection.schema_editor() as editor: editor.create_model(model) editor.add_field(model, field) constraint_name = "CamelCaseIndex" expected_constraint_name = identifier_converter(constraint_name) editor.execute( editor.sql_create_index % { "table": editor.quote_name(table), "name": editor.quote_name(constraint_name), "using": "", "columns": editor.quote_name(column), "extra": "", "condition": "", "include": "", } ) self.assertIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) editor.alter_field(model, get_field(db_index=True), field, strict=True) self.assertNotIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) constraint_name = "CamelCaseUniqConstraint" expected_constraint_name = identifier_converter(constraint_name) editor.execute(editor._create_unique_sql(model, [field], constraint_name)) self.assertIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) editor.alter_field(model, get_field(unique=True), field, strict=True) self.assertNotIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) if editor.sql_create_fk: constraint_name = "CamelCaseFKConstraint" expected_constraint_name = identifier_converter(constraint_name) editor.execute( editor.sql_create_fk % { "table": editor.quote_name(table), "name": editor.quote_name(constraint_name), "column": editor.quote_name(column), "to_table": editor.quote_name(table), "to_column": editor.quote_name(model._meta.auto_field.column), "deferrable": connection.ops.deferrable_sql(), } ) self.assertIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) editor.alter_field( model, get_field(Author, CASCADE, field_class=ForeignKey), field, strict=True, ) self.assertNotIn( expected_constraint_name, self.get_constraints(model._meta.db_table) ) def test_add_field_use_effective_default(self): """ #23987 - effective_default() should be used as the field default when adding a new field. """ # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no surname field columns = self.column_classes(Author) self.assertNotIn("surname", columns) # Create a row Author.objects.create(name="Anonymous1") # Add new CharField to ensure default will be used from effective_default new_field = CharField(max_length=15, blank=True) new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure field was added with the right default with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertEqual( item[0], None if connection.features.interprets_empty_strings_as_nulls else "", ) def test_add_field_default_dropped(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Ensure there's no surname field columns = self.column_classes(Author) self.assertNotIn("surname", columns) # Create a row Author.objects.create(name="Anonymous1") # Add new CharField with a default new_field = CharField(max_length=15, blank=True, default="surname default") new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) # Ensure field was added with the right default with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertEqual(item[0], "surname default") # And that the default is no longer set in the database. field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author" ) if f.name == "surname" ) if connection.features.can_introspect_default: self.assertIsNone(field.default) def test_add_field_default_nullable(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add new nullable CharField with a default. new_field = CharField(max_length=15, blank=True, null=True, default="surname") new_field.set_attributes_from_name("surname") with connection.schema_editor() as editor: editor.add_field(Author, new_field) Author.objects.create(name="Anonymous1") with connection.cursor() as cursor: cursor.execute("SELECT surname FROM schema_author;") item = cursor.fetchall()[0] self.assertIsNone(item[0]) field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author", ) if f.name == "surname" ) # Field is still nullable. self.assertTrue(field.null_ok) # The database default is no longer set. if connection.features.can_introspect_default: self.assertIn(field.default, ["NULL", None]) def test_add_textfield_default_nullable(self): with connection.schema_editor() as editor: editor.create_model(Author) # Add new nullable TextField with a default. new_field = TextField(blank=True, null=True, default="text") new_field.set_attributes_from_name("description") with connection.schema_editor() as editor: editor.add_field(Author, new_field) Author.objects.create(name="Anonymous1") with connection.cursor() as cursor: cursor.execute("SELECT description FROM schema_author;") item = cursor.fetchall()[0] self.assertIsNone(item[0]) field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author", ) if f.name == "description" ) # Field is still nullable. self.assertTrue(field.null_ok) # The database default is no longer set. if connection.features.can_introspect_default: self.assertIn(field.default, ["NULL", None]) def test_alter_field_default_dropped(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Create a row Author.objects.create(name="Anonymous1") self.assertIsNone(Author.objects.get().height) old_field = Author._meta.get_field("height") # The default from the new field is used in updating existing rows. new_field = IntegerField(blank=True, default=42) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual(Author.objects.get().height, 42) # The database default should be removed. with connection.cursor() as cursor: field = next( f for f in connection.introspection.get_table_description( cursor, "schema_author" ) if f.name == "height" ) if connection.features.can_introspect_default: self.assertIsNone(field.default) def test_alter_field_default_doesnt_perform_queries(self): """ No queries are performed if a field default changes and the field's not changing from null to non-null. """ with connection.schema_editor() as editor: editor.create_model(AuthorWithDefaultHeight) old_field = AuthorWithDefaultHeight._meta.get_field("height") new_default = old_field.default * 2 new_field = PositiveIntegerField(null=True, blank=True, default=new_default) new_field.set_attributes_from_name("height") with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field( AuthorWithDefaultHeight, old_field, new_field, strict=True ) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_fk_attributes_noop(self): """ No queries are performed when changing field attributes that don't affect the schema. """ with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) old_field = Book._meta.get_field("author") new_field = ForeignKey( Author, blank=True, editable=False, error_messages={"invalid": "error message"}, help_text="help text", limit_choices_to={"limit": "choice"}, on_delete=PROTECT, related_name="related_name", related_query_name="related_query_name", validators=[lambda x: x], verbose_name="verbose name", ) new_field.set_attributes_from_name("author") with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(Book, old_field, new_field, strict=True) with connection.schema_editor() as editor, self.assertNumQueries(0): editor.alter_field(Book, new_field, old_field, strict=True) def test_add_textfield_unhashable_default(self): # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Create a row Author.objects.create(name="Anonymous1") # Create a field that has an unhashable default new_field = TextField(default={}) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.add_field(Author, new_field) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_add_indexed_charfield(self): field = CharField(max_length=255, db_index=True) field.set_attributes_from_name("nom_de_plume") with connection.schema_editor() as editor: editor.create_model(Author) editor.add_field(Author, field) # Should create two indexes; one for like operator. self.assertEqual( self.get_constraints_for_column(Author, "nom_de_plume"), [ "schema_author_nom_de_plume_7570a851", "schema_author_nom_de_plume_7570a851_like", ], ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_add_unique_charfield(self): field = CharField(max_length=255, unique=True) field.set_attributes_from_name("nom_de_plume") with connection.schema_editor() as editor: editor.create_model(Author) editor.add_field(Author, field) # Should create two indexes; one for like operator. self.assertEqual( self.get_constraints_for_column(Author, "nom_de_plume"), [ "schema_author_nom_de_plume_7570a851_like", "schema_author_nom_de_plume_key", ], ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_index_to_charfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) # Alter to add db_index=True and create 2 indexes. old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, db_index=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, "name"), ["schema_author_name_1fbc5617", "schema_author_name_1fbc5617_like"], ) # Remove db_index=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_unique_to_charfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) # Alter to add unique=True and create 2 indexes. old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("name") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, "name"), ["schema_author_name_1fbc5617_like", "schema_author_name_1fbc5617_uniq"], ) # Remove unique=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, "name"), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_index_to_textfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Note) self.assertEqual(self.get_constraints_for_column(Note, "info"), []) # Alter to add db_index=True and create 2 indexes. old_field = Note._meta.get_field("info") new_field = TextField(db_index=True) new_field.set_attributes_from_name("info") with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Note, "info"), ["schema_note_info_4b0ea695", "schema_note_info_4b0ea695_like"], ) # Remove db_index=True to drop both indexes. with connection.schema_editor() as editor: editor.alter_field(Note, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Note, "info"), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_unique_to_charfield_with_db_index(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) # Alter to add unique=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field("title") new_field = CharField(max_length=100, db_index=True, unique=True) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"], ) # Alter to remove unique=True (should drop unique index) new_field2 = CharField(max_length=100, db_index=True) new_field2.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_remove_unique_and_db_index_from_charfield(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) # Alter to add unique=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field("title") new_field = CharField(max_length=100, db_index=True, unique=True) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"], ) # Alter to remove both unique=True and db_index=True (should drop all indexes) new_field2 = CharField(max_length=100) new_field2.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), [] ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_swap_unique_and_db_index_with_charfield(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(BookWithoutAuthor) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) # Alter to set unique=True and remove db_index=True (should replace the index) old_field = BookWithoutAuthor._meta.get_field("title") new_field = CharField(max_length=100, unique=True) new_field.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff_like", "schema_book_title_2dfb2dff_uniq"], ) # Alter to set db_index=True and remove unique=True (should restore index) new_field2 = CharField(max_length=100, db_index=True) new_field2.set_attributes_from_name("title") with connection.schema_editor() as editor: editor.alter_field(BookWithoutAuthor, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(BookWithoutAuthor, "title"), ["schema_book_title_2dfb2dff", "schema_book_title_2dfb2dff_like"], ) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_alter_field_add_db_index_to_charfield_with_unique(self): # Create the table and verify initial indexes. with connection.schema_editor() as editor: editor.create_model(Tag) self.assertEqual( self.get_constraints_for_column(Tag, "slug"), ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"], ) # Alter to add db_index=True old_field = Tag._meta.get_field("slug") new_field = SlugField(db_index=True, unique=True) new_field.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Tag, "slug"), ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"], ) # Alter to remove db_index=True new_field2 = SlugField(unique=True) new_field2.set_attributes_from_name("slug") with connection.schema_editor() as editor: editor.alter_field(Tag, new_field, new_field2, strict=True) self.assertEqual( self.get_constraints_for_column(Tag, "slug"), ["schema_tag_slug_2c418ba3_like", "schema_tag_slug_key"], ) def test_alter_field_add_index_to_integerfield(self): # Create the table and verify no initial indexes. with connection.schema_editor() as editor: editor.create_model(Author) self.assertEqual(self.get_constraints_for_column(Author, "weight"), []) # Alter to add db_index=True and create index. old_field = Author._meta.get_field("weight") new_field = IntegerField(null=True, db_index=True) new_field.set_attributes_from_name("weight") with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_constraints_for_column(Author, "weight"), ["schema_author_weight_587740f9"], ) # Remove db_index=True to drop index. with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertEqual(self.get_constraints_for_column(Author, "weight"), []) def test_alter_pk_with_self_referential_field(self): """ Changing the primary key field name of a model with a self-referential foreign key (#26384). """ with connection.schema_editor() as editor: editor.create_model(Node) old_field = Node._meta.get_field("node_id") new_field = AutoField(primary_key=True) new_field.set_attributes_from_name("id") with connection.schema_editor() as editor: editor.alter_field(Node, old_field, new_field, strict=True) self.assertForeignKeyExists(Node, "parent_id", Node._meta.db_table) @mock.patch("django.db.backends.base.schema.datetime") @mock.patch("django.db.backends.base.schema.timezone") def test_add_datefield_and_datetimefield_use_effective_default( self, mocked_datetime, mocked_tz ): """ effective_default() should be used for DateField, DateTimeField, and TimeField if auto_now or auto_now_add is set (#25005). """ now = datetime.datetime(month=1, day=1, year=2000, hour=1, minute=1) now_tz = datetime.datetime( month=1, day=1, year=2000, hour=1, minute=1, tzinfo=timezone.utc ) mocked_datetime.now = mock.MagicMock(return_value=now) mocked_tz.now = mock.MagicMock(return_value=now_tz) # Create the table with connection.schema_editor() as editor: editor.create_model(Author) # Check auto_now/auto_now_add attributes are not defined columns = self.column_classes(Author) self.assertNotIn("dob_auto_now", columns) self.assertNotIn("dob_auto_now_add", columns) self.assertNotIn("dtob_auto_now", columns) self.assertNotIn("dtob_auto_now_add", columns) self.assertNotIn("tob_auto_now", columns) self.assertNotIn("tob_auto_now_add", columns) # Create a row Author.objects.create(name="Anonymous1") # Ensure fields were added with the correct defaults dob_auto_now = DateField(auto_now=True) dob_auto_now.set_attributes_from_name("dob_auto_now") self.check_added_field_default( editor, Author, dob_auto_now, "dob_auto_now", now.date(), cast_function=lambda x: x.date(), ) dob_auto_now_add = DateField(auto_now_add=True) dob_auto_now_add.set_attributes_from_name("dob_auto_now_add") self.check_added_field_default( editor, Author, dob_auto_now_add, "dob_auto_now_add", now.date(), cast_function=lambda x: x.date(), ) dtob_auto_now = DateTimeField(auto_now=True) dtob_auto_now.set_attributes_from_name("dtob_auto_now") self.check_added_field_default( editor, Author, dtob_auto_now, "dtob_auto_now", now, ) dt_tm_of_birth_auto_now_add = DateTimeField(auto_now_add=True) dt_tm_of_birth_auto_now_add.set_attributes_from_name("dtob_auto_now_add") self.check_added_field_default( editor, Author, dt_tm_of_birth_auto_now_add, "dtob_auto_now_add", now, ) tob_auto_now = TimeField(auto_now=True) tob_auto_now.set_attributes_from_name("tob_auto_now") self.check_added_field_default( editor, Author, tob_auto_now, "tob_auto_now", now.time(), cast_function=lambda x: x.time(), ) tob_auto_now_add = TimeField(auto_now_add=True) tob_auto_now_add.set_attributes_from_name("tob_auto_now_add") self.check_added_field_default( editor, Author, tob_auto_now_add, "tob_auto_now_add", now.time(), cast_function=lambda x: x.time(), ) def test_namespaced_db_table_create_index_name(self): """ Table names are stripped of their namespace/schema before being used to generate index names. """ with connection.schema_editor() as editor: max_name_length = connection.ops.max_name_length() or 200 namespace = "n" * max_name_length table_name = "t" * max_name_length namespaced_table_name = '"%s"."%s"' % (namespace, table_name) self.assertEqual( editor._create_index_name(table_name, []), editor._create_index_name(namespaced_table_name, []), ) @unittest.skipUnless( connection.vendor == "oracle", "Oracle specific db_table syntax" ) def test_creation_with_db_table_double_quotes(self): oracle_user = connection.creation._test_database_user() class Student(Model): name = CharField(max_length=30) class Meta: app_label = "schema" apps = new_apps db_table = '"%s"."DJANGO_STUDENT_TABLE"' % oracle_user class Document(Model): name = CharField(max_length=30) students = ManyToManyField(Student) class Meta: app_label = "schema" apps = new_apps db_table = '"%s"."DJANGO_DOCUMENT_TABLE"' % oracle_user self.local_models = [Student, Document] with connection.schema_editor() as editor: editor.create_model(Student) editor.create_model(Document) doc = Document.objects.create(name="Test Name") student = Student.objects.create(name="Some man") doc.students.add(student) @isolate_apps("schema") @unittest.skipUnless( connection.vendor == "postgresql", "PostgreSQL specific db_table syntax." ) def test_namespaced_db_table_foreign_key_reference(self): with connection.cursor() as cursor: cursor.execute("CREATE SCHEMA django_schema_tests") def delete_schema(): with connection.cursor() as cursor: cursor.execute("DROP SCHEMA django_schema_tests CASCADE") self.addCleanup(delete_schema) class Author(Model): class Meta: app_label = "schema" class Book(Model): class Meta: app_label = "schema" db_table = '"django_schema_tests"."schema_book"' author = ForeignKey(Author, CASCADE) author.set_attributes_from_name("author") with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) editor.add_field(Book, author) def test_rename_table_renames_deferred_sql_references(self): atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: editor.create_model(Author) editor.create_model(Book) editor.alter_db_table(Author, "schema_author", "schema_renamed_author") editor.alter_db_table(Author, "schema_book", "schema_renamed_book") try: self.assertGreater(len(editor.deferred_sql), 0) for statement in editor.deferred_sql: self.assertIs(statement.references_table("schema_author"), False) self.assertIs(statement.references_table("schema_book"), False) finally: editor.alter_db_table(Author, "schema_renamed_author", "schema_author") editor.alter_db_table(Author, "schema_renamed_book", "schema_book") def test_rename_column_renames_deferred_sql_references(self): with connection.schema_editor() as editor: editor.create_model(Author) editor.create_model(Book) old_title = Book._meta.get_field("title") new_title = CharField(max_length=100, db_index=True) new_title.set_attributes_from_name("renamed_title") editor.alter_field(Book, old_title, new_title) old_author = Book._meta.get_field("author") new_author = ForeignKey(Author, CASCADE) new_author.set_attributes_from_name("renamed_author") editor.alter_field(Book, old_author, new_author) self.assertGreater(len(editor.deferred_sql), 0) for statement in editor.deferred_sql: self.assertIs(statement.references_column("book", "title"), False) self.assertIs(statement.references_column("book", "author_id"), False) @isolate_apps("schema") def test_referenced_field_without_constraint_rename_inside_atomic_block(self): """ Foreign keys without database level constraint don't prevent the field they reference from being renamed in an atomic block. """ class Foo(Model): field = CharField(max_length=255, unique=True) class Meta: app_label = "schema" class Bar(Model): foo = ForeignKey(Foo, CASCADE, to_field="field", db_constraint=False) class Meta: app_label = "schema" self.isolated_local_models = [Foo, Bar] with connection.schema_editor() as editor: editor.create_model(Foo) editor.create_model(Bar) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("renamed") with connection.schema_editor(atomic=True) as editor: editor.alter_field(Foo, Foo._meta.get_field("field"), new_field) @isolate_apps("schema") def test_referenced_table_without_constraint_rename_inside_atomic_block(self): """ Foreign keys without database level constraint don't prevent the table they reference from being renamed in an atomic block. """ class Foo(Model): field = CharField(max_length=255, unique=True) class Meta: app_label = "schema" class Bar(Model): foo = ForeignKey(Foo, CASCADE, to_field="field", db_constraint=False) class Meta: app_label = "schema" self.isolated_local_models = [Foo, Bar] with connection.schema_editor() as editor: editor.create_model(Foo) editor.create_model(Bar) new_field = CharField(max_length=255, unique=True) new_field.set_attributes_from_name("renamed") with connection.schema_editor(atomic=True) as editor: editor.alter_db_table(Foo, Foo._meta.db_table, "renamed_table") Foo._meta.db_table = "renamed_table" @isolate_apps("schema") @skipUnlessDBFeature("supports_collation_on_charfield") def test_db_collation_charfield(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") class Foo(Model): field = CharField(max_length=255, db_collation=collation) class Meta: app_label = "schema" self.isolated_local_models = [Foo] with connection.schema_editor() as editor: editor.create_model(Foo) self.assertEqual( self.get_column_collation(Foo._meta.db_table, "field"), collation, ) @isolate_apps("schema") @skipUnlessDBFeature("supports_collation_on_textfield") def test_db_collation_textfield(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") class Foo(Model): field = TextField(db_collation=collation) class Meta: app_label = "schema" self.isolated_local_models = [Foo] with connection.schema_editor() as editor: editor.create_model(Foo) self.assertEqual( self.get_column_collation(Foo._meta.db_table, "field"), collation, ) @skipUnlessDBFeature("supports_collation_on_charfield") def test_add_field_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Author) new_field = CharField(max_length=255, db_collation=collation) new_field.set_attributes_from_name("alias") with connection.schema_editor() as editor: editor.add_field(Author, new_field) columns = self.column_classes(Author) self.assertEqual( columns["alias"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual(columns["alias"][1][8], collation) @skipUnlessDBFeature("supports_collation_on_charfield") def test_alter_field_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Author) old_field = Author._meta.get_field("name") new_field = CharField(max_length=255, db_collation=collation) new_field.set_attributes_from_name("name") new_field.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field, strict=True) self.assertEqual( self.get_column_collation(Author._meta.db_table, "name"), collation, ) with connection.schema_editor() as editor: editor.alter_field(Author, new_field, old_field, strict=True) self.assertIsNone(self.get_column_collation(Author._meta.db_table, "name")) @skipUnlessDBFeature("supports_collation_on_charfield") def test_alter_field_type_and_db_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") with connection.schema_editor() as editor: editor.create_model(Note) old_field = Note._meta.get_field("info") new_field = CharField(max_length=255, db_collation=collation) new_field.set_attributes_from_name("info") new_field.model = Note with connection.schema_editor() as editor: editor.alter_field(Note, old_field, new_field, strict=True) columns = self.column_classes(Note) self.assertEqual( columns["info"][0], connection.features.introspected_field_types["CharField"], ) self.assertEqual(columns["info"][1][8], collation) with connection.schema_editor() as editor: editor.alter_field(Note, new_field, old_field, strict=True) columns = self.column_classes(Note) self.assertEqual(columns["info"][0], "TextField") self.assertIsNone(columns["info"][1][8]) @skipUnlessDBFeature( "supports_collation_on_charfield", "supports_non_deterministic_collations", ) def test_ci_cs_db_collation(self): cs_collation = connection.features.test_collations.get("cs") ci_collation = connection.features.test_collations.get("ci") try: if connection.vendor == "mysql": cs_collation = "latin1_general_cs" elif connection.vendor == "postgresql": cs_collation = "en-x-icu" with connection.cursor() as cursor: cursor.execute( "CREATE COLLATION IF NOT EXISTS case_insensitive " "(provider = icu, locale = 'und-u-ks-level2', " "deterministic = false)" ) ci_collation = "case_insensitive" # Create the table. with connection.schema_editor() as editor: editor.create_model(Author) # Case-insensitive collation. old_field = Author._meta.get_field("name") new_field_ci = CharField(max_length=255, db_collation=ci_collation) new_field_ci.set_attributes_from_name("name") new_field_ci.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, old_field, new_field_ci, strict=True) Author.objects.create(name="ANDREW") self.assertIs(Author.objects.filter(name="Andrew").exists(), True) # Case-sensitive collation. new_field_cs = CharField(max_length=255, db_collation=cs_collation) new_field_cs.set_attributes_from_name("name") new_field_cs.model = Author with connection.schema_editor() as editor: editor.alter_field(Author, new_field_ci, new_field_cs, strict=True) self.assertIs(Author.objects.filter(name="Andrew").exists(), False) finally: if connection.vendor == "postgresql": with connection.cursor() as cursor: cursor.execute("DROP COLLATION IF EXISTS case_insensitive")
dc2d43bfef84be2976b35ffa73937ac52489a73d5db1a0d548079b5fffbe850a
from django.apps.registry import Apps from django.db import models # Because we want to test creation and deletion of these as separate things, # these models are all inserted into a separate Apps so the main test # runner doesn't migrate them. new_apps = Apps() class Author(models.Model): name = models.CharField(max_length=255) height = models.PositiveIntegerField(null=True, blank=True) weight = models.IntegerField(null=True, blank=True) uuid = models.UUIDField(null=True) class Meta: apps = new_apps class AuthorCharFieldWithIndex(models.Model): char_field = models.CharField(max_length=31, db_index=True) class Meta: apps = new_apps class AuthorTextFieldWithIndex(models.Model): text_field = models.TextField(db_index=True) class Meta: apps = new_apps class AuthorWithDefaultHeight(models.Model): name = models.CharField(max_length=255) height = models.PositiveIntegerField(null=True, blank=True, default=42) class Meta: apps = new_apps class AuthorWithEvenLongerName(models.Model): name = models.CharField(max_length=255) height = models.PositiveIntegerField(null=True, blank=True) class Meta: apps = new_apps class AuthorWithIndexedName(models.Model): name = models.CharField(max_length=255, db_index=True) class Meta: apps = new_apps class AuthorWithUniqueName(models.Model): name = models.CharField(max_length=255, unique=True) class Meta: apps = new_apps class AuthorWithIndexedNameAndBirthday(models.Model): name = models.CharField(max_length=255) birthday = models.DateField() class Meta: apps = new_apps index_together = [["name", "birthday"]] class AuthorWithUniqueNameAndBirthday(models.Model): name = models.CharField(max_length=255) birthday = models.DateField() class Meta: apps = new_apps unique_together = [["name", "birthday"]] class Book(models.Model): author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() # tags = models.ManyToManyField("Tag", related_name="books") class Meta: apps = new_apps class BookWeak(models.Model): author = models.ForeignKey(Author, models.CASCADE, db_constraint=False) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() class Meta: apps = new_apps class BookWithLongName(models.Model): author_foreign_key_with_really_long_field_name = models.ForeignKey( AuthorWithEvenLongerName, models.CASCADE, ) class Meta: apps = new_apps class BookWithO2O(models.Model): author = models.OneToOneField(Author, models.CASCADE) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() class Meta: apps = new_apps db_table = "schema_book" class BookWithSlug(models.Model): author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() slug = models.CharField(max_length=20, unique=True) class Meta: apps = new_apps db_table = "schema_book" class BookWithoutAuthor(models.Model): title = models.CharField(max_length=100, db_index=True) pub_date = models.DateTimeField() class Meta: apps = new_apps db_table = "schema_book" class BookForeignObj(models.Model): title = models.CharField(max_length=100, db_index=True) author_id = models.IntegerField() class Meta: apps = new_apps class IntegerPK(models.Model): i = models.IntegerField(primary_key=True) j = models.IntegerField(unique=True) class Meta: apps = new_apps db_table = "INTEGERPK" # uppercase to ensure proper quoting class Note(models.Model): info = models.TextField() address = models.TextField(null=True) class Meta: apps = new_apps class NoteRename(models.Model): detail_info = models.TextField() class Meta: apps = new_apps db_table = "schema_note" class Tag(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) class Meta: apps = new_apps class TagIndexed(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) class Meta: apps = new_apps index_together = [["slug", "title"]] class TagM2MTest(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(unique=True) class Meta: apps = new_apps class TagUniqueRename(models.Model): title = models.CharField(max_length=255) slug2 = models.SlugField(unique=True) class Meta: apps = new_apps db_table = "schema_tag" # Based on tests/reserved_names/models.py class Thing(models.Model): when = models.CharField(max_length=1, primary_key=True) class Meta: apps = new_apps db_table = "drop" def __str__(self): return self.when class UniqueTest(models.Model): year = models.IntegerField() slug = models.SlugField(unique=False) class Meta: apps = new_apps unique_together = ["year", "slug"] class Node(models.Model): node_id = models.AutoField(primary_key=True) parent = models.ForeignKey("self", models.CASCADE, null=True, blank=True) class Meta: apps = new_apps
0f898e468aa6d106fe9d86a7f5c85ee785dc1d2100d3813f0572f4517fd4661f
from django.db import connection from django.test import TestCase class SchemaLoggerTests(TestCase): def test_extra_args(self): editor = connection.schema_editor(collect_sql=True) sql = "SELECT * FROM foo WHERE id in (%s, %s)" params = [42, 1337] with self.assertLogs("django.db.backends.schema", "DEBUG") as cm: editor.execute(sql, params) self.assertEqual(cm.records[0].sql, sql) self.assertEqual(cm.records[0].params, params) self.assertEqual( cm.records[0].getMessage(), "SELECT * FROM foo WHERE id in (%s, %s); (params [42, 1337])", )
dabdaeaca3b6b9a264b89bc4b0f73f9b8cd55c01fd7b5a9a54b70ab53d406efe
from functools import partial from django.db import models from django.db.models.fields.related import ( RECURSIVE_RELATIONSHIP_CONSTANT, ManyToManyDescriptor, RelatedField, create_many_to_many_intermediary_model, ) class CustomManyToManyField(RelatedField): """ Ticket #24104 - Need to have a custom ManyToManyField, which is not an inheritor of ManyToManyField. """ many_to_many = True def __init__( self, to, db_constraint=True, swappable=True, related_name=None, related_query_name=None, limit_choices_to=None, symmetrical=None, through=None, through_fields=None, db_table=None, **kwargs, ): try: to._meta except AttributeError: to = str(to) kwargs["rel"] = models.ManyToManyRel( self, to, related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, symmetrical=symmetrical if symmetrical is not None else (to == RECURSIVE_RELATIONSHIP_CONSTANT), through=through, through_fields=through_fields, db_constraint=db_constraint, ) self.swappable = swappable self.db_table = db_table if kwargs["rel"].through is not None and self.db_table is not None: raise ValueError( "Cannot specify a db_table if an intermediary model is used." ) super().__init__( related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, **kwargs, ) def contribute_to_class(self, cls, name, **kwargs): if self.remote_field.symmetrical and ( self.remote_field.model == "self" or self.remote_field.model == cls._meta.object_name ): self.remote_field.related_name = "%s_rel_+" % name super().contribute_to_class(cls, name, **kwargs) if ( not self.remote_field.through and not cls._meta.abstract and not cls._meta.swapped ): self.remote_field.through = create_many_to_many_intermediary_model( self, cls ) setattr(cls, self.name, ManyToManyDescriptor(self.remote_field)) self.m2m_db_table = partial(self._get_m2m_db_table, cls._meta) def get_internal_type(self): return "ManyToManyField" # Copy those methods from ManyToManyField because they don't call super() internally contribute_to_related_class = models.ManyToManyField.__dict__[ "contribute_to_related_class" ] _get_m2m_attr = models.ManyToManyField.__dict__["_get_m2m_attr"] _get_m2m_reverse_attr = models.ManyToManyField.__dict__["_get_m2m_reverse_attr"] _get_m2m_db_table = models.ManyToManyField.__dict__["_get_m2m_db_table"] class InheritedManyToManyField(models.ManyToManyField): pass class MediumBlobField(models.BinaryField): """ A MySQL BinaryField that uses a different blob size. """ def db_type(self, connection): return "MEDIUMBLOB"
213c2fc76d6b93f65ccec8ef038197997aee5ab801eaa556050befab06514cc9
from django.test import TestCase from .models import Organiser, Pool, PoolStyle, Tournament class ExistingRelatedInstancesTests(TestCase): @classmethod def setUpTestData(cls): cls.t1 = Tournament.objects.create(name="Tourney 1") cls.t2 = Tournament.objects.create(name="Tourney 2") cls.o1 = Organiser.objects.create(name="Organiser 1") cls.p1 = Pool.objects.create( name="T1 Pool 1", tournament=cls.t1, organiser=cls.o1 ) cls.p2 = Pool.objects.create( name="T1 Pool 2", tournament=cls.t1, organiser=cls.o1 ) cls.p3 = Pool.objects.create( name="T2 Pool 1", tournament=cls.t2, organiser=cls.o1 ) cls.p4 = Pool.objects.create( name="T2 Pool 2", tournament=cls.t2, organiser=cls.o1 ) cls.ps1 = PoolStyle.objects.create(name="T1 Pool 2 Style", pool=cls.p2) cls.ps2 = PoolStyle.objects.create(name="T2 Pool 1 Style", pool=cls.p3) def test_foreign_key(self): with self.assertNumQueries(2): tournament = Tournament.objects.get(pk=self.t1.pk) pool = tournament.pool_set.all()[0] self.assertIs(tournament, pool.tournament) def test_foreign_key_prefetch_related(self): with self.assertNumQueries(2): tournament = Tournament.objects.prefetch_related("pool_set").get( pk=self.t1.pk ) pool = tournament.pool_set.all()[0] self.assertIs(tournament, pool.tournament) def test_foreign_key_multiple_prefetch(self): with self.assertNumQueries(2): tournaments = list( Tournament.objects.prefetch_related("pool_set").order_by("pk") ) pool1 = tournaments[0].pool_set.all()[0] self.assertIs(tournaments[0], pool1.tournament) pool2 = tournaments[1].pool_set.all()[0] self.assertIs(tournaments[1], pool2.tournament) def test_queryset_or(self): tournament_1 = self.t1 tournament_2 = self.t2 with self.assertNumQueries(1): pools = tournament_1.pool_set.all() | tournament_2.pool_set.all() related_objects = {pool.tournament for pool in pools} self.assertEqual(related_objects, {tournament_1, tournament_2}) def test_queryset_or_different_cached_items(self): tournament = self.t1 organiser = self.o1 with self.assertNumQueries(1): pools = tournament.pool_set.all() | organiser.pool_set.all() first = pools.filter(pk=self.p1.pk)[0] self.assertIs(first.tournament, tournament) self.assertIs(first.organiser, organiser) def test_queryset_or_only_one_with_precache(self): tournament_1 = self.t1 tournament_2 = self.t2 # 2 queries here as pool 3 has tournament 2, which is not cached with self.assertNumQueries(2): pools = tournament_1.pool_set.all() | Pool.objects.filter(pk=self.p3.pk) related_objects = {pool.tournament for pool in pools} self.assertEqual(related_objects, {tournament_1, tournament_2}) # and the other direction with self.assertNumQueries(2): pools = Pool.objects.filter(pk=self.p3.pk) | tournament_1.pool_set.all() related_objects = {pool.tournament for pool in pools} self.assertEqual(related_objects, {tournament_1, tournament_2}) def test_queryset_and(self): tournament = self.t1 organiser = self.o1 with self.assertNumQueries(1): pools = tournament.pool_set.all() & organiser.pool_set.all() first = pools.filter(pk=self.p1.pk)[0] self.assertIs(first.tournament, tournament) self.assertIs(first.organiser, organiser) def test_one_to_one(self): with self.assertNumQueries(2): style = PoolStyle.objects.get(pk=self.ps1.pk) pool = style.pool self.assertIs(style, pool.poolstyle) def test_one_to_one_select_related(self): with self.assertNumQueries(1): style = PoolStyle.objects.select_related("pool").get(pk=self.ps1.pk) pool = style.pool self.assertIs(style, pool.poolstyle) def test_one_to_one_multi_select_related(self): with self.assertNumQueries(1): poolstyles = list(PoolStyle.objects.select_related("pool").order_by("pk")) self.assertIs(poolstyles[0], poolstyles[0].pool.poolstyle) self.assertIs(poolstyles[1], poolstyles[1].pool.poolstyle) def test_one_to_one_prefetch_related(self): with self.assertNumQueries(2): style = PoolStyle.objects.prefetch_related("pool").get(pk=self.ps1.pk) pool = style.pool self.assertIs(style, pool.poolstyle) def test_one_to_one_multi_prefetch_related(self): with self.assertNumQueries(2): poolstyles = list(PoolStyle.objects.prefetch_related("pool").order_by("pk")) self.assertIs(poolstyles[0], poolstyles[0].pool.poolstyle) self.assertIs(poolstyles[1], poolstyles[1].pool.poolstyle) def test_reverse_one_to_one(self): with self.assertNumQueries(2): pool = Pool.objects.get(pk=self.p2.pk) style = pool.poolstyle self.assertIs(pool, style.pool) def test_reverse_one_to_one_select_related(self): with self.assertNumQueries(1): pool = Pool.objects.select_related("poolstyle").get(pk=self.p2.pk) style = pool.poolstyle self.assertIs(pool, style.pool) def test_reverse_one_to_one_prefetch_related(self): with self.assertNumQueries(2): pool = Pool.objects.prefetch_related("poolstyle").get(pk=self.p2.pk) style = pool.poolstyle self.assertIs(pool, style.pool) def test_reverse_one_to_one_multi_select_related(self): with self.assertNumQueries(1): pools = list(Pool.objects.select_related("poolstyle").order_by("pk")) self.assertIs(pools[1], pools[1].poolstyle.pool) self.assertIs(pools[2], pools[2].poolstyle.pool) def test_reverse_one_to_one_multi_prefetch_related(self): with self.assertNumQueries(2): pools = list(Pool.objects.prefetch_related("poolstyle").order_by("pk")) self.assertIs(pools[1], pools[1].poolstyle.pool) self.assertIs(pools[2], pools[2].poolstyle.pool)
11d7da1a75409644e0255602301693012b5dd9e1ddf22eb1975ef477a8808e2d
from django.contrib.admin import ModelAdmin, TabularInline from django.contrib.admin.helpers import InlineAdminForm from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import Permission, User from django.contrib.contenttypes.models import ContentType from django.test import RequestFactory, TestCase, override_settings from django.urls import reverse from .admin import InnerInline from .admin import site as admin_site from .models import ( Author, BinaryTree, Book, BothVerboseNameProfile, Chapter, Child, ChildModel1, ChildModel2, Fashionista, FootNote, Holder, Holder2, Holder3, Holder4, Inner, Inner2, Inner3, Inner4Stacked, Inner4Tabular, Novel, OutfitItem, Parent, ParentModelWithCustomPk, Person, Poll, Profile, ProfileCollection, Question, ShowInlineParent, Sighting, SomeChildModel, SomeParentModel, Teacher, VerboseNamePluralProfile, VerboseNameProfile, ) INLINE_CHANGELINK_HTML = 'class="inlinechangelink">Change</a>' class TestDataMixin: @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", email="[email protected]", password="secret" ) @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestInline(TestDataMixin, TestCase): factory = RequestFactory() @classmethod def setUpTestData(cls): super().setUpTestData() cls.holder = Holder.objects.create(dummy=13) Inner.objects.create(dummy=42, holder=cls.holder) cls.parent = SomeParentModel.objects.create(name="a") SomeChildModel.objects.create(name="b", position="0", parent=cls.parent) SomeChildModel.objects.create(name="c", position="1", parent=cls.parent) cls.view_only_user = User.objects.create_user( username="user", password="pwd", is_staff=True, ) parent_ct = ContentType.objects.get_for_model(SomeParentModel) child_ct = ContentType.objects.get_for_model(SomeChildModel) permission = Permission.objects.get( codename="view_someparentmodel", content_type=parent_ct, ) cls.view_only_user.user_permissions.add(permission) permission = Permission.objects.get( codename="view_somechildmodel", content_type=child_ct, ) cls.view_only_user.user_permissions.add(permission) def setUp(self): self.client.force_login(self.superuser) def test_can_delete(self): """ can_delete should be passed to inlineformset factory. """ response = self.client.get( reverse("admin:admin_inlines_holder_change", args=(self.holder.id,)) ) inner_formset = response.context["inline_admin_formsets"][0].formset expected = InnerInline.can_delete actual = inner_formset.can_delete self.assertEqual(expected, actual, "can_delete must be equal") def test_readonly_stacked_inline_label(self): """Bug #13174.""" holder = Holder.objects.create(dummy=42) Inner.objects.create(holder=holder, dummy=42, readonly="") response = self.client.get( reverse("admin:admin_inlines_holder_change", args=(holder.id,)) ) self.assertContains(response, "<label>Inner readonly label:</label>") def test_many_to_many_inlines(self): "Autogenerated many-to-many inlines are displayed correctly (#13407)" response = self.client.get(reverse("admin:admin_inlines_author_add")) # The heading for the m2m inline block uses the right text self.assertContains(response, "<h2>Author-book relationships</h2>") # The "add another" label is correct self.assertContains(response, "Add another Author-book relationship") # The '+' is dropped from the autogenerated form prefix (Author_books+) self.assertContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_primary(self): person = Person.objects.create(firstname="Imelda") item = OutfitItem.objects.create(name="Shoes") # Imelda likes shoes, but can't carry her own bags. data = { "shoppingweakness_set-TOTAL_FORMS": 1, "shoppingweakness_set-INITIAL_FORMS": 0, "shoppingweakness_set-MAX_NUM_FORMS": 0, "_save": "Save", "person": person.id, "max_weight": 0, "shoppingweakness_set-0-item": item.id, } response = self.client.post( reverse("admin:admin_inlines_fashionista_add"), data ) self.assertEqual(response.status_code, 302) self.assertEqual(len(Fashionista.objects.filter(person__firstname="Imelda")), 1) def test_tabular_inline_column_css_class(self): """ Field names are included in the context to output a field-specific CSS class name in the column headers. """ response = self.client.get(reverse("admin:admin_inlines_poll_add")) text_field, call_me_field = list( response.context["inline_admin_formset"].fields() ) # Editable field. self.assertEqual(text_field["name"], "text") self.assertContains(response, '<th class="column-text required">') # Read-only field. self.assertEqual(call_me_field["name"], "call_me") self.assertContains(response, '<th class="column-call_me">') def test_custom_form_tabular_inline_label(self): """ A model form with a form field specified (TitleForm.title1) should have its label rendered in the tabular inline. """ response = self.client.get(reverse("admin:admin_inlines_titlecollection_add")) self.assertContains( response, '<th class="column-title1 required">Title1</th>', html=True ) def test_custom_form_tabular_inline_extra_field_label(self): response = self.client.get(reverse("admin:admin_inlines_outfititem_add")) _, extra_field = list(response.context["inline_admin_formset"].fields()) self.assertEqual(extra_field["label"], "Extra field") def test_non_editable_custom_form_tabular_inline_extra_field_label(self): response = self.client.get(reverse("admin:admin_inlines_chapter_add")) _, extra_field = list(response.context["inline_admin_formset"].fields()) self.assertEqual(extra_field["label"], "Extra field") def test_custom_form_tabular_inline_overridden_label(self): """ SomeChildModelForm.__init__() overrides the label of a form field. That label is displayed in the TabularInline. """ response = self.client.get(reverse("admin:admin_inlines_someparentmodel_add")) field = list(response.context["inline_admin_formset"].fields())[0] self.assertEqual(field["label"], "new label") self.assertContains( response, '<th class="column-name required">New label</th>', html=True ) def test_tabular_non_field_errors(self): """ non_field_errors are displayed correctly, including the correct value for colspan. """ data = { "title_set-TOTAL_FORMS": 1, "title_set-INITIAL_FORMS": 0, "title_set-MAX_NUM_FORMS": 0, "_save": "Save", "title_set-0-title1": "a title", "title_set-0-title2": "a different title", } response = self.client.post( reverse("admin:admin_inlines_titlecollection_add"), data ) # Here colspan is "4": two fields (title1 and title2), one hidden field # and the delete checkbox. self.assertContains( response, '<tr class="row-form-errors"><td colspan="4">' '<ul class="errorlist nonfield">' "<li>The two titles must be the same</li></ul></td></tr>", ) def test_no_parent_callable_lookup(self): """Admin inline `readonly_field` shouldn't invoke parent ModelAdmin callable""" # Identically named callable isn't present in the parent ModelAdmin, # rendering of the add view shouldn't explode response = self.client.get(reverse("admin:admin_inlines_novel_add")) # View should have the child inlines section self.assertContains( response, '<div class="js-inline-admin-formset inline-group" id="chapter_set-group"', ) def test_callable_lookup(self): """ Admin inline should invoke local callable when its name is listed in readonly_fields. """ response = self.client.get(reverse("admin:admin_inlines_poll_add")) # Add parent object view should have the child inlines section self.assertContains( response, '<div class="js-inline-admin-formset inline-group" id="question_set-group"', ) # The right callable should be used for the inline readonly_fields # column cells self.assertContains(response, "<p>Callable in QuestionInline</p>") def test_help_text(self): """ The inlines' model field help texts are displayed when using both the stacked and tabular layouts. """ response = self.client.get(reverse("admin:admin_inlines_holder4_add")) self.assertContains( response, '<div class="help">Awesome stacked help text is awesome.</div>', 4 ) self.assertContains( response, '<img src="/static/admin/img/icon-unknown.svg" ' 'class="help help-tooltip" width="10" height="10" ' 'alt="(Awesome tabular help text is awesome.)" ' 'title="Awesome tabular help text is awesome.">', 1, ) # ReadOnly fields response = self.client.get(reverse("admin:admin_inlines_capofamiglia_add")) self.assertContains( response, '<img src="/static/admin/img/icon-unknown.svg" ' 'class="help help-tooltip" width="10" height="10" ' 'alt="(Help text for ReadOnlyInline)" ' 'title="Help text for ReadOnlyInline">', 1, ) def test_tabular_model_form_meta_readonly_field(self): """ Tabular inlines use ModelForm.Meta.help_texts and labels for read-only fields. """ response = self.client.get(reverse("admin:admin_inlines_someparentmodel_add")) self.assertContains( response, '<img src="/static/admin/img/icon-unknown.svg" ' 'class="help help-tooltip" width="10" height="10" ' 'alt="(Help text from ModelForm.Meta)" ' 'title="Help text from ModelForm.Meta">', ) self.assertContains(response, "Label from ModelForm.Meta") def test_inline_hidden_field_no_column(self): """#18263 -- Make sure hidden fields don't get a column in tabular inlines""" parent = SomeParentModel.objects.create(name="a") SomeChildModel.objects.create(name="b", position="0", parent=parent) SomeChildModel.objects.create(name="c", position="1", parent=parent) response = self.client.get( reverse("admin:admin_inlines_someparentmodel_change", args=(parent.pk,)) ) self.assertNotContains(response, '<td class="field-position">') self.assertInHTML( '<input id="id_somechildmodel_set-1-position" ' 'name="somechildmodel_set-1-position" type="hidden" value="1">', response.rendered_content, ) def test_tabular_inline_hidden_field_with_view_only_permissions(self): """ Content of hidden field is not visible in tabular inline when user has view-only permission. """ self.client.force_login(self.view_only_user) url = reverse( "tabular_inline_hidden_field_admin:admin_inlines_someparentmodel_change", args=(self.parent.pk,), ) response = self.client.get(url) self.assertInHTML( '<th class="column-position hidden">Position</th>', response.rendered_content, ) self.assertInHTML( '<td class="field-position hidden"><p>0</p></td>', response.rendered_content ) self.assertInHTML( '<td class="field-position hidden"><p>1</p></td>', response.rendered_content ) def test_stacked_inline_hidden_field_with_view_only_permissions(self): """ Content of hidden field is not visible in stacked inline when user has view-only permission. """ self.client.force_login(self.view_only_user) url = reverse( "stacked_inline_hidden_field_in_group_admin:" "admin_inlines_someparentmodel_change", args=(self.parent.pk,), ) response = self.client.get(url) # The whole line containing name + position fields is not hidden. self.assertContains( response, '<div class="form-row field-name field-position">' ) # The div containing the position field is hidden. self.assertInHTML( '<div class="fieldBox field-position hidden">' '<label class="inline">Position:</label>' '<div class="readonly">0</div></div>', response.rendered_content, ) self.assertInHTML( '<div class="fieldBox field-position hidden">' '<label class="inline">Position:</label>' '<div class="readonly">1</div></div>', response.rendered_content, ) def test_stacked_inline_single_hidden_field_in_line_with_view_only_permissions( self, ): """ Content of hidden field is not visible in stacked inline when user has view-only permission and the field is grouped on a separate line. """ self.client.force_login(self.view_only_user) url = reverse( "stacked_inline_hidden_field_on_single_line_admin:" "admin_inlines_someparentmodel_change", args=(self.parent.pk,), ) response = self.client.get(url) # The whole line containing position field is hidden. self.assertInHTML( '<div class="form-row hidden field-position">' "<div><label>Position:</label>" '<div class="readonly">0</div></div></div>', response.rendered_content, ) self.assertInHTML( '<div class="form-row hidden field-position">' "<div><label>Position:</label>" '<div class="readonly">1</div></div></div>', response.rendered_content, ) def test_tabular_inline_with_hidden_field_non_field_errors_has_correct_colspan( self, ): """ In tabular inlines, when a form has non-field errors, those errors are rendered in a table line with a single cell spanning the whole table width. Colspan must be equal to the number of visible columns. """ parent = SomeParentModel.objects.create(name="a") child = SomeChildModel.objects.create(name="b", position="0", parent=parent) url = reverse( "tabular_inline_hidden_field_admin:admin_inlines_someparentmodel_change", args=(parent.id,), ) data = { "name": parent.name, "somechildmodel_set-TOTAL_FORMS": 1, "somechildmodel_set-INITIAL_FORMS": 1, "somechildmodel_set-MIN_NUM_FORMS": 0, "somechildmodel_set-MAX_NUM_FORMS": 1000, "_save": "Save", "somechildmodel_set-0-id": child.id, "somechildmodel_set-0-parent": parent.id, "somechildmodel_set-0-name": child.name, "somechildmodel_set-0-position": 1, } response = self.client.post(url, data) # Form has 3 visible columns and 1 hidden column. self.assertInHTML( '<thead><tr><th class="original"></th>' '<th class="column-name required">Name</th>' '<th class="column-position required hidden">Position</th>' "<th>Delete?</th></tr></thead>", response.rendered_content, ) # The non-field error must be spanned on 3 (visible) columns. self.assertInHTML( '<tr class="row-form-errors"><td colspan="3">' '<ul class="errorlist nonfield"><li>A non-field error</li></ul></td></tr>', response.rendered_content, ) def test_non_related_name_inline(self): """ Multiple inlines with related_name='+' have correct form prefixes. """ response = self.client.get(reverse("admin:admin_inlines_capofamiglia_add")) self.assertContains( response, '<input type="hidden" name="-1-0-id" id="id_-1-0-id">', html=True ) self.assertContains( response, '<input type="hidden" name="-1-0-capo_famiglia" ' 'id="id_-1-0-capo_famiglia">', html=True, ) self.assertContains( response, '<input id="id_-1-0-name" type="text" class="vTextField" name="-1-0-name" ' 'maxlength="100">', html=True, ) self.assertContains( response, '<input type="hidden" name="-2-0-id" id="id_-2-0-id">', html=True ) self.assertContains( response, '<input type="hidden" name="-2-0-capo_famiglia" ' 'id="id_-2-0-capo_famiglia">', html=True, ) self.assertContains( response, '<input id="id_-2-0-name" type="text" class="vTextField" name="-2-0-name" ' 'maxlength="100">', html=True, ) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_localize_pk_shortcut(self): """ The "View on Site" link is correct for locales that use thousand separators. """ holder = Holder.objects.create(pk=123456789, dummy=42) inner = Inner.objects.create(pk=987654321, holder=holder, dummy=42, readonly="") response = self.client.get( reverse("admin:admin_inlines_holder_change", args=(holder.id,)) ) inner_shortcut = "r/%s/%s/" % ( ContentType.objects.get_for_model(inner).pk, inner.pk, ) self.assertContains(response, inner_shortcut) def test_custom_pk_shortcut(self): """ The "View on Site" link is correct for models with a custom primary key field. """ parent = ParentModelWithCustomPk.objects.create(my_own_pk="foo", name="Foo") child1 = ChildModel1.objects.create(my_own_pk="bar", name="Bar", parent=parent) child2 = ChildModel2.objects.create(my_own_pk="baz", name="Baz", parent=parent) response = self.client.get( reverse("admin:admin_inlines_parentmodelwithcustompk_change", args=("foo",)) ) child1_shortcut = "r/%s/%s/" % ( ContentType.objects.get_for_model(child1).pk, child1.pk, ) child2_shortcut = "r/%s/%s/" % ( ContentType.objects.get_for_model(child2).pk, child2.pk, ) self.assertContains(response, child1_shortcut) self.assertContains(response, child2_shortcut) def test_create_inlines_on_inherited_model(self): """ An object can be created with inlines when it inherits another class. """ data = { "name": "Martian", "sighting_set-TOTAL_FORMS": 1, "sighting_set-INITIAL_FORMS": 0, "sighting_set-MAX_NUM_FORMS": 0, "sighting_set-0-place": "Zone 51", "_save": "Save", } response = self.client.post( reverse("admin:admin_inlines_extraterrestrial_add"), data ) self.assertEqual(response.status_code, 302) self.assertEqual(Sighting.objects.filter(et__name="Martian").count(), 1) def test_custom_get_extra_form(self): bt_head = BinaryTree.objects.create(name="Tree Head") BinaryTree.objects.create(name="First Child", parent=bt_head) # The maximum number of forms should respect 'get_max_num' on the # ModelAdmin max_forms_input = ( '<input id="id_binarytree_set-MAX_NUM_FORMS" ' 'name="binarytree_set-MAX_NUM_FORMS" type="hidden" value="%d">' ) # The total number of forms will remain the same in either case total_forms_hidden = ( '<input id="id_binarytree_set-TOTAL_FORMS" ' 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="2">' ) response = self.client.get(reverse("admin:admin_inlines_binarytree_add")) self.assertInHTML(max_forms_input % 3, response.rendered_content) self.assertInHTML(total_forms_hidden, response.rendered_content) response = self.client.get( reverse("admin:admin_inlines_binarytree_change", args=(bt_head.id,)) ) self.assertInHTML(max_forms_input % 2, response.rendered_content) self.assertInHTML(total_forms_hidden, response.rendered_content) def test_min_num(self): """ min_num and extra determine number of forms. """ class MinNumInline(TabularInline): model = BinaryTree min_num = 2 extra = 3 modeladmin = ModelAdmin(BinaryTree, admin_site) modeladmin.inlines = [MinNumInline] min_forms = ( '<input id="id_binarytree_set-MIN_NUM_FORMS" ' 'name="binarytree_set-MIN_NUM_FORMS" type="hidden" value="2">' ) total_forms = ( '<input id="id_binarytree_set-TOTAL_FORMS" ' 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="5">' ) request = self.factory.get(reverse("admin:admin_inlines_binarytree_add")) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request) self.assertInHTML(min_forms, response.rendered_content) self.assertInHTML(total_forms, response.rendered_content) def test_custom_min_num(self): bt_head = BinaryTree.objects.create(name="Tree Head") BinaryTree.objects.create(name="First Child", parent=bt_head) class MinNumInline(TabularInline): model = BinaryTree extra = 3 def get_min_num(self, request, obj=None, **kwargs): if obj: return 5 return 2 modeladmin = ModelAdmin(BinaryTree, admin_site) modeladmin.inlines = [MinNumInline] min_forms = ( '<input id="id_binarytree_set-MIN_NUM_FORMS" ' 'name="binarytree_set-MIN_NUM_FORMS" type="hidden" value="%d">' ) total_forms = ( '<input id="id_binarytree_set-TOTAL_FORMS" ' 'name="binarytree_set-TOTAL_FORMS" type="hidden" value="%d">' ) request = self.factory.get(reverse("admin:admin_inlines_binarytree_add")) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request) self.assertInHTML(min_forms % 2, response.rendered_content) self.assertInHTML(total_forms % 5, response.rendered_content) request = self.factory.get( reverse("admin:admin_inlines_binarytree_change", args=(bt_head.id,)) ) request.user = User(username="super", is_superuser=True) response = modeladmin.changeform_view(request, object_id=str(bt_head.id)) self.assertInHTML(min_forms % 5, response.rendered_content) self.assertInHTML(total_forms % 8, response.rendered_content) def test_inline_nonauto_noneditable_pk(self): response = self.client.get(reverse("admin:admin_inlines_author_add")) self.assertContains( response, '<input id="id_nonautopkbook_set-0-rand_pk" ' 'name="nonautopkbook_set-0-rand_pk" type="hidden">', html=True, ) self.assertContains( response, '<input id="id_nonautopkbook_set-2-0-rand_pk" ' 'name="nonautopkbook_set-2-0-rand_pk" type="hidden">', html=True, ) def test_inline_nonauto_noneditable_inherited_pk(self): response = self.client.get(reverse("admin:admin_inlines_author_add")) self.assertContains( response, '<input id="id_nonautopkbookchild_set-0-nonautopkbook_ptr" ' 'name="nonautopkbookchild_set-0-nonautopkbook_ptr" type="hidden">', html=True, ) self.assertContains( response, '<input id="id_nonautopkbookchild_set-2-nonautopkbook_ptr" ' 'name="nonautopkbookchild_set-2-nonautopkbook_ptr" type="hidden">', html=True, ) def test_inline_editable_pk(self): response = self.client.get(reverse("admin:admin_inlines_author_add")) self.assertContains( response, '<input class="vIntegerField" id="id_editablepkbook_set-0-manual_pk" ' 'name="editablepkbook_set-0-manual_pk" type="number">', html=True, count=1, ) self.assertContains( response, '<input class="vIntegerField" id="id_editablepkbook_set-2-0-manual_pk" ' 'name="editablepkbook_set-2-0-manual_pk" type="number">', html=True, count=1, ) def test_stacked_inline_edit_form_contains_has_original_class(self): holder = Holder.objects.create(dummy=1) holder.inner_set.create(dummy=1) response = self.client.get( reverse("admin:admin_inlines_holder_change", args=(holder.pk,)) ) self.assertContains( response, '<div class="inline-related has_original" id="inner_set-0">', count=1, ) self.assertContains( response, '<div class="inline-related" id="inner_set-1">', count=1 ) def test_inlines_show_change_link_registered(self): "Inlines `show_change_link` for registered models when enabled." holder = Holder4.objects.create(dummy=1) item1 = Inner4Stacked.objects.create(dummy=1, holder=holder) item2 = Inner4Tabular.objects.create(dummy=1, holder=holder) items = ( ("inner4stacked", item1.pk), ("inner4tabular", item2.pk), ) response = self.client.get( reverse("admin:admin_inlines_holder4_change", args=(holder.pk,)) ) self.assertTrue( response.context["inline_admin_formset"].opts.has_registered_model ) for model, pk in items: url = reverse("admin:admin_inlines_%s_change" % model, args=(pk,)) self.assertContains( response, '<a href="%s" %s' % (url, INLINE_CHANGELINK_HTML) ) def test_inlines_show_change_link_unregistered(self): "Inlines `show_change_link` disabled for unregistered models." parent = ParentModelWithCustomPk.objects.create(my_own_pk="foo", name="Foo") ChildModel1.objects.create(my_own_pk="bar", name="Bar", parent=parent) ChildModel2.objects.create(my_own_pk="baz", name="Baz", parent=parent) response = self.client.get( reverse("admin:admin_inlines_parentmodelwithcustompk_change", args=("foo",)) ) self.assertFalse( response.context["inline_admin_formset"].opts.has_registered_model ) self.assertNotContains(response, INLINE_CHANGELINK_HTML) def test_tabular_inline_show_change_link_false_registered(self): "Inlines `show_change_link` disabled by default." poll = Poll.objects.create(name="New poll") Question.objects.create(poll=poll) response = self.client.get( reverse("admin:admin_inlines_poll_change", args=(poll.pk,)) ) self.assertTrue( response.context["inline_admin_formset"].opts.has_registered_model ) self.assertNotContains(response, INLINE_CHANGELINK_HTML) def test_noneditable_inline_has_field_inputs(self): """Inlines without change permission shows field inputs on add form.""" response = self.client.get( reverse("admin:admin_inlines_novelreadonlychapter_add") ) self.assertContains( response, '<input type="text" name="chapter_set-0-name" ' 'class="vTextField" maxlength="40" id="id_chapter_set-0-name">', html=True, ) def test_inlines_plural_heading_foreign_key(self): response = self.client.get(reverse("admin:admin_inlines_holder4_add")) self.assertContains(response, "<h2>Inner4 stackeds</h2>", html=True) self.assertContains(response, "<h2>Inner4 tabulars</h2>", html=True) def test_inlines_singular_heading_one_to_one(self): response = self.client.get(reverse("admin:admin_inlines_person_add")) self.assertContains(response, "<h2>Author</h2>", html=True) # Tabular. self.assertContains(response, "<h2>Fashionista</h2>", html=True) # Stacked. def test_inlines_based_on_model_state(self): parent = ShowInlineParent.objects.create(show_inlines=False) data = { "show_inlines": "on", "_save": "Save", } change_url = reverse( "admin:admin_inlines_showinlineparent_change", args=(parent.id,), ) response = self.client.post(change_url, data) self.assertEqual(response.status_code, 302) parent.refresh_from_db() self.assertIs(parent.show_inlines, True) @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestInlineMedia(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_inline_media_only_base(self): holder = Holder(dummy=13) holder.save() Inner(dummy=42, holder=holder).save() change_url = reverse("admin:admin_inlines_holder_change", args=(holder.id,)) response = self.client.get(change_url) self.assertContains(response, "my_awesome_admin_scripts.js") def test_inline_media_only_inline(self): holder = Holder3(dummy=13) holder.save() Inner3(dummy=42, holder=holder).save() change_url = reverse("admin:admin_inlines_holder3_change", args=(holder.id,)) response = self.client.get(change_url) self.assertEqual( response.context["inline_admin_formsets"][0].media._js, [ "admin/js/vendor/jquery/jquery.min.js", "my_awesome_inline_scripts.js", "custom_number.js", "admin/js/jquery.init.js", "admin/js/inlines.js", ], ) self.assertContains(response, "my_awesome_inline_scripts.js") def test_all_inline_media(self): holder = Holder2(dummy=13) holder.save() Inner2(dummy=42, holder=holder).save() change_url = reverse("admin:admin_inlines_holder2_change", args=(holder.id,)) response = self.client.get(change_url) self.assertContains(response, "my_awesome_admin_scripts.js") self.assertContains(response, "my_awesome_inline_scripts.js") @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestInlineAdminForm(TestCase): def test_immutable_content_type(self): """Regression for #9362 The problem depends only on InlineAdminForm and its "original" argument, so we can safely set the other arguments to None/{}. We just need to check that the content_type argument of Child isn't altered by the internals of the inline form.""" sally = Teacher.objects.create(name="Sally") john = Parent.objects.create(name="John") joe = Child.objects.create(name="Joe", teacher=sally, parent=john) iaf = InlineAdminForm(None, None, {}, {}, joe) parent_ct = ContentType.objects.get_for_model(Parent) self.assertEqual(iaf.original.content_type, parent_ct) @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestInlineProtectedOnDelete(TestDataMixin, TestCase): def setUp(self): self.client.force_login(self.superuser) def test_deleting_inline_with_protected_delete_does_not_validate(self): lotr = Novel.objects.create(name="Lord of the rings") chapter = Chapter.objects.create(novel=lotr, name="Many Meetings") foot_note = FootNote.objects.create(chapter=chapter, note="yadda yadda") change_url = reverse("admin:admin_inlines_novel_change", args=(lotr.id,)) response = self.client.get(change_url) data = { "name": lotr.name, "chapter_set-TOTAL_FORMS": 1, "chapter_set-INITIAL_FORMS": 1, "chapter_set-MAX_NUM_FORMS": 1000, "_save": "Save", "chapter_set-0-id": chapter.id, "chapter_set-0-name": chapter.name, "chapter_set-0-novel": lotr.id, "chapter_set-0-DELETE": "on", } response = self.client.post(change_url, data) self.assertContains( response, "Deleting chapter %s would require deleting " "the following protected related objects: foot note %s" % (chapter, foot_note), ) @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestInlinePermissions(TestCase): """ Make sure the admin respects permissions for objects that are edited inline. Refs #8060. """ @classmethod def setUpTestData(cls): cls.user = User(username="admin", is_staff=True, is_active=True) cls.user.set_password("secret") cls.user.save() cls.author_ct = ContentType.objects.get_for_model(Author) cls.holder_ct = ContentType.objects.get_for_model(Holder2) cls.book_ct = ContentType.objects.get_for_model(Book) cls.inner_ct = ContentType.objects.get_for_model(Inner2) # User always has permissions to add and change Authors, and Holders, # the main (parent) models of the inlines. Permissions on the inlines # vary per test. permission = Permission.objects.get( codename="add_author", content_type=cls.author_ct ) cls.user.user_permissions.add(permission) permission = Permission.objects.get( codename="change_author", content_type=cls.author_ct ) cls.user.user_permissions.add(permission) permission = Permission.objects.get( codename="add_holder2", content_type=cls.holder_ct ) cls.user.user_permissions.add(permission) permission = Permission.objects.get( codename="change_holder2", content_type=cls.holder_ct ) cls.user.user_permissions.add(permission) author = Author.objects.create(pk=1, name="The Author") cls.book = author.books.create(name="The inline Book") cls.author_change_url = reverse( "admin:admin_inlines_author_change", args=(author.id,) ) # Get the ID of the automatically created intermediate model for the # Author-Book m2m. author_book_auto_m2m_intermediate = Author.books.through.objects.get( author=author, book=cls.book ) cls.author_book_auto_m2m_intermediate_id = author_book_auto_m2m_intermediate.pk cls.holder = Holder2.objects.create(dummy=13) cls.inner2 = Inner2.objects.create(dummy=42, holder=cls.holder) def setUp(self): self.holder_change_url = reverse( "admin:admin_inlines_holder2_change", args=(self.holder.id,) ) self.client.force_login(self.user) def test_inline_add_m2m_noperm(self): response = self.client.get(reverse("admin:admin_inlines_author_add")) # No change permission on books, so no inline self.assertNotContains(response, "<h2>Author-book relationships</h2>") self.assertNotContains(response, "Add another Author-Book Relationship") self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_add_fk_noperm(self): response = self.client.get(reverse("admin:admin_inlines_holder2_add")) # No permissions on Inner2s, so no inline self.assertNotContains(response, "<h2>Inner2s</h2>") self.assertNotContains(response, "Add another Inner2") self.assertNotContains(response, 'id="id_inner2_set-TOTAL_FORMS"') def test_inline_change_m2m_noperm(self): response = self.client.get(self.author_change_url) # No change permission on books, so no inline self.assertNotContains(response, "<h2>Author-book relationships</h2>") self.assertNotContains(response, "Add another Author-Book Relationship") self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_change_fk_noperm(self): response = self.client.get(self.holder_change_url) # No permissions on Inner2s, so no inline self.assertNotContains(response, "<h2>Inner2s</h2>") self.assertNotContains(response, "Add another Inner2") self.assertNotContains(response, 'id="id_inner2_set-TOTAL_FORMS"') def test_inline_add_m2m_view_only_perm(self): permission = Permission.objects.get( codename="view_book", content_type=self.book_ct ) self.user.user_permissions.add(permission) response = self.client.get(reverse("admin:admin_inlines_author_add")) # View-only inlines. (It could be nicer to hide the empty, non-editable # inlines on the add page.) self.assertIs( response.context["inline_admin_formset"].has_view_permission, True ) self.assertIs( response.context["inline_admin_formset"].has_add_permission, False ) self.assertIs( response.context["inline_admin_formset"].has_change_permission, False ) self.assertIs( response.context["inline_admin_formset"].has_delete_permission, False ) self.assertContains(response, "<h2>Author-book relationships</h2>") self.assertContains( response, '<input type="hidden" name="Author_books-TOTAL_FORMS" value="0" ' 'id="id_Author_books-TOTAL_FORMS">', html=True, ) self.assertNotContains(response, "Add another Author-Book Relationship") def test_inline_add_m2m_add_perm(self): permission = Permission.objects.get( codename="add_book", content_type=self.book_ct ) self.user.user_permissions.add(permission) response = self.client.get(reverse("admin:admin_inlines_author_add")) # No change permission on Books, so no inline self.assertNotContains(response, "<h2>Author-book relationships</h2>") self.assertNotContains(response, "Add another Author-Book Relationship") self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') def test_inline_add_fk_add_perm(self): permission = Permission.objects.get( codename="add_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(reverse("admin:admin_inlines_holder2_add")) # Add permission on inner2s, so we get the inline self.assertContains(response, "<h2>Inner2s</h2>") self.assertContains(response, "Add another Inner2") self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" ' 'value="3" name="inner2_set-TOTAL_FORMS">', html=True, ) def test_inline_change_m2m_add_perm(self): permission = Permission.objects.get( codename="add_book", content_type=self.book_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.author_change_url) # No change permission on books, so no inline self.assertNotContains(response, "<h2>Author-book relationships</h2>") self.assertNotContains(response, "Add another Author-Book Relationship") self.assertNotContains(response, 'id="id_Author_books-TOTAL_FORMS"') self.assertNotContains(response, 'id="id_Author_books-0-DELETE"') def test_inline_change_m2m_view_only_perm(self): permission = Permission.objects.get( codename="view_book", content_type=self.book_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.author_change_url) # View-only inlines. self.assertIs( response.context["inline_admin_formset"].has_view_permission, True ) self.assertIs( response.context["inline_admin_formset"].has_add_permission, False ) self.assertIs( response.context["inline_admin_formset"].has_change_permission, False ) self.assertIs( response.context["inline_admin_formset"].has_delete_permission, False ) self.assertContains(response, "<h2>Author-book relationships</h2>") self.assertContains( response, '<input type="hidden" name="Author_books-TOTAL_FORMS" value="1" ' 'id="id_Author_books-TOTAL_FORMS">', html=True, ) # The field in the inline is read-only. self.assertContains(response, "<p>%s</p>" % self.book) self.assertNotContains( response, '<input type="checkbox" name="Author_books-0-DELETE" ' 'id="id_Author_books-0-DELETE">', html=True, ) def test_inline_change_m2m_change_perm(self): permission = Permission.objects.get( codename="change_book", content_type=self.book_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.author_change_url) # We have change perm on books, so we can add/change/delete inlines self.assertIs( response.context["inline_admin_formset"].has_view_permission, True ) self.assertIs(response.context["inline_admin_formset"].has_add_permission, True) self.assertIs( response.context["inline_admin_formset"].has_change_permission, True ) self.assertIs( response.context["inline_admin_formset"].has_delete_permission, True ) self.assertContains(response, "<h2>Author-book relationships</h2>") self.assertContains(response, "Add another Author-book relationship") self.assertContains( response, '<input type="hidden" id="id_Author_books-TOTAL_FORMS" ' 'value="4" name="Author_books-TOTAL_FORMS">', html=True, ) self.assertContains( response, '<input type="hidden" id="id_Author_books-0-id" value="%i" ' 'name="Author_books-0-id">' % self.author_book_auto_m2m_intermediate_id, html=True, ) self.assertContains(response, 'id="id_Author_books-0-DELETE"') def test_inline_change_fk_add_perm(self): permission = Permission.objects.get( codename="add_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Add permission on inner2s, so we can add but not modify existing self.assertContains(response, "<h2>Inner2s</h2>") self.assertContains(response, "Add another Inner2") # 3 extra forms only, not the existing instance form self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="3" ' 'name="inner2_set-TOTAL_FORMS">', html=True, ) self.assertNotContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" ' 'name="inner2_set-0-id">' % self.inner2.id, html=True, ) def test_inline_change_fk_change_perm(self): permission = Permission.objects.get( codename="change_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Change permission on inner2s, so we can change existing but not add new self.assertContains(response, "<h2>Inner2s</h2>", count=2) # Just the one form for existing instances self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" ' 'name="inner2_set-TOTAL_FORMS">', html=True, ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" ' 'name="inner2_set-0-id">' % self.inner2.id, html=True, ) # max-num 0 means we can't add new ones self.assertContains( response, '<input type="hidden" id="id_inner2_set-MAX_NUM_FORMS" value="0" ' 'name="inner2_set-MAX_NUM_FORMS">', html=True, ) # TabularInline self.assertContains( response, '<th class="column-dummy required">Dummy</th>', html=True ) self.assertContains( response, '<input type="number" name="inner2_set-2-0-dummy" value="%s" ' 'class="vIntegerField" id="id_inner2_set-2-0-dummy">' % self.inner2.dummy, html=True, ) def test_inline_change_fk_add_change_perm(self): permission = Permission.objects.get( codename="add_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) permission = Permission.objects.get( codename="change_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Add/change perm, so we can add new and change existing self.assertContains(response, "<h2>Inner2s</h2>") # One form for existing instance and three extra for new self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" ' 'name="inner2_set-TOTAL_FORMS">', html=True, ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" ' 'name="inner2_set-0-id">' % self.inner2.id, html=True, ) def test_inline_change_fk_change_del_perm(self): permission = Permission.objects.get( codename="change_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) permission = Permission.objects.get( codename="delete_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # Change/delete perm on inner2s, so we can change/delete existing self.assertContains(response, "<h2>Inner2s</h2>") # One form for existing instance only, no new self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="1" ' 'name="inner2_set-TOTAL_FORMS">', html=True, ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" ' 'name="inner2_set-0-id">' % self.inner2.id, html=True, ) self.assertContains(response, 'id="id_inner2_set-0-DELETE"') def test_inline_change_fk_all_perms(self): permission = Permission.objects.get( codename="add_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) permission = Permission.objects.get( codename="change_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) permission = Permission.objects.get( codename="delete_inner2", content_type=self.inner_ct ) self.user.user_permissions.add(permission) response = self.client.get(self.holder_change_url) # All perms on inner2s, so we can add/change/delete self.assertContains(response, "<h2>Inner2s</h2>", count=2) # One form for existing instance only, three for new self.assertContains( response, '<input type="hidden" id="id_inner2_set-TOTAL_FORMS" value="4" ' 'name="inner2_set-TOTAL_FORMS">', html=True, ) self.assertContains( response, '<input type="hidden" id="id_inner2_set-0-id" value="%i" ' 'name="inner2_set-0-id">' % self.inner2.id, html=True, ) self.assertContains(response, 'id="id_inner2_set-0-DELETE"') # TabularInline self.assertContains( response, '<th class="column-dummy required">Dummy</th>', html=True ) self.assertContains( response, '<input type="number" name="inner2_set-2-0-dummy" value="%s" ' 'class="vIntegerField" id="id_inner2_set-2-0-dummy">' % self.inner2.dummy, html=True, ) @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestReadOnlyChangeViewInlinePermissions(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user( "testing", password="password", is_staff=True ) cls.user.user_permissions.add( Permission.objects.get( codename="view_poll", content_type=ContentType.objects.get_for_model(Poll), ) ) cls.user.user_permissions.add( *Permission.objects.filter( codename__endswith="question", content_type=ContentType.objects.get_for_model(Question), ).values_list("pk", flat=True) ) cls.poll = Poll.objects.create(name="Survey") cls.add_url = reverse("admin:admin_inlines_poll_add") cls.change_url = reverse("admin:admin_inlines_poll_change", args=(cls.poll.id,)) def setUp(self): self.client.force_login(self.user) def test_add_url_not_allowed(self): response = self.client.get(self.add_url) self.assertEqual(response.status_code, 403) response = self.client.post(self.add_url, {}) self.assertEqual(response.status_code, 403) def test_post_to_change_url_not_allowed(self): response = self.client.post(self.change_url, {}) self.assertEqual(response.status_code, 403) def test_get_to_change_url_is_allowed(self): response = self.client.get(self.change_url) self.assertEqual(response.status_code, 200) def test_main_model_is_rendered_as_read_only(self): response = self.client.get(self.change_url) self.assertContains( response, '<div class="readonly">%s</div>' % self.poll.name, html=True ) input = ( '<input type="text" name="name" value="%s" class="vTextField" ' 'maxlength="40" required id="id_name">' ) self.assertNotContains(response, input % self.poll.name, html=True) def test_inlines_are_rendered_as_read_only(self): question = Question.objects.create( text="How will this be rendered?", poll=self.poll ) response = self.client.get(self.change_url) self.assertContains( response, '<td class="field-text"><p>%s</p></td>' % question.text, html=True ) self.assertNotContains(response, 'id="id_question_set-0-text"') self.assertNotContains(response, 'id="id_related_objs-0-DELETE"') def test_submit_line_shows_only_close_button(self): response = self.client.get(self.change_url) self.assertContains( response, '<a href="/admin/admin_inlines/poll/" class="closelink">Close</a>', html=True, ) delete_link = '<p class="deletelink-box"><a href="/admin/admin_inlines/poll/%s/delete/" class="deletelink">Delete</a></p>' # noqa self.assertNotContains(response, delete_link % self.poll.id, html=True) self.assertNotContains( response, '<input type="submit" value="Save and add another" name="_addanother">', ) self.assertNotContains( response, '<input type="submit" value="Save and continue editing" name="_continue">', ) def test_inline_delete_buttons_are_not_shown(self): Question.objects.create(text="How will this be rendered?", poll=self.poll) response = self.client.get(self.change_url) self.assertNotContains( response, '<input type="checkbox" name="question_set-0-DELETE" ' 'id="id_question_set-0-DELETE">', html=True, ) def test_extra_inlines_are_not_shown(self): response = self.client.get(self.change_url) self.assertNotContains(response, 'id="id_question_set-0-text"') @override_settings(ROOT_URLCONF="admin_inlines.urls") class TestVerboseNameInlineForms(TestDataMixin, TestCase): factory = RequestFactory() def test_verbose_name_inline(self): class NonVerboseProfileInline(TabularInline): model = Profile verbose_name = "Non-verbose childs" class VerboseNameProfileInline(TabularInline): model = VerboseNameProfile verbose_name = "Childs with verbose name" class VerboseNamePluralProfileInline(TabularInline): model = VerboseNamePluralProfile verbose_name = "Childs with verbose name plural" class BothVerboseNameProfileInline(TabularInline): model = BothVerboseNameProfile verbose_name = "Childs with both verbose names" modeladmin = ModelAdmin(ProfileCollection, admin_site) modeladmin.inlines = [ NonVerboseProfileInline, VerboseNameProfileInline, VerboseNamePluralProfileInline, BothVerboseNameProfileInline, ] obj = ProfileCollection.objects.create() url = reverse("admin:admin_inlines_profilecollection_change", args=(obj.pk,)) request = self.factory.get(url) request.user = self.superuser response = modeladmin.changeform_view(request) self.assertNotContains(response, "Add another Profile") # Non-verbose model. self.assertContains(response, "<h2>Non-verbose childss</h2>") self.assertContains(response, "Add another Non-verbose child") self.assertNotContains(response, "<h2>Profiles</h2>") # Model with verbose name. self.assertContains(response, "<h2>Childs with verbose names</h2>") self.assertContains(response, "Add another Childs with verbose name") self.assertNotContains(response, "<h2>Model with verbose name onlys</h2>") self.assertNotContains(response, "Add another Model with verbose name only") # Model with verbose name plural. self.assertContains(response, "<h2>Childs with verbose name plurals</h2>") self.assertContains(response, "Add another Childs with verbose name plural") self.assertNotContains(response, "<h2>Model with verbose name plural only</h2>") # Model with both verbose names. self.assertContains(response, "<h2>Childs with both verbose namess</h2>") self.assertContains(response, "Add another Childs with both verbose names") self.assertNotContains(response, "<h2>Model with both - plural name</h2>") self.assertNotContains(response, "Add another Model with both - name") def test_verbose_name_plural_inline(self): class NonVerboseProfileInline(TabularInline): model = Profile verbose_name_plural = "Non-verbose childs" class VerboseNameProfileInline(TabularInline): model = VerboseNameProfile verbose_name_plural = "Childs with verbose name" class VerboseNamePluralProfileInline(TabularInline): model = VerboseNamePluralProfile verbose_name_plural = "Childs with verbose name plural" class BothVerboseNameProfileInline(TabularInline): model = BothVerboseNameProfile verbose_name_plural = "Childs with both verbose names" modeladmin = ModelAdmin(ProfileCollection, admin_site) modeladmin.inlines = [ NonVerboseProfileInline, VerboseNameProfileInline, VerboseNamePluralProfileInline, BothVerboseNameProfileInline, ] obj = ProfileCollection.objects.create() url = reverse("admin:admin_inlines_profilecollection_change", args=(obj.pk,)) request = self.factory.get(url) request.user = self.superuser response = modeladmin.changeform_view(request) # Non-verbose model. self.assertContains(response, "<h2>Non-verbose childs</h2>") self.assertContains(response, "Add another Profile") self.assertNotContains(response, "<h2>Profiles</h2>") # Model with verbose name. self.assertContains(response, "<h2>Childs with verbose name</h2>") self.assertContains(response, "Add another Model with verbose name only") self.assertNotContains(response, "<h2>Model with verbose name onlys</h2>") # Model with verbose name plural. self.assertContains(response, "<h2>Childs with verbose name plural</h2>") self.assertContains(response, "Add another Profile") self.assertNotContains(response, "<h2>Model with verbose name plural only</h2>") # Model with both verbose names. self.assertContains(response, "<h2>Childs with both verbose names</h2>") self.assertContains(response, "Add another Model with both - name") self.assertNotContains(response, "<h2>Model with both - plural name</h2>") def test_both_verbose_names_inline(self): class NonVerboseProfileInline(TabularInline): model = Profile verbose_name = "Non-verbose childs - name" verbose_name_plural = "Non-verbose childs - plural name" class VerboseNameProfileInline(TabularInline): model = VerboseNameProfile verbose_name = "Childs with verbose name - name" verbose_name_plural = "Childs with verbose name - plural name" class VerboseNamePluralProfileInline(TabularInline): model = VerboseNamePluralProfile verbose_name = "Childs with verbose name plural - name" verbose_name_plural = "Childs with verbose name plural - plural name" class BothVerboseNameProfileInline(TabularInline): model = BothVerboseNameProfile verbose_name = "Childs with both - name" verbose_name_plural = "Childs with both - plural name" modeladmin = ModelAdmin(ProfileCollection, admin_site) modeladmin.inlines = [ NonVerboseProfileInline, VerboseNameProfileInline, VerboseNamePluralProfileInline, BothVerboseNameProfileInline, ] obj = ProfileCollection.objects.create() url = reverse("admin:admin_inlines_profilecollection_change", args=(obj.pk,)) request = self.factory.get(url) request.user = self.superuser response = modeladmin.changeform_view(request) self.assertNotContains(response, "Add another Profile") # Non-verbose model. self.assertContains(response, "<h2>Non-verbose childs - plural name</h2>") self.assertContains(response, "Add another Non-verbose childs - name") self.assertNotContains(response, "<h2>Profiles</h2>") # Model with verbose name. self.assertContains(response, "<h2>Childs with verbose name - plural name</h2>") self.assertContains(response, "Add another Childs with verbose name - name") self.assertNotContains(response, "<h2>Model with verbose name onlys</h2>") # Model with verbose name plural. self.assertContains( response, "<h2>Childs with verbose name plural - plural name</h2>", ) self.assertContains( response, "Add another Childs with verbose name plural - name", ) self.assertNotContains(response, "<h2>Model with verbose name plural only</h2>") # Model with both verbose names. self.assertContains(response, "<h2>Childs with both - plural name</h2>") self.assertContains(response, "Add another Childs with both - name") self.assertNotContains(response, "<h2>Model with both - plural name</h2>") self.assertNotContains(response, "Add another Model with both - name") @override_settings(ROOT_URLCONF="admin_inlines.urls") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_inlines"] + AdminSeleniumTestCase.available_apps def setUp(self): User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) def test_add_stackeds(self): """ The "Add another XXX" link correctly adds items to the stacked formset. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder4_add") ) inline_id = "#inner4stacked_set-group" rows_selector = "%s .dynamic-inner4stacked_set" % inline_id self.assertCountSeleniumElements(rows_selector, 3) add_button = self.selenium.find_element( By.LINK_TEXT, "Add another Inner4 stacked" ) add_button.click() self.assertCountSeleniumElements(rows_selector, 4) def test_delete_stackeds(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder4_add") ) inline_id = "#inner4stacked_set-group" rows_selector = "%s .dynamic-inner4stacked_set" % inline_id self.assertCountSeleniumElements(rows_selector, 3) add_button = self.selenium.find_element( By.LINK_TEXT, "Add another Inner4 stacked" ) add_button.click() add_button.click() self.assertCountSeleniumElements(rows_selector, 5) for delete_link in self.selenium.find_elements( By.CSS_SELECTOR, "%s .inline-deletelink" % inline_id ): delete_link.click() with self.disable_implicit_wait(): self.assertCountSeleniumElements(rows_selector, 0) def test_delete_invalid_stacked_inlines(self): from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder4_add") ) inline_id = "#inner4stacked_set-group" rows_selector = "%s .dynamic-inner4stacked_set" % inline_id self.assertCountSeleniumElements(rows_selector, 3) add_button = self.selenium.find_element( By.LINK_TEXT, "Add another Inner4 stacked", ) add_button.click() add_button.click() self.assertCountSeleniumElements("#id_inner4stacked_set-4-dummy", 1) # Enter some data and click 'Save'. self.selenium.find_element(By.NAME, "dummy").send_keys("1") self.selenium.find_element(By.NAME, "inner4stacked_set-0-dummy").send_keys( "100" ) self.selenium.find_element(By.NAME, "inner4stacked_set-1-dummy").send_keys( "101" ) self.selenium.find_element(By.NAME, "inner4stacked_set-2-dummy").send_keys( "222" ) self.selenium.find_element(By.NAME, "inner4stacked_set-3-dummy").send_keys( "103" ) self.selenium.find_element(By.NAME, "inner4stacked_set-4-dummy").send_keys( "222" ) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # Sanity check. self.assertCountSeleniumElements(rows_selector, 5) errorlist = self.selenium.find_element( By.CSS_SELECTOR, "%s .dynamic-inner4stacked_set .errorlist li" % inline_id, ) self.assertEqual("Please correct the duplicate values below.", errorlist.text) delete_link = self.selenium.find_element( By.CSS_SELECTOR, "#inner4stacked_set-4 .inline-deletelink" ) delete_link.click() self.assertCountSeleniumElements(rows_selector, 4) with self.disable_implicit_wait(), self.assertRaises(NoSuchElementException): self.selenium.find_element( By.CSS_SELECTOR, "%s .dynamic-inner4stacked_set .errorlist li" % inline_id, ) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # The objects have been created in the database. self.assertEqual(Inner4Stacked.objects.count(), 4) def test_delete_invalid_tabular_inlines(self): from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder4_add") ) inline_id = "#inner4tabular_set-group" rows_selector = "%s .dynamic-inner4tabular_set" % inline_id self.assertCountSeleniumElements(rows_selector, 3) add_button = self.selenium.find_element( By.LINK_TEXT, "Add another Inner4 tabular" ) add_button.click() add_button.click() self.assertCountSeleniumElements("#id_inner4tabular_set-4-dummy", 1) # Enter some data and click 'Save'. self.selenium.find_element(By.NAME, "dummy").send_keys("1") self.selenium.find_element(By.NAME, "inner4tabular_set-0-dummy").send_keys( "100" ) self.selenium.find_element(By.NAME, "inner4tabular_set-1-dummy").send_keys( "101" ) self.selenium.find_element(By.NAME, "inner4tabular_set-2-dummy").send_keys( "222" ) self.selenium.find_element(By.NAME, "inner4tabular_set-3-dummy").send_keys( "103" ) self.selenium.find_element(By.NAME, "inner4tabular_set-4-dummy").send_keys( "222" ) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # Sanity Check. self.assertCountSeleniumElements(rows_selector, 5) # Non-field errorlist is in its own <tr> just before # tr#inner4tabular_set-3: errorlist = self.selenium.find_element( By.CSS_SELECTOR, "%s #inner4tabular_set-3 + .row-form-errors .errorlist li" % inline_id, ) self.assertEqual("Please correct the duplicate values below.", errorlist.text) delete_link = self.selenium.find_element( By.CSS_SELECTOR, "#inner4tabular_set-4 .inline-deletelink" ) delete_link.click() self.assertCountSeleniumElements(rows_selector, 4) with self.disable_implicit_wait(), self.assertRaises(NoSuchElementException): self.selenium.find_element( By.CSS_SELECTOR, "%s .dynamic-inner4tabular_set .errorlist li" % inline_id, ) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # The objects have been created in the database. self.assertEqual(Inner4Tabular.objects.count(), 4) def test_add_inlines(self): """ The "Add another XXX" link correctly adds items to the inline form. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_profilecollection_add") ) # There's only one inline to start with and it has the correct ID. self.assertCountSeleniumElements(".dynamic-profile_set", 1) self.assertEqual( self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-profile_set")[ 0 ].get_attribute("id"), "profile_set-0", ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-0 input[name=profile_set-0-first_name]", 1 ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-0 input[name=profile_set-0-last_name]", 1 ) # Add an inline self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() # The inline has been added, it has the right id, and it contains the # correct fields. self.assertCountSeleniumElements(".dynamic-profile_set", 2) self.assertEqual( self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-profile_set")[ 1 ].get_attribute("id"), "profile_set-1", ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-1 input[name=profile_set-1-first_name]", 1 ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-1 input[name=profile_set-1-last_name]", 1 ) # Let's add another one to be sure self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() self.assertCountSeleniumElements(".dynamic-profile_set", 3) self.assertEqual( self.selenium.find_elements(By.CSS_SELECTOR, ".dynamic-profile_set")[ 2 ].get_attribute("id"), "profile_set-2", ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-2 input[name=profile_set-2-first_name]", 1 ) self.assertCountSeleniumElements( ".dynamic-profile_set#profile_set-2 input[name=profile_set-2-last_name]", 1 ) # Enter some data and click 'Save' self.selenium.find_element(By.NAME, "profile_set-0-first_name").send_keys( "0 first name 1" ) self.selenium.find_element(By.NAME, "profile_set-0-last_name").send_keys( "0 last name 2" ) self.selenium.find_element(By.NAME, "profile_set-1-first_name").send_keys( "1 first name 1" ) self.selenium.find_element(By.NAME, "profile_set-1-last_name").send_keys( "1 last name 2" ) self.selenium.find_element(By.NAME, "profile_set-2-first_name").send_keys( "2 first name 1" ) self.selenium.find_element(By.NAME, "profile_set-2-last_name").send_keys( "2 last name 2" ) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # The objects have been created in the database self.assertEqual(ProfileCollection.objects.count(), 1) self.assertEqual(Profile.objects.count(), 3) def test_add_inline_link_absent_for_view_only_parent_model(self): from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By user = User.objects.create_user("testing", password="password", is_staff=True) user.user_permissions.add( Permission.objects.get( codename="view_poll", content_type=ContentType.objects.get_for_model(Poll), ) ) user.user_permissions.add( *Permission.objects.filter( codename__endswith="question", content_type=ContentType.objects.get_for_model(Question), ).values_list("pk", flat=True) ) self.admin_login(username="testing", password="password") poll = Poll.objects.create(name="Survey") change_url = reverse("admin:admin_inlines_poll_change", args=(poll.id,)) self.selenium.get(self.live_server_url + change_url) with self.disable_implicit_wait(): with self.assertRaises(NoSuchElementException): self.selenium.find_element(By.LINK_TEXT, "Add another Question") def test_delete_inlines(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_profilecollection_add") ) # Add a few inlines self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() self.selenium.find_element(By.LINK_TEXT, "Add another Profile").click() self.assertCountSeleniumElements( "#profile_set-group table tr.dynamic-profile_set", 5 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-0", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-1", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-2", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-3", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-4", 1 ) # Click on a few delete buttons self.selenium.find_element( By.CSS_SELECTOR, "form#profilecollection_form tr.dynamic-profile_set#profile_set-1 " "td.delete a", ).click() self.selenium.find_element( By.CSS_SELECTOR, "form#profilecollection_form tr.dynamic-profile_set#profile_set-2 " "td.delete a", ).click() # The rows are gone and the IDs have been re-sequenced self.assertCountSeleniumElements( "#profile_set-group table tr.dynamic-profile_set", 3 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-0", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-1", 1 ) self.assertCountSeleniumElements( "form#profilecollection_form tr.dynamic-profile_set#profile_set-2", 1 ) def test_collapsed_inlines(self): from selenium.webdriver.common.by import By # Collapsed inlines have SHOW/HIDE links. self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_author_add") ) # One field is in a stacked inline, other in a tabular one. test_fields = [ "#id_nonautopkbook_set-0-title", "#id_nonautopkbook_set-2-0-title", ] show_links = self.selenium.find_elements(By.LINK_TEXT, "SHOW") self.assertEqual(len(show_links), 3) for show_index, field_name in enumerate(test_fields, 0): self.wait_until_invisible(field_name) show_links[show_index].click() self.wait_until_visible(field_name) hide_links = self.selenium.find_elements(By.LINK_TEXT, "HIDE") self.assertEqual(len(hide_links), 2) for hide_index, field_name in enumerate(test_fields, 0): self.wait_until_visible(field_name) hide_links[hide_index].click() self.wait_until_invisible(field_name) def test_added_stacked_inline_with_collapsed_fields(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_teacher_add") ) self.selenium.find_element(By.LINK_TEXT, "Add another Child").click() test_fields = ["#id_child_set-0-name", "#id_child_set-1-name"] show_links = self.selenium.find_elements(By.LINK_TEXT, "SHOW") self.assertEqual(len(show_links), 2) for show_index, field_name in enumerate(test_fields, 0): self.wait_until_invisible(field_name) show_links[show_index].click() self.wait_until_visible(field_name) hide_links = self.selenium.find_elements(By.LINK_TEXT, "HIDE") self.assertEqual(len(hide_links), 2) for hide_index, field_name in enumerate(test_fields, 0): self.wait_until_visible(field_name) hide_links[hide_index].click() self.wait_until_invisible(field_name) def assertBorder(self, element, border): width, style, color = border.split(" ") border_properties = [ "border-bottom-%s", "border-left-%s", "border-right-%s", "border-top-%s", ] for prop in border_properties: prop = prop % "width" self.assertEqual(element.value_of_css_property(prop), width) for prop in border_properties: prop = prop % "style" self.assertEqual(element.value_of_css_property(prop), style) # Convert hex color to rgb. self.assertRegex(color, "#[0-9a-f]{6}") r, g, b = int(color[1:3], 16), int(color[3:5], 16), int(color[5:], 16) # The value may be expressed as either rgb() or rgba() depending on the # browser. colors = [ "rgb(%d, %d, %d)" % (r, g, b), "rgba(%d, %d, %d, 1)" % (r, g, b), ] for prop in border_properties: prop = prop % "color" self.assertIn(element.value_of_css_property(prop), colors) def test_inline_formset_error_input_border(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder5_add") ) self.wait_until_visible("#id_dummy") self.selenium.find_element(By.ID, "id_dummy").send_keys(1) fields = ["id_inner5stacked_set-0-dummy", "id_inner5tabular_set-0-dummy"] show_links = self.selenium.find_elements(By.LINK_TEXT, "SHOW") for show_index, field_name in enumerate(fields): show_links[show_index].click() self.wait_until_visible("#" + field_name) self.selenium.find_element(By.ID, field_name).send_keys(1) # Before save all inputs have default border for inline in ("stacked", "tabular"): for field_name in ("name", "select", "text"): element_id = "id_inner5%s_set-0-%s" % (inline, field_name) self.assertBorder( self.selenium.find_element(By.ID, element_id), "1px solid #cccccc", ) self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() # Test the red border around inputs by css selectors stacked_selectors = [".errors input", ".errors select", ".errors textarea"] for selector in stacked_selectors: self.assertBorder( self.selenium.find_element(By.CSS_SELECTOR, selector), "1px solid #ba2121", ) tabular_selectors = [ "td ul.errorlist + input", "td ul.errorlist + select", "td ul.errorlist + textarea", ] for selector in tabular_selectors: self.assertBorder( self.selenium.find_element(By.CSS_SELECTOR, selector), "1px solid #ba2121", ) def test_inline_formset_error(self): from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_holder5_add") ) stacked_inline_formset_selector = ( "div#inner5stacked_set-group fieldset.module.collapse" ) tabular_inline_formset_selector = ( "div#inner5tabular_set-group fieldset.module.collapse" ) # Inlines without errors, both inlines collapsed self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() self.assertCountSeleniumElements( stacked_inline_formset_selector + ".collapsed", 1 ) self.assertCountSeleniumElements( tabular_inline_formset_selector + ".collapsed", 1 ) show_links = self.selenium.find_elements(By.LINK_TEXT, "SHOW") self.assertEqual(len(show_links), 2) # Inlines with errors, both inlines expanded test_fields = ["#id_inner5stacked_set-0-dummy", "#id_inner5tabular_set-0-dummy"] for show_index, field_name in enumerate(test_fields): show_links[show_index].click() self.wait_until_visible(field_name) self.selenium.find_element(By.ID, field_name[1:]).send_keys(1) hide_links = self.selenium.find_elements(By.LINK_TEXT, "HIDE") self.assertEqual(len(hide_links), 2) for hide_index, field_name in enumerate(test_fields): hide_link = hide_links[hide_index] self.selenium.execute_script( "window.scrollTo(0, %s);" % hide_link.location["y"] ) hide_link.click() self.wait_until_invisible(field_name) with self.wait_page_loaded(): self.selenium.find_element(By.XPATH, '//input[@value="Save"]').click() with self.disable_implicit_wait(): self.assertCountSeleniumElements( stacked_inline_formset_selector + ".collapsed", 0 ) self.assertCountSeleniumElements( tabular_inline_formset_selector + ".collapsed", 0 ) self.assertCountSeleniumElements(stacked_inline_formset_selector, 1) self.assertCountSeleniumElements(tabular_inline_formset_selector, 1) def test_inlines_verbose_name(self): """ The item added by the "Add another XXX" link must use the correct verbose_name in the inline form. """ from selenium.webdriver.common.by import By self.admin_login(username="super", password="secret") # Hide sidebar. self.selenium.get( self.live_server_url + reverse("admin:admin_inlines_course_add") ) toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) toggle_button.click() # Each combination of horizontal/vertical filter with stacked/tabular # inlines. tests = [ "admin:admin_inlines_course_add", "admin:admin_inlines_courseproxy_add", "admin:admin_inlines_courseproxy1_add", "admin:admin_inlines_courseproxy2_add", ] css_selector = ".dynamic-class_set#class_set-%s h2" for url_name in tests: with self.subTest(url=url_name): self.selenium.get(self.live_server_url + reverse(url_name)) # First inline shows the verbose_name. available, chosen = self.selenium.find_elements( By.CSS_SELECTOR, css_selector % 0 ) self.assertEqual(available.text, "AVAILABLE ATTENDANT") self.assertEqual(chosen.text, "CHOSEN ATTENDANT") # Added inline should also have the correct verbose_name. self.selenium.find_element(By.LINK_TEXT, "Add another Class").click() available, chosen = self.selenium.find_elements( By.CSS_SELECTOR, css_selector % 1 ) self.assertEqual(available.text, "AVAILABLE ATTENDANT") self.assertEqual(chosen.text, "CHOSEN ATTENDANT") # Third inline should also have the correct verbose_name. self.selenium.find_element(By.LINK_TEXT, "Add another Class").click() available, chosen = self.selenium.find_elements( By.CSS_SELECTOR, css_selector % 2 ) self.assertEqual(available.text, "AVAILABLE ATTENDANT") self.assertEqual(chosen.text, "CHOSEN ATTENDANT")
362c7ce2866c7e2fa08cff881b571ed245aa62d3ff4f81af020f9679b37ab985
""" Testing of admin inline formsets. """ import random from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Parent(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Teacher(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Child(models.Model): name = models.CharField(max_length=50) teacher = models.ForeignKey(Teacher, models.CASCADE) content_type = models.ForeignKey(ContentType, models.CASCADE) object_id = models.PositiveIntegerField() parent = GenericForeignKey() def __str__(self): return "I am %s, a child of %s" % (self.name, self.parent) class Book(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=50) books = models.ManyToManyField(Book) person = models.OneToOneField("Person", models.CASCADE, null=True) class NonAutoPKBook(models.Model): rand_pk = models.IntegerField(primary_key=True, editable=False) author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=50) def save(self, *args, **kwargs): while not self.rand_pk: test_pk = random.randint(1, 99999) if not NonAutoPKBook.objects.filter(rand_pk=test_pk).exists(): self.rand_pk = test_pk super().save(*args, **kwargs) class NonAutoPKBookChild(NonAutoPKBook): pass class EditablePKBook(models.Model): manual_pk = models.IntegerField(primary_key=True) author = models.ForeignKey(Author, models.CASCADE) title = models.CharField(max_length=50) class Holder(models.Model): dummy = models.IntegerField() class Inner(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder, models.CASCADE) readonly = models.CharField("Inner readonly label", max_length=1) def get_absolute_url(self): return "/inner/" class Holder2(models.Model): dummy = models.IntegerField() class Inner2(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder2, models.CASCADE) class Holder3(models.Model): dummy = models.IntegerField() class Inner3(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder3, models.CASCADE) # Models for ticket #8190 class Holder4(models.Model): dummy = models.IntegerField() class Inner4Stacked(models.Model): dummy = models.IntegerField(help_text="Awesome stacked help text is awesome.") holder = models.ForeignKey(Holder4, models.CASCADE) class Meta: constraints = [ models.UniqueConstraint( fields=["dummy", "holder"], name="unique_stacked_dummy_per_holder" ) ] class Inner4Tabular(models.Model): dummy = models.IntegerField(help_text="Awesome tabular help text is awesome.") holder = models.ForeignKey(Holder4, models.CASCADE) class Meta: constraints = [ models.UniqueConstraint( fields=["dummy", "holder"], name="unique_tabular_dummy_per_holder" ) ] # Models for ticket #31441 class Holder5(models.Model): dummy = models.IntegerField() class Inner5Stacked(models.Model): name = models.CharField(max_length=10) select = models.CharField(choices=(("1", "One"), ("2", "Two")), max_length=10) text = models.TextField() dummy = models.IntegerField() holder = models.ForeignKey(Holder5, models.CASCADE) class Inner5Tabular(models.Model): name = models.CharField(max_length=10) select = models.CharField(choices=(("1", "One"), ("2", "Two")), max_length=10) text = models.TextField() dummy = models.IntegerField() holder = models.ForeignKey(Holder5, models.CASCADE) # Models for #12749 class Person(models.Model): firstname = models.CharField(max_length=15) class OutfitItem(models.Model): name = models.CharField(max_length=15) class Fashionista(models.Model): person = models.OneToOneField(Person, models.CASCADE, primary_key=True) weaknesses = models.ManyToManyField( OutfitItem, through="ShoppingWeakness", blank=True ) class ShoppingWeakness(models.Model): fashionista = models.ForeignKey(Fashionista, models.CASCADE) item = models.ForeignKey(OutfitItem, models.CASCADE) # Models for #13510 class TitleCollection(models.Model): pass class Title(models.Model): collection = models.ForeignKey( TitleCollection, models.SET_NULL, blank=True, null=True ) title1 = models.CharField(max_length=100) title2 = models.CharField(max_length=100) # Models for #15424 class Poll(models.Model): name = models.CharField(max_length=40) class Question(models.Model): text = models.CharField(max_length=40) poll = models.ForeignKey(Poll, models.CASCADE) class Novel(models.Model): name = models.CharField(max_length=40) class NovelReadonlyChapter(Novel): class Meta: proxy = True class Chapter(models.Model): name = models.CharField(max_length=40) novel = models.ForeignKey(Novel, models.CASCADE) class FootNote(models.Model): """ Model added for ticket 19838 """ chapter = models.ForeignKey(Chapter, models.PROTECT) note = models.CharField(max_length=40) # Models for #16838 class CapoFamiglia(models.Model): name = models.CharField(max_length=100) class Consigliere(models.Model): name = models.CharField(max_length=100, help_text="Help text for Consigliere") capo_famiglia = models.ForeignKey(CapoFamiglia, models.CASCADE, related_name="+") class SottoCapo(models.Model): name = models.CharField(max_length=100) capo_famiglia = models.ForeignKey(CapoFamiglia, models.CASCADE, related_name="+") class ReadOnlyInline(models.Model): name = models.CharField(max_length=100, help_text="Help text for ReadOnlyInline") capo_famiglia = models.ForeignKey(CapoFamiglia, models.CASCADE) # Models for #18433 class ParentModelWithCustomPk(models.Model): my_own_pk = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=100) class ChildModel1(models.Model): my_own_pk = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=100) parent = models.ForeignKey(ParentModelWithCustomPk, models.CASCADE) def get_absolute_url(self): return "/child_model1/" class ChildModel2(models.Model): my_own_pk = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=100) parent = models.ForeignKey(ParentModelWithCustomPk, models.CASCADE) def get_absolute_url(self): return "/child_model2/" # Models for #19425 class BinaryTree(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey("self", models.SET_NULL, null=True, blank=True) # Models for #19524 class LifeForm(models.Model): pass class ExtraTerrestrial(LifeForm): name = models.CharField(max_length=100) class Sighting(models.Model): et = models.ForeignKey(ExtraTerrestrial, models.CASCADE) place = models.CharField(max_length=100) # Models for #18263 class SomeParentModel(models.Model): name = models.CharField(max_length=1) class SomeChildModel(models.Model): name = models.CharField(max_length=1) position = models.PositiveIntegerField() parent = models.ForeignKey(SomeParentModel, models.CASCADE) readonly_field = models.CharField(max_length=1) # Models for #30231 class Course(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Class(models.Model): person = models.ManyToManyField(Person, verbose_name="attendant") course = models.ForeignKey(Course, on_delete=models.CASCADE) class CourseProxy(Course): class Meta: proxy = True class CourseProxy1(Course): class Meta: proxy = True class CourseProxy2(Course): class Meta: proxy = True # Other models class ShowInlineParent(models.Model): show_inlines = models.BooleanField(default=False) class ShowInlineChild(models.Model): parent = models.ForeignKey(ShowInlineParent, on_delete=models.CASCADE) class ProfileCollection(models.Model): pass class Profile(models.Model): collection = models.ForeignKey( ProfileCollection, models.SET_NULL, blank=True, null=True ) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class VerboseNameProfile(Profile): class Meta: verbose_name = "Model with verbose name only" class VerboseNamePluralProfile(Profile): class Meta: verbose_name_plural = "Model with verbose name plural only" class BothVerboseNameProfile(Profile): class Meta: verbose_name = "Model with both - name" verbose_name_plural = "Model with both - plural name"
f3bb3afac58c23c6ea4c9c67311e2963083ae593d6b6bf9f02c2a8d7f5cd0e0a
from django import forms from django.contrib import admin from django.core.exceptions import ValidationError from django.db import models from .models import ( Author, BinaryTree, CapoFamiglia, Chapter, Child, ChildModel1, ChildModel2, Class, Consigliere, Course, CourseProxy, CourseProxy1, CourseProxy2, EditablePKBook, ExtraTerrestrial, Fashionista, FootNote, Holder, Holder2, Holder3, Holder4, Holder5, Inner, Inner2, Inner3, Inner4Stacked, Inner4Tabular, Inner5Stacked, Inner5Tabular, NonAutoPKBook, NonAutoPKBookChild, Novel, NovelReadonlyChapter, OutfitItem, ParentModelWithCustomPk, Person, Poll, Profile, ProfileCollection, Question, ReadOnlyInline, ShoppingWeakness, ShowInlineChild, ShowInlineParent, Sighting, SomeChildModel, SomeParentModel, SottoCapo, Teacher, Title, TitleCollection, ) site = admin.AdminSite(name="admin") class BookInline(admin.TabularInline): model = Author.books.through class NonAutoPKBookTabularInline(admin.TabularInline): model = NonAutoPKBook classes = ("collapse",) class NonAutoPKBookChildTabularInline(admin.TabularInline): model = NonAutoPKBookChild classes = ("collapse",) class NonAutoPKBookStackedInline(admin.StackedInline): model = NonAutoPKBook classes = ("collapse",) class EditablePKBookTabularInline(admin.TabularInline): model = EditablePKBook class EditablePKBookStackedInline(admin.StackedInline): model = EditablePKBook class AuthorAdmin(admin.ModelAdmin): inlines = [ BookInline, NonAutoPKBookTabularInline, NonAutoPKBookStackedInline, EditablePKBookTabularInline, EditablePKBookStackedInline, NonAutoPKBookChildTabularInline, ] class InnerInline(admin.StackedInline): model = Inner can_delete = False readonly_fields = ("readonly",) # For bug #13174 tests. class HolderAdmin(admin.ModelAdmin): class Media: js = ("my_awesome_admin_scripts.js",) class ReadOnlyInlineInline(admin.TabularInline): model = ReadOnlyInline readonly_fields = ["name"] class InnerInline2(admin.StackedInline): model = Inner2 class Media: js = ("my_awesome_inline_scripts.js",) class InnerInline2Tabular(admin.TabularInline): model = Inner2 class CustomNumberWidget(forms.NumberInput): class Media: js = ("custom_number.js",) class InnerInline3(admin.StackedInline): model = Inner3 formfield_overrides = { models.IntegerField: {"widget": CustomNumberWidget}, } class Media: js = ("my_awesome_inline_scripts.js",) class TitleForm(forms.ModelForm): title1 = forms.CharField(max_length=100) def clean(self): cleaned_data = self.cleaned_data title1 = cleaned_data.get("title1") title2 = cleaned_data.get("title2") if title1 != title2: raise ValidationError("The two titles must be the same") return cleaned_data class TitleInline(admin.TabularInline): model = Title form = TitleForm extra = 1 class Inner4StackedInline(admin.StackedInline): model = Inner4Stacked show_change_link = True class Inner4TabularInline(admin.TabularInline): model = Inner4Tabular show_change_link = True class Holder4Admin(admin.ModelAdmin): inlines = [Inner4StackedInline, Inner4TabularInline] class Inner5StackedInline(admin.StackedInline): model = Inner5Stacked classes = ("collapse",) class Inner5TabularInline(admin.TabularInline): model = Inner5Tabular classes = ("collapse",) class Holder5Admin(admin.ModelAdmin): inlines = [Inner5StackedInline, Inner5TabularInline] class InlineWeakness(admin.TabularInline): model = ShoppingWeakness extra = 1 class WeaknessForm(forms.ModelForm): extra_field = forms.CharField() class Meta: model = ShoppingWeakness fields = "__all__" class WeaknessInlineCustomForm(admin.TabularInline): model = ShoppingWeakness form = WeaknessForm class FootNoteForm(forms.ModelForm): extra_field = forms.CharField() class Meta: model = FootNote fields = "__all__" class FootNoteNonEditableInlineCustomForm(admin.TabularInline): model = FootNote form = FootNoteForm def has_change_permission(self, request, obj=None): return False class QuestionInline(admin.TabularInline): model = Question readonly_fields = ["call_me"] def call_me(self, obj): return "Callable in QuestionInline" class PollAdmin(admin.ModelAdmin): inlines = [QuestionInline] def call_me(self, obj): return "Callable in PollAdmin" class ChapterInline(admin.TabularInline): model = Chapter readonly_fields = ["call_me"] def call_me(self, obj): return "Callable in ChapterInline" class NovelAdmin(admin.ModelAdmin): inlines = [ChapterInline] class ReadOnlyChapterInline(admin.TabularInline): model = Chapter def has_change_permission(self, request, obj=None): return False class NovelReadonlyChapterAdmin(admin.ModelAdmin): inlines = [ReadOnlyChapterInline] class ConsigliereInline(admin.TabularInline): model = Consigliere class SottoCapoInline(admin.TabularInline): model = SottoCapo class ProfileInline(admin.TabularInline): model = Profile extra = 1 # admin for #18433 class ChildModel1Inline(admin.TabularInline): model = ChildModel1 class ChildModel2Inline(admin.StackedInline): model = ChildModel2 # admin for #19425 and #18388 class BinaryTreeAdmin(admin.TabularInline): model = BinaryTree def get_extra(self, request, obj=None, **kwargs): extra = 2 if obj: return extra - obj.binarytree_set.count() return extra def get_max_num(self, request, obj=None, **kwargs): max_num = 3 if obj: return max_num - obj.binarytree_set.count() return max_num # admin for #19524 class SightingInline(admin.TabularInline): model = Sighting # admin and form for #18263 class SomeChildModelForm(forms.ModelForm): class Meta: fields = "__all__" model = SomeChildModel widgets = { "position": forms.HiddenInput, } labels = {"readonly_field": "Label from ModelForm.Meta"} help_texts = {"readonly_field": "Help text from ModelForm.Meta"} def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["name"].label = "new label" class SomeChildModelInline(admin.TabularInline): model = SomeChildModel form = SomeChildModelForm readonly_fields = ("readonly_field",) class StudentInline(admin.StackedInline): model = Child extra = 1 fieldsets = [ ("Name", {"fields": ("name",), "classes": ("collapse",)}), ] class TeacherAdmin(admin.ModelAdmin): inlines = [StudentInline] class AuthorTabularInline(admin.TabularInline): model = Author class FashonistaStackedInline(admin.StackedInline): model = Fashionista # Admin for #30231 class ClassStackedHorizontal(admin.StackedInline): model = Class extra = 1 filter_horizontal = ["person"] class ClassAdminStackedHorizontal(admin.ModelAdmin): inlines = [ClassStackedHorizontal] class ClassTabularHorizontal(admin.TabularInline): model = Class extra = 1 filter_horizontal = ["person"] class ClassAdminTabularHorizontal(admin.ModelAdmin): inlines = [ClassTabularHorizontal] class ClassTabularVertical(admin.TabularInline): model = Class extra = 1 filter_vertical = ["person"] class ClassAdminTabularVertical(admin.ModelAdmin): inlines = [ClassTabularVertical] class ClassStackedVertical(admin.StackedInline): model = Class extra = 1 filter_vertical = ["person"] class ClassAdminStackedVertical(admin.ModelAdmin): inlines = [ClassStackedVertical] class ChildHiddenFieldForm(forms.ModelForm): class Meta: model = SomeChildModel fields = ["name", "position", "parent"] widgets = {"position": forms.HiddenInput} def _post_clean(self): super()._post_clean() if self.instance is not None and self.instance.position == 1: self.add_error(None, ValidationError("A non-field error")) class ChildHiddenFieldTabularInline(admin.TabularInline): model = SomeChildModel form = ChildHiddenFieldForm class ChildHiddenFieldInFieldsGroupStackedInline(admin.StackedInline): model = SomeChildModel form = ChildHiddenFieldForm fields = [("name", "position")] class ChildHiddenFieldOnSingleLineStackedInline(admin.StackedInline): model = SomeChildModel form = ChildHiddenFieldForm fields = ("name", "position") class ShowInlineChildInline(admin.StackedInline): model = ShowInlineChild class ShowInlineParentAdmin(admin.ModelAdmin): def get_inlines(self, request, obj): if obj is not None and obj.show_inlines: return [ShowInlineChildInline] return [] site.register(TitleCollection, inlines=[TitleInline]) # Test bug #12561 and #12778 # only ModelAdmin media site.register(Holder, HolderAdmin, inlines=[InnerInline]) # ModelAdmin and Inline media site.register(Holder2, HolderAdmin, inlines=[InnerInline2, InnerInline2Tabular]) # only Inline media site.register(Holder3, inlines=[InnerInline3]) site.register(Poll, PollAdmin) site.register(Novel, NovelAdmin) site.register(NovelReadonlyChapter, NovelReadonlyChapterAdmin) site.register(Fashionista, inlines=[InlineWeakness]) site.register(Holder4, Holder4Admin) site.register(Holder5, Holder5Admin) site.register(Author, AuthorAdmin) site.register( CapoFamiglia, inlines=[ConsigliereInline, SottoCapoInline, ReadOnlyInlineInline] ) site.register(ProfileCollection, inlines=[ProfileInline]) site.register(ParentModelWithCustomPk, inlines=[ChildModel1Inline, ChildModel2Inline]) site.register(BinaryTree, inlines=[BinaryTreeAdmin]) site.register(ExtraTerrestrial, inlines=[SightingInline]) site.register(SomeParentModel, inlines=[SomeChildModelInline]) site.register([Question, Inner4Stacked, Inner4Tabular]) site.register(Teacher, TeacherAdmin) site.register(Chapter, inlines=[FootNoteNonEditableInlineCustomForm]) site.register(OutfitItem, inlines=[WeaknessInlineCustomForm]) site.register(Person, inlines=[AuthorTabularInline, FashonistaStackedInline]) site.register(Course, ClassAdminStackedHorizontal) site.register(CourseProxy, ClassAdminStackedVertical) site.register(CourseProxy1, ClassAdminTabularVertical) site.register(CourseProxy2, ClassAdminTabularHorizontal) site.register(ShowInlineParent, ShowInlineParentAdmin) # Used to test hidden fields in tabular and stacked inlines. site2 = admin.AdminSite(name="tabular_inline_hidden_field_admin") site2.register(SomeParentModel, inlines=[ChildHiddenFieldTabularInline]) site3 = admin.AdminSite(name="stacked_inline_hidden_field_in_group_admin") site3.register(SomeParentModel, inlines=[ChildHiddenFieldInFieldsGroupStackedInline]) site4 = admin.AdminSite(name="stacked_inline_hidden_field_on_single_line_admin") site4.register(SomeParentModel, inlines=[ChildHiddenFieldOnSingleLineStackedInline])
0434beb676ac0d061a08fff163e5c6ead8b44c19ce8fb11218e27ec3b5cb602b
from django.urls import path from . import admin urlpatterns = [ path("admin/", admin.site.urls), path("admin2/", admin.site2.urls), path("admin3/", admin.site3.urls), path("admin4/", admin.site4.urls), ]
ed1f56cac0efa9a7dc1443027f9ecdfed68672415401bb86c470f92c0fc07b3c
import json from django.template.loader import render_to_string from django.test import SimpleTestCase class TestTemplates(SimpleTestCase): def test_javascript_escaping(self): context = { "inline_admin_formset": { "inline_formset_data": json.dumps( { "formset": {"prefix": "my-prefix"}, "opts": {"verbose_name": "verbose name\\"}, } ), }, } output = render_to_string("admin/edit_inline/stacked.html", context) self.assertIn("&quot;prefix&quot;: &quot;my-prefix&quot;", output) self.assertIn("&quot;verbose_name&quot;: &quot;verbose name\\\\&quot;", output) output = render_to_string("admin/edit_inline/tabular.html", context) self.assertIn("&quot;prefix&quot;: &quot;my-prefix&quot;", output) self.assertIn("&quot;verbose_name&quot;: &quot;verbose name\\\\&quot;", output)
21853b74678389b68bf8a9c9f445f175316426a29beb3c7bec72df687991f146
from datetime import date from django.test import TestCase from .models import Article class MethodsTests(TestCase): def test_custom_methods(self): a = Article.objects.create( headline="Parrot programs in Python", pub_date=date(2005, 7, 27) ) b = Article.objects.create( headline="Beatles reunite", pub_date=date(2005, 7, 27) ) self.assertFalse(a.was_published_today()) self.assertQuerysetEqual( a.articles_from_same_day_1(), [ "Beatles reunite", ], lambda a: a.headline, ) self.assertQuerysetEqual( a.articles_from_same_day_2(), [ "Beatles reunite", ], lambda a: a.headline, ) self.assertQuerysetEqual( b.articles_from_same_day_1(), [ "Parrot programs in Python", ], lambda a: a.headline, ) self.assertQuerysetEqual( b.articles_from_same_day_2(), [ "Parrot programs in Python", ], lambda a: a.headline, )
c532fbc3ad778543b0e1804ca2d1985ad34865f3e6e8570f65fad0465daf6c4a
""" Giving models custom methods Any method you add to a model will be available to instances. """ import datetime from django.db import models class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateField() def __str__(self): return self.headline def was_published_today(self): return self.pub_date == datetime.date.today() def articles_from_same_day_1(self): return Article.objects.filter(pub_date=self.pub_date).exclude(id=self.id) def articles_from_same_day_2(self): """ Verbose version of get_articles_from_same_day_1, which does a custom database query for the sake of demonstration. """ from django.db import connection with connection.cursor() as cursor: cursor.execute( """ SELECT id, headline, pub_date FROM custom_methods_article WHERE pub_date = %s AND id != %s""", [connection.ops.adapt_datefield_value(self.pub_date), self.id], ) return [self.__class__(*row) for row in cursor.fetchall()]
7fc9fda27cba3b61176741907bd00579a5a106fe1be4ad0149648ab88c9d621a
from django.db import connection from django.db.models import Max from django.test import TestCase from .models import Cash, CashModel class FromDBValueTest(TestCase): @classmethod def setUpTestData(cls): CashModel.objects.create(cash="12.50") def test_simple_load(self): instance = CashModel.objects.get() self.assertIsInstance(instance.cash, Cash) def test_values_list(self): values_list = CashModel.objects.values_list("cash", flat=True) self.assertIsInstance(values_list[0], Cash) def test_values(self): values = CashModel.objects.values("cash") self.assertIsInstance(values[0]["cash"], Cash) def test_aggregation(self): maximum = CashModel.objects.aggregate(m=Max("cash"))["m"] self.assertIsInstance(maximum, Cash) def test_defer(self): instance = CashModel.objects.defer("cash").get() self.assertIsInstance(instance.cash, Cash) def test_connection(self): instance = CashModel.objects.get() self.assertEqual(instance.cash.vendor, connection.vendor)
034a1b75e1b2a5ce7a673719eb7bbacb2378714c969cda48876032ffdf32af47
import decimal from django.db import models class Cash(decimal.Decimal): currency = "USD" class CashField(models.DecimalField): def __init__(self, **kwargs): kwargs["max_digits"] = 20 kwargs["decimal_places"] = 2 super().__init__(**kwargs) def from_db_value(self, value, expression, connection): cash = Cash(value) cash.vendor = connection.vendor return cash class CashModel(models.Model): cash = CashField()
e75dd67ade0fb236164d721ae8df439aeb85f9a88dee0cd8c9a7f580137c27da
from django.apps import apps from django.test import SimpleTestCase class NoModelTests(SimpleTestCase): def test_no_models(self): """It's possible to load an app with no models.py file.""" app_config = apps.get_app_config("no_models") self.assertIsNone(app_config.models_module)
e4a65c6f7f1bd4123ea131ad0b9120e6edc691927a337b7db763486c710020ec
from unittest import mock from django.core import checks from django.core.checks import Error, Warning from django.db import models from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import ( isolate_apps, modify_settings, override_settings, override_system_checks, ) class EmptyRouter: pass @isolate_apps("check_framework", attr_name="apps") @override_system_checks([checks.model_checks.check_all_models]) class DuplicateDBTableTests(SimpleTestCase): def test_collision_in_same_app(self): class Model1(models.Model): class Meta: db_table = "test_table" class Model2(models.Model): class Meta: db_table = "test_table" self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "db_table 'test_table' is used by multiple models: " "check_framework.Model1, check_framework.Model2.", obj="test_table", id="models.E028", ) ], ) @override_settings( DATABASE_ROUTERS=["check_framework.test_model_checks.EmptyRouter"] ) def test_collision_in_same_app_database_routers_installed(self): class Model1(models.Model): class Meta: db_table = "test_table" class Model2(models.Model): class Meta: db_table = "test_table" self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Warning( "db_table 'test_table' is used by multiple models: " "check_framework.Model1, check_framework.Model2.", hint=( "You have configured settings.DATABASE_ROUTERS. Verify " "that check_framework.Model1, check_framework.Model2 are " "correctly routed to separate databases." ), obj="test_table", id="models.W035", ) ], ) @modify_settings(INSTALLED_APPS={"append": "basic"}) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_collision_across_apps(self, apps): class Model1(models.Model): class Meta: app_label = "basic" db_table = "test_table" class Model2(models.Model): class Meta: app_label = "check_framework" db_table = "test_table" self.assertEqual( checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "db_table 'test_table' is used by multiple models: " "basic.Model1, check_framework.Model2.", obj="test_table", id="models.E028", ) ], ) @modify_settings(INSTALLED_APPS={"append": "basic"}) @override_settings( DATABASE_ROUTERS=["check_framework.test_model_checks.EmptyRouter"] ) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_collision_across_apps_database_routers_installed(self, apps): class Model1(models.Model): class Meta: app_label = "basic" db_table = "test_table" class Model2(models.Model): class Meta: app_label = "check_framework" db_table = "test_table" self.assertEqual( checks.run_checks(app_configs=apps.get_app_configs()), [ Warning( "db_table 'test_table' is used by multiple models: " "basic.Model1, check_framework.Model2.", hint=( "You have configured settings.DATABASE_ROUTERS. Verify " "that basic.Model1, check_framework.Model2 are correctly " "routed to separate databases." ), obj="test_table", id="models.W035", ) ], ) def test_no_collision_for_unmanaged_models(self): class Unmanaged(models.Model): class Meta: db_table = "test_table" managed = False class Managed(models.Model): class Meta: db_table = "test_table" self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) def test_no_collision_for_proxy_models(self): class Model(models.Model): class Meta: db_table = "test_table" class ProxyModel(Model): class Meta: proxy = True self.assertEqual(Model._meta.db_table, ProxyModel._meta.db_table) self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) @isolate_apps("check_framework", attr_name="apps") @override_system_checks([checks.model_checks.check_all_models]) class IndexNameTests(SimpleTestCase): def test_collision_in_same_model(self): index = models.Index(fields=["id"], name="foo") class Model(models.Model): class Meta: indexes = [index, index] self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique for model check_framework.Model.", id="models.E029", ), ], ) def test_collision_in_different_models(self): index = models.Index(fields=["id"], name="foo") class Model1(models.Model): class Meta: indexes = [index] class Model2(models.Model): class Meta: indexes = [index] self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique among models: " "check_framework.Model1, check_framework.Model2.", id="models.E030", ), ], ) def test_collision_abstract_model(self): class AbstractModel(models.Model): class Meta: indexes = [models.Index(fields=["id"], name="foo")] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "index name 'foo' is not unique among models: " "check_framework.Model1, check_framework.Model2.", id="models.E030", ), ], ) def test_no_collision_abstract_model_interpolation(self): class AbstractModel(models.Model): name = models.CharField(max_length=20) class Meta: indexes = [ models.Index(fields=["name"], name="%(app_label)s_%(class)s_foo") ] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) @modify_settings(INSTALLED_APPS={"append": "basic"}) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_collision_across_apps(self, apps): index = models.Index(fields=["id"], name="foo") class Model1(models.Model): class Meta: app_label = "basic" indexes = [index] class Model2(models.Model): class Meta: app_label = "check_framework" indexes = [index] self.assertEqual( checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "index name 'foo' is not unique among models: basic.Model1, " "check_framework.Model2.", id="models.E030", ), ], ) @modify_settings(INSTALLED_APPS={"append": "basic"}) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_no_collision_across_apps_interpolation(self, apps): index = models.Index(fields=["id"], name="%(app_label)s_%(class)s_foo") class Model1(models.Model): class Meta: app_label = "basic" constraints = [index] class Model2(models.Model): class Meta: app_label = "check_framework" constraints = [index] self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), []) @isolate_apps("check_framework", attr_name="apps") @override_system_checks([checks.model_checks.check_all_models]) @skipUnlessDBFeature("supports_table_check_constraints") class ConstraintNameTests(TestCase): def test_collision_in_same_model(self): class Model(models.Model): class Meta: constraints = [ models.CheckConstraint(check=models.Q(id__gt=0), name="foo"), models.CheckConstraint(check=models.Q(id__lt=100), name="foo"), ] self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique for model " "check_framework.Model.", id="models.E031", ), ], ) def test_collision_in_different_models(self): constraint = models.CheckConstraint(check=models.Q(id__gt=0), name="foo") class Model1(models.Model): class Meta: constraints = [constraint] class Model2(models.Model): class Meta: constraints = [constraint] self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique among models: " "check_framework.Model1, check_framework.Model2.", id="models.E032", ), ], ) def test_collision_abstract_model(self): class AbstractModel(models.Model): class Meta: constraints = [ models.CheckConstraint(check=models.Q(id__gt=0), name="foo") ] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique among models: " "check_framework.Model1, check_framework.Model2.", id="models.E032", ), ], ) def test_no_collision_abstract_model_interpolation(self): class AbstractModel(models.Model): class Meta: constraints = [ models.CheckConstraint( check=models.Q(id__gt=0), name="%(app_label)s_%(class)s_foo" ), ] abstract = True class Model1(AbstractModel): pass class Model2(AbstractModel): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) @modify_settings(INSTALLED_APPS={"append": "basic"}) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_collision_across_apps(self, apps): constraint = models.CheckConstraint(check=models.Q(id__gt=0), name="foo") class Model1(models.Model): class Meta: app_label = "basic" constraints = [constraint] class Model2(models.Model): class Meta: app_label = "check_framework" constraints = [constraint] self.assertEqual( checks.run_checks(app_configs=apps.get_app_configs()), [ Error( "constraint name 'foo' is not unique among models: " "basic.Model1, check_framework.Model2.", id="models.E032", ), ], ) @modify_settings(INSTALLED_APPS={"append": "basic"}) @isolate_apps("basic", "check_framework", kwarg_name="apps") def test_no_collision_across_apps_interpolation(self, apps): constraint = models.CheckConstraint( check=models.Q(id__gt=0), name="%(app_label)s_%(class)s_foo" ) class Model1(models.Model): class Meta: app_label = "basic" constraints = [constraint] class Model2(models.Model): class Meta: app_label = "check_framework" constraints = [constraint] self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), []) def mocked_is_overridden(self, setting): # Force treating DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' as a not # overridden setting. return ( setting != "DEFAULT_AUTO_FIELD" or self.DEFAULT_AUTO_FIELD != "django.db.models.AutoField" ) @mock.patch("django.conf.UserSettingsHolder.is_overridden", mocked_is_overridden) @override_settings(DEFAULT_AUTO_FIELD="django.db.models.AutoField") @isolate_apps("check_framework.apps.CheckDefaultPKConfig", attr_name="apps") @override_system_checks([checks.model_checks.check_all_models]) class ModelDefaultAutoFieldTests(SimpleTestCase): msg = ( "Auto-created primary key used when not defining a primary key type, " "by default 'django.db.models.AutoField'." ) hint = ( "Configure the DEFAULT_AUTO_FIELD setting or the " "CheckDefaultPKConfig.default_auto_field attribute to point to a " "subclass of AutoField, e.g. 'django.db.models.BigAutoField'." ) def test_auto_created_pk(self): class Model(models.Model): pass self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Warning(self.msg, hint=self.hint, obj=Model, id="models.W042"), ], ) def test_explicit_inherited_pk(self): class Parent(models.Model): id = models.AutoField(primary_key=True) class Child(Parent): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) def test_skipped_on_model_with_invalid_app_label(self): class Model(models.Model): class Meta: app_label = "invalid_app_label" self.assertEqual(Model.check(), []) def test_skipped_on_abstract_model(self): class Abstract(models.Model): class Meta: abstract = True # Call .check() because abstract models are not registered. self.assertEqual(Abstract.check(), []) def test_explicit_inherited_parent_link(self): class Parent(models.Model): id = models.AutoField(primary_key=True) class Child(Parent): parent_ptr = models.OneToOneField(Parent, models.CASCADE, parent_link=True) self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) def test_auto_created_inherited_pk(self): class Parent(models.Model): pass class Child(Parent): pass self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Warning(self.msg, hint=self.hint, obj=Parent, id="models.W042"), ], ) def test_auto_created_inherited_parent_link(self): class Parent(models.Model): pass class Child(Parent): parent_ptr = models.OneToOneField(Parent, models.CASCADE, parent_link=True) self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Warning(self.msg, hint=self.hint, obj=Parent, id="models.W042"), ], ) def test_auto_created_pk_inherited_abstract_parent(self): class Parent(models.Model): class Meta: abstract = True class Child(Parent): pass self.assertEqual( checks.run_checks(app_configs=self.apps.get_app_configs()), [ Warning(self.msg, hint=self.hint, obj=Child, id="models.W042"), ], ) @override_settings(DEFAULT_AUTO_FIELD="django.db.models.BigAutoField") def test_default_auto_field_setting(self): class Model(models.Model): pass self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) def test_explicit_pk(self): class Model(models.Model): id = models.BigAutoField(primary_key=True) self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), []) @isolate_apps("check_framework.apps.CheckPKConfig", kwarg_name="apps") def test_app_default_auto_field(self, apps): class ModelWithPkViaAppConfig(models.Model): class Meta: app_label = "check_framework.apps.CheckPKConfig" self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [])
883498457d2d6dd9b3028688806d239ffb2e6539f1f631b7c5981a650e7afca5
import pathlib from django.core.checks import Warning from django.core.checks.caches import ( E001, check_cache_location_not_exposed, check_default_cache_is_configured, check_file_based_cache_is_absolute, ) from django.test import SimpleTestCase from django.test.utils import override_settings class CheckCacheSettingsAppDirsTest(SimpleTestCase): VALID_CACHES_CONFIGURATION = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, } INVALID_CACHES_CONFIGURATION = { "other": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache", }, } @override_settings(CACHES=VALID_CACHES_CONFIGURATION) def test_default_cache_included(self): """ Don't error if 'default' is present in CACHES setting. """ self.assertEqual(check_default_cache_is_configured(None), []) @override_settings(CACHES=INVALID_CACHES_CONFIGURATION) def test_default_cache_not_included(self): """ Error if 'default' not present in CACHES setting. """ self.assertEqual(check_default_cache_is_configured(None), [E001]) class CheckCacheLocationTest(SimpleTestCase): warning_message = ( "Your 'default' cache configuration might expose your cache or lead " "to corruption of your data because its LOCATION %s %s." ) @staticmethod def get_settings(setting, cache_path, setting_path): return { "CACHES": { "default": { "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": cache_path, }, }, setting: [setting_path] if setting == "STATICFILES_DIRS" else setting_path, } def test_cache_path_matches_media_static_setting(self): root = pathlib.Path.cwd() for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"): settings = self.get_settings(setting, root, root) with self.subTest(setting=setting), self.settings(**settings): msg = self.warning_message % ("matches", setting) self.assertEqual( check_cache_location_not_exposed(None), [ Warning(msg, id="caches.W002"), ], ) def test_cache_path_inside_media_static_setting(self): root = pathlib.Path.cwd() for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"): settings = self.get_settings(setting, root / "cache", root) with self.subTest(setting=setting), self.settings(**settings): msg = self.warning_message % ("is inside", setting) self.assertEqual( check_cache_location_not_exposed(None), [ Warning(msg, id="caches.W002"), ], ) def test_cache_path_contains_media_static_setting(self): root = pathlib.Path.cwd() for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"): settings = self.get_settings(setting, root, root / "other") with self.subTest(setting=setting), self.settings(**settings): msg = self.warning_message % ("contains", setting) self.assertEqual( check_cache_location_not_exposed(None), [ Warning(msg, id="caches.W002"), ], ) def test_cache_path_not_conflict(self): root = pathlib.Path.cwd() for setting in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"): settings = self.get_settings(setting, root / "cache", root / "other") with self.subTest(setting=setting), self.settings(**settings): self.assertEqual(check_cache_location_not_exposed(None), []) def test_staticfiles_dirs_prefix(self): root = pathlib.Path.cwd() tests = [ (root, root, "matches"), (root / "cache", root, "is inside"), (root, root / "other", "contains"), ] for cache_path, setting_path, msg in tests: settings = self.get_settings( "STATICFILES_DIRS", cache_path, ("prefix", setting_path), ) with self.subTest(path=setting_path), self.settings(**settings): msg = self.warning_message % (msg, "STATICFILES_DIRS") self.assertEqual( check_cache_location_not_exposed(None), [ Warning(msg, id="caches.W002"), ], ) def test_staticfiles_dirs_prefix_not_conflict(self): root = pathlib.Path.cwd() settings = self.get_settings( "STATICFILES_DIRS", root / "cache", ("prefix", root / "other"), ) with self.settings(**settings): self.assertEqual(check_cache_location_not_exposed(None), []) class CheckCacheAbsolutePath(SimpleTestCase): def test_absolute_path(self): with self.settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": pathlib.Path.cwd() / "cache", }, } ): self.assertEqual(check_file_based_cache_is_absolute(None), []) def test_relative_path(self): with self.settings( CACHES={ "default": { "BACKEND": "django.core.cache.backends.filebased.FileBasedCache", "LOCATION": "cache", }, } ): self.assertEqual( check_file_based_cache_is_absolute(None), [ Warning( "Your 'default' cache LOCATION path is relative. Use an " "absolute path instead.", id="caches.W003", ), ], )
b3b72d92f573c476f9fddd79a94db73957a301938ca80367b9818b1a809d8b77
import sys from io import StringIO from django.apps import apps from django.core import checks from django.core.checks import Error, Warning from django.core.checks.messages import CheckMessage from django.core.checks.registry import CheckRegistry from django.core.management import call_command from django.core.management.base import CommandError from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps, override_settings, override_system_checks from .models import SimpleModel, my_check class DummyObj: def __repr__(self): return "obj" class SystemCheckFrameworkTests(SimpleTestCase): def test_register_and_run_checks(self): def f(**kwargs): calls[0] += 1 return [1, 2, 3] def f2(**kwargs): return [4] def f3(**kwargs): return [5] calls = [0] # test register as decorator registry = CheckRegistry() registry.register()(f) registry.register("tag1", "tag2")(f2) registry.register("tag2", deploy=True)(f3) # test register as function registry2 = CheckRegistry() registry2.register(f) registry2.register(f2, "tag1", "tag2") registry2.register(f3, "tag2", deploy=True) # check results errors = registry.run_checks() errors2 = registry2.run_checks() self.assertEqual(errors, errors2) self.assertEqual(sorted(errors), [1, 2, 3, 4]) self.assertEqual(calls[0], 2) errors = registry.run_checks(tags=["tag1"]) errors2 = registry2.run_checks(tags=["tag1"]) self.assertEqual(errors, errors2) self.assertEqual(sorted(errors), [4]) errors = registry.run_checks( tags=["tag1", "tag2"], include_deployment_checks=True ) errors2 = registry2.run_checks( tags=["tag1", "tag2"], include_deployment_checks=True ) self.assertEqual(errors, errors2) self.assertEqual(sorted(errors), [4, 5]) def test_register_no_kwargs_error(self): registry = CheckRegistry() msg = "Check functions must accept keyword arguments (**kwargs)." with self.assertRaisesMessage(TypeError, msg): @registry.register def no_kwargs(app_configs, databases): pass def test_register_run_checks_non_iterable(self): registry = CheckRegistry() @registry.register def return_non_iterable(**kwargs): return Error("Message") msg = ( "The function %r did not return a list. All functions registered " "with the checks registry must return a list." % return_non_iterable ) with self.assertRaisesMessage(TypeError, msg): registry.run_checks() class MessageTests(SimpleTestCase): def test_printing(self): e = Error("Message", hint="Hint", obj=DummyObj()) expected = "obj: Message\n\tHINT: Hint" self.assertEqual(str(e), expected) def test_printing_no_hint(self): e = Error("Message", obj=DummyObj()) expected = "obj: Message" self.assertEqual(str(e), expected) def test_printing_no_object(self): e = Error("Message", hint="Hint") expected = "?: Message\n\tHINT: Hint" self.assertEqual(str(e), expected) def test_printing_with_given_id(self): e = Error("Message", hint="Hint", obj=DummyObj(), id="ID") expected = "obj: (ID) Message\n\tHINT: Hint" self.assertEqual(str(e), expected) def test_printing_field_error(self): field = SimpleModel._meta.get_field("field") e = Error("Error", obj=field) expected = "check_framework.SimpleModel.field: Error" self.assertEqual(str(e), expected) def test_printing_model_error(self): e = Error("Error", obj=SimpleModel) expected = "check_framework.SimpleModel: Error" self.assertEqual(str(e), expected) def test_printing_manager_error(self): manager = SimpleModel.manager e = Error("Error", obj=manager) expected = "check_framework.SimpleModel.manager: Error" self.assertEqual(str(e), expected) def test_equal_to_self(self): e = Error("Error", obj=SimpleModel) self.assertEqual(e, e) def test_equal_to_same_constructed_check(self): e1 = Error("Error", obj=SimpleModel) e2 = Error("Error", obj=SimpleModel) self.assertEqual(e1, e2) def test_not_equal_to_different_constructed_check(self): e1 = Error("Error", obj=SimpleModel) e2 = Error("Error2", obj=SimpleModel) self.assertNotEqual(e1, e2) def test_not_equal_to_non_check(self): e = Error("Error", obj=DummyObj()) self.assertNotEqual(e, "a string") def test_invalid_level(self): msg = "The first argument should be level." with self.assertRaisesMessage(TypeError, msg): CheckMessage("ERROR", "Message") def simple_system_check(**kwargs): simple_system_check.kwargs = kwargs return [] def tagged_system_check(**kwargs): tagged_system_check.kwargs = kwargs return [checks.Warning("System Check")] tagged_system_check.tags = ["simpletag"] def deployment_system_check(**kwargs): deployment_system_check.kwargs = kwargs return [checks.Warning("Deployment Check")] deployment_system_check.tags = ["deploymenttag"] class CheckCommandTests(SimpleTestCase): def setUp(self): simple_system_check.kwargs = None tagged_system_check.kwargs = None self.old_stdout, self.old_stderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = StringIO(), StringIO() def tearDown(self): sys.stdout, sys.stderr = self.old_stdout, self.old_stderr @override_system_checks([simple_system_check, tagged_system_check]) def test_simple_call(self): call_command("check") self.assertEqual( simple_system_check.kwargs, {"app_configs": None, "databases": None} ) self.assertEqual( tagged_system_check.kwargs, {"app_configs": None, "databases": None} ) @override_system_checks([simple_system_check, tagged_system_check]) def test_given_app(self): call_command("check", "auth", "admin") auth_config = apps.get_app_config("auth") admin_config = apps.get_app_config("admin") self.assertEqual( simple_system_check.kwargs, {"app_configs": [auth_config, admin_config], "databases": None}, ) self.assertEqual( tagged_system_check.kwargs, {"app_configs": [auth_config, admin_config], "databases": None}, ) @override_system_checks([simple_system_check, tagged_system_check]) def test_given_tag(self): call_command("check", tags=["simpletag"]) self.assertIsNone(simple_system_check.kwargs) self.assertEqual( tagged_system_check.kwargs, {"app_configs": None, "databases": None} ) @override_system_checks([simple_system_check, tagged_system_check]) def test_invalid_tag(self): msg = 'There is no system check with the "missingtag" tag.' with self.assertRaisesMessage(CommandError, msg): call_command("check", tags=["missingtag"]) @override_system_checks([simple_system_check]) def test_list_tags_empty(self): call_command("check", list_tags=True) self.assertEqual("\n", sys.stdout.getvalue()) @override_system_checks([tagged_system_check]) def test_list_tags(self): call_command("check", list_tags=True) self.assertEqual("simpletag\n", sys.stdout.getvalue()) @override_system_checks( [tagged_system_check], deployment_checks=[deployment_system_check] ) def test_list_deployment_check_omitted(self): call_command("check", list_tags=True) self.assertEqual("simpletag\n", sys.stdout.getvalue()) @override_system_checks( [tagged_system_check], deployment_checks=[deployment_system_check] ) def test_list_deployment_check_included(self): call_command("check", deploy=True, list_tags=True) self.assertEqual("deploymenttag\nsimpletag\n", sys.stdout.getvalue()) @override_system_checks( [tagged_system_check], deployment_checks=[deployment_system_check] ) def test_tags_deployment_check_omitted(self): msg = 'There is no system check with the "deploymenttag" tag.' with self.assertRaisesMessage(CommandError, msg): call_command("check", tags=["deploymenttag"]) @override_system_checks( [tagged_system_check], deployment_checks=[deployment_system_check] ) def test_tags_deployment_check_included(self): call_command("check", deploy=True, tags=["deploymenttag"]) self.assertIn("Deployment Check", sys.stderr.getvalue()) @override_system_checks([tagged_system_check]) def test_fail_level(self): with self.assertRaises(CommandError): call_command("check", fail_level="WARNING") def custom_error_system_check(app_configs, **kwargs): return [Error("Error", id="myerrorcheck.E001")] def custom_warning_system_check(app_configs, **kwargs): return [Warning("Warning", id="mywarningcheck.E001")] class SilencingCheckTests(SimpleTestCase): def setUp(self): self.old_stdout, self.old_stderr = sys.stdout, sys.stderr self.stdout, self.stderr = StringIO(), StringIO() sys.stdout, sys.stderr = self.stdout, self.stderr def tearDown(self): sys.stdout, sys.stderr = self.old_stdout, self.old_stderr @override_settings(SILENCED_SYSTEM_CHECKS=["myerrorcheck.E001"]) @override_system_checks([custom_error_system_check]) def test_silenced_error(self): out = StringIO() err = StringIO() call_command("check", stdout=out, stderr=err) self.assertEqual( out.getvalue(), "System check identified no issues (1 silenced).\n" ) self.assertEqual(err.getvalue(), "") @override_settings(SILENCED_SYSTEM_CHECKS=["mywarningcheck.E001"]) @override_system_checks([custom_warning_system_check]) def test_silenced_warning(self): out = StringIO() err = StringIO() call_command("check", stdout=out, stderr=err) self.assertEqual( out.getvalue(), "System check identified no issues (1 silenced).\n" ) self.assertEqual(err.getvalue(), "") class CheckFrameworkReservedNamesTests(SimpleTestCase): @isolate_apps("check_framework", kwarg_name="apps") @override_system_checks([checks.model_checks.check_all_models]) def test_model_check_method_not_shadowed(self, apps): class ModelWithAttributeCalledCheck(models.Model): check = 42 class ModelWithFieldCalledCheck(models.Model): check = models.IntegerField() class ModelWithRelatedManagerCalledCheck(models.Model): pass class ModelWithDescriptorCalledCheck(models.Model): check = models.ForeignKey( ModelWithRelatedManagerCalledCheck, models.CASCADE ) article = models.ForeignKey( ModelWithRelatedManagerCalledCheck, models.CASCADE, related_name="check", ) errors = checks.run_checks(app_configs=apps.get_app_configs()) expected = [ Error( "The 'ModelWithAttributeCalledCheck.check()' class method is " "currently overridden by 42.", obj=ModelWithAttributeCalledCheck, id="models.E020", ), Error( "The 'ModelWithFieldCalledCheck.check()' class method is " "currently overridden by %r." % ModelWithFieldCalledCheck.check, obj=ModelWithFieldCalledCheck, id="models.E020", ), Error( "The 'ModelWithRelatedManagerCalledCheck.check()' class method is " "currently overridden by %r." % ModelWithRelatedManagerCalledCheck.check, obj=ModelWithRelatedManagerCalledCheck, id="models.E020", ), Error( "The 'ModelWithDescriptorCalledCheck.check()' class method is " "currently overridden by %r." % ModelWithDescriptorCalledCheck.check, obj=ModelWithDescriptorCalledCheck, id="models.E020", ), ] self.assertEqual(errors, expected) class ChecksRunDuringTests(SimpleTestCase): def test_registered_check_did_run(self): self.assertTrue(my_check.did_run)
595d54555c78bff7f0512964ee00ce675faabdca45f42352ebd8a751a654cbf4
from django.core.checks import register from django.db import models class SimpleModel(models.Model): field = models.IntegerField() manager = models.manager.Manager() @register("tests") def my_check(app_configs, **kwargs): my_check.did_run = True return [] my_check.did_run = False
8822ac7f19a7c13c0cffb03cebc0269ad46cc2c471904e1bd94a41e71c309edf
from django.core import checks from django.db import models from django.test import SimpleTestCase from django.test.utils import isolate_apps @isolate_apps("check_framework") class TestDeprecatedField(SimpleTestCase): def test_default_details(self): class MyField(models.Field): system_check_deprecated_details = {} class Model(models.Model): name = MyField() model = Model() self.assertEqual( model.check(), [ checks.Warning( msg="MyField has been deprecated.", obj=Model._meta.get_field("name"), id="fields.WXXX", ) ], ) def test_user_specified_details(self): class MyField(models.Field): system_check_deprecated_details = { "msg": "This field is deprecated and will be removed soon.", "hint": "Use something else.", "id": "fields.W999", } class Model(models.Model): name = MyField() model = Model() self.assertEqual( model.check(), [ checks.Warning( msg="This field is deprecated and will be removed soon.", hint="Use something else.", obj=Model._meta.get_field("name"), id="fields.W999", ) ], ) @isolate_apps("check_framework") class TestRemovedField(SimpleTestCase): def test_default_details(self): class MyField(models.Field): system_check_removed_details = {} class Model(models.Model): name = MyField() model = Model() self.assertEqual( model.check(), [ checks.Error( msg=( "MyField has been removed except for support in historical " "migrations." ), obj=Model._meta.get_field("name"), id="fields.EXXX", ) ], ) def test_user_specified_details(self): class MyField(models.Field): system_check_removed_details = { "msg": "Support for this field is gone.", "hint": "Use something else.", "id": "fields.E999", } class Model(models.Model): name = MyField() model = Model() self.assertEqual( model.check(), [ checks.Error( msg="Support for this field is gone.", hint="Use something else.", obj=Model._meta.get_field("name"), id="fields.E999", ) ], )
2303bc3714d3f265009db0e496e43928f0aab389aa0413b7ae9161d12fee9969
from django.conf import settings from django.core.checks.messages import Error, Warning from django.core.checks.security import base, csrf, sessions from django.core.management.utils import get_random_secret_key from django.test import SimpleTestCase from django.test.utils import override_settings class CheckSessionCookieSecureTest(SimpleTestCase): @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_secure_with_installed_app(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W010]) @override_settings( SESSION_COOKIE_SECURE="1", INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_secure_with_installed_app_truthy(self): """SESSION_COOKIE_SECURE must be boolean.""" self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W010]) @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=[], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_secure_with_middleware(self): """ Warn if SESSION_COOKIE_SECURE is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W011]) @override_settings( SESSION_COOKIE_SECURE=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_secure_both(self): """ If SESSION_COOKIE_SECURE is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(sessions.check_session_cookie_secure(None), [sessions.W012]) @override_settings( SESSION_COOKIE_SECURE=True, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_secure_true(self): """ If SESSION_COOKIE_SECURE is on, there's no warning about it. """ self.assertEqual(sessions.check_session_cookie_secure(None), []) class CheckSessionCookieHttpOnlyTest(SimpleTestCase): @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_httponly_with_installed_app(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions" is in INSTALLED_APPS. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W013]) @override_settings( SESSION_COOKIE_HTTPONLY="1", INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=[], ) def test_session_cookie_httponly_with_installed_app_truthy(self): """SESSION_COOKIE_HTTPONLY must be boolean.""" self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W013]) @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=[], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_httponly_with_middleware(self): """ Warn if SESSION_COOKIE_HTTPONLY is off and "django.contrib.sessions.middleware.SessionMiddleware" is in MIDDLEWARE. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W014]) @override_settings( SESSION_COOKIE_HTTPONLY=False, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_httponly_both(self): """ If SESSION_COOKIE_HTTPONLY is off and we find both the session app and the middleware, provide one common warning. """ self.assertEqual(sessions.check_session_cookie_httponly(None), [sessions.W015]) @override_settings( SESSION_COOKIE_HTTPONLY=True, INSTALLED_APPS=["django.contrib.sessions"], MIDDLEWARE=["django.contrib.sessions.middleware.SessionMiddleware"], ) def test_session_cookie_httponly_true(self): """ If SESSION_COOKIE_HTTPONLY is on, there's no warning about it. """ self.assertEqual(sessions.check_session_cookie_httponly(None), []) class CheckCSRFMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_no_csrf_middleware(self): """ Warn if CsrfViewMiddleware isn't in MIDDLEWARE. """ self.assertEqual(csrf.check_csrf_middleware(None), [csrf.W003]) @override_settings(MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"]) def test_with_csrf_middleware(self): self.assertEqual(csrf.check_csrf_middleware(None), []) class CheckCSRFCookieSecureTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE=False, ) def test_with_csrf_cookie_secure_false(self): """ Warn if CsrfViewMiddleware is in MIDDLEWARE but CSRF_COOKIE_SECURE isn't True. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), [csrf.W016]) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE="1", ) def test_with_csrf_cookie_secure_truthy(self): """CSRF_COOKIE_SECURE must be boolean.""" self.assertEqual(csrf.check_csrf_cookie_secure(None), [csrf.W016]) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_USE_SESSIONS=True, CSRF_COOKIE_SECURE=False, ) def test_use_sessions_with_csrf_cookie_secure_false(self): """ No warning if CSRF_COOKIE_SECURE isn't True while CSRF_USE_SESSIONS is True. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), []) @override_settings(MIDDLEWARE=[], CSRF_COOKIE_SECURE=False) def test_with_csrf_cookie_secure_false_no_middleware(self): """ No warning if CsrfViewMiddleware isn't in MIDDLEWARE, even if CSRF_COOKIE_SECURE is False. """ self.assertEqual(csrf.check_csrf_cookie_secure(None), []) @override_settings( MIDDLEWARE=["django.middleware.csrf.CsrfViewMiddleware"], CSRF_COOKIE_SECURE=True, ) def test_with_csrf_cookie_secure_true(self): self.assertEqual(csrf.check_csrf_cookie_secure(None), []) class CheckSecurityMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_no_security_middleware(self): """ Warn if SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_security_middleware(None), [base.W001]) @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"]) def test_with_security_middleware(self): self.assertEqual(base.check_security_middleware(None), []) class CheckStrictTransportSecurityTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_SECONDS=0, ) def test_no_sts(self): """ Warn if SECURE_HSTS_SECONDS isn't > 0. """ self.assertEqual(base.check_sts(None), [base.W004]) @override_settings(MIDDLEWARE=[], SECURE_HSTS_SECONDS=0) def test_no_sts_no_middleware(self): """ Don't warn if SECURE_HSTS_SECONDS isn't > 0 and SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_SECONDS=3600, ) def test_with_sts(self): self.assertEqual(base.check_sts(None), []) class CheckStrictTransportSecuritySubdomainsTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_subdomains(self): """ Warn if SECURE_HSTS_INCLUDE_SUBDOMAINS isn't True. """ self.assertEqual(base.check_sts_include_subdomains(None), [base.W005]) @override_settings( MIDDLEWARE=[], SECURE_HSTS_INCLUDE_SUBDOMAINS=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_subdomains_no_middleware(self): """ Don't warn if SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts_include_subdomains(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, SECURE_HSTS_SECONDS=None, ) def test_no_sts_subdomains_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. """ self.assertEqual(base.check_sts_include_subdomains(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_INCLUDE_SUBDOMAINS=True, SECURE_HSTS_SECONDS=3600, ) def test_with_sts_subdomains(self): self.assertEqual(base.check_sts_include_subdomains(None), []) class CheckStrictTransportSecurityPreloadTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_PRELOAD=False, SECURE_HSTS_SECONDS=3600, ) def test_no_sts_preload(self): """ Warn if SECURE_HSTS_PRELOAD isn't True. """ self.assertEqual(base.check_sts_preload(None), [base.W021]) @override_settings( MIDDLEWARE=[], SECURE_HSTS_PRELOAD=False, SECURE_HSTS_SECONDS=3600 ) def test_no_sts_preload_no_middleware(self): """ Don't warn if SecurityMiddleware isn't installed. """ self.assertEqual(base.check_sts_preload(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, SECURE_HSTS_SECONDS=None, ) def test_no_sts_preload_no_seconds(self): """ Don't warn if SECURE_HSTS_SECONDS isn't set. """ self.assertEqual(base.check_sts_preload(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_HSTS_PRELOAD=True, SECURE_HSTS_SECONDS=3600, ) def test_with_sts_preload(self): self.assertEqual(base.check_sts_preload(None), []) class CheckXFrameOptionsMiddlewareTest(SimpleTestCase): @override_settings(MIDDLEWARE=[]) def test_middleware_not_installed(self): """ Warn if XFrameOptionsMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_xframe_options_middleware(None), [base.W002]) @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"] ) def test_middleware_installed(self): self.assertEqual(base.check_xframe_options_middleware(None), []) class CheckXFrameOptionsDenyTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"], X_FRAME_OPTIONS="SAMEORIGIN", ) def test_x_frame_options_not_deny(self): """ Warn if XFrameOptionsMiddleware is in MIDDLEWARE but X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(base.check_xframe_deny(None), [base.W019]) @override_settings(MIDDLEWARE=[], X_FRAME_OPTIONS="SAMEORIGIN") def test_middleware_not_installed(self): """ No error if XFrameOptionsMiddleware isn't in MIDDLEWARE even if X_FRAME_OPTIONS isn't 'DENY'. """ self.assertEqual(base.check_xframe_deny(None), []) @override_settings( MIDDLEWARE=["django.middleware.clickjacking.XFrameOptionsMiddleware"], X_FRAME_OPTIONS="DENY", ) def test_xframe_deny(self): self.assertEqual(base.check_xframe_deny(None), []) class CheckContentTypeNosniffTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CONTENT_TYPE_NOSNIFF=False, ) def test_no_content_type_nosniff(self): """ Warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True. """ self.assertEqual(base.check_content_type_nosniff(None), [base.W006]) @override_settings(MIDDLEWARE=[], SECURE_CONTENT_TYPE_NOSNIFF=False) def test_no_content_type_nosniff_no_middleware(self): """ Don't warn if SECURE_CONTENT_TYPE_NOSNIFF isn't True and SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_content_type_nosniff(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CONTENT_TYPE_NOSNIFF=True, ) def test_with_content_type_nosniff(self): self.assertEqual(base.check_content_type_nosniff(None), []) class CheckSSLRedirectTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=False, ) def test_no_ssl_redirect(self): """ Warn if SECURE_SSL_REDIRECT isn't True. """ self.assertEqual(base.check_ssl_redirect(None), [base.W008]) @override_settings(MIDDLEWARE=[], SECURE_SSL_REDIRECT=False) def test_no_ssl_redirect_no_middleware(self): """ Don't warn if SECURE_SSL_REDIRECT is False and SecurityMiddleware isn't installed. """ self.assertEqual(base.check_ssl_redirect(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_SSL_REDIRECT=True, ) def test_with_ssl_redirect(self): self.assertEqual(base.check_ssl_redirect(None), []) class CheckSecretKeyTest(SimpleTestCase): @override_settings(SECRET_KEY=("abcdefghijklmnopqrstuvwx" * 2) + "ab") def test_okay_secret_key(self): self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH) self.assertGreater( len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS ) self.assertEqual(base.check_secret_key(None), []) @override_settings(SECRET_KEY="") def test_empty_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=None) def test_missing_secret_key(self): del settings.SECRET_KEY self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=None) def test_none_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings( SECRET_KEY=base.SECRET_KEY_INSECURE_PREFIX + get_random_secret_key() ) def test_insecure_secret_key(self): self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY=("abcdefghijklmnopqrstuvwx" * 2) + "a") def test_low_length_secret_key(self): self.assertEqual(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH - 1) self.assertEqual(base.check_secret_key(None), [base.W009]) @override_settings(SECRET_KEY="abcd" * 20) def test_low_entropy_secret_key(self): self.assertGreater(len(settings.SECRET_KEY), base.SECRET_KEY_MIN_LENGTH) self.assertLess( len(set(settings.SECRET_KEY)), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS ) self.assertEqual(base.check_secret_key(None), [base.W009]) class CheckSecretKeyFallbacksTest(SimpleTestCase): @override_settings(SECRET_KEY_FALLBACKS=[("abcdefghijklmnopqrstuvwx" * 2) + "ab"]) def test_okay_secret_key_fallbacks(self): self.assertEqual( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH, ) self.assertGreater( len(set(settings.SECRET_KEY_FALLBACKS[0])), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS, ) self.assertEqual(base.check_secret_key_fallbacks(None), []) def test_no_secret_key_fallbacks(self): with self.settings(SECRET_KEY_FALLBACKS=None): del settings.SECRET_KEY_FALLBACKS self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS", id=base.W025.id), ], ) @override_settings( SECRET_KEY_FALLBACKS=[base.SECRET_KEY_INSECURE_PREFIX + get_random_secret_key()] ) def test_insecure_secret_key_fallbacks(self): self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id), ], ) @override_settings(SECRET_KEY_FALLBACKS=[("abcdefghijklmnopqrstuvwx" * 2) + "a"]) def test_low_length_secret_key_fallbacks(self): self.assertEqual( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH - 1, ) self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id), ], ) @override_settings(SECRET_KEY_FALLBACKS=["abcd" * 20]) def test_low_entropy_secret_key_fallbacks(self): self.assertGreater( len(settings.SECRET_KEY_FALLBACKS[0]), base.SECRET_KEY_MIN_LENGTH, ) self.assertLess( len(set(settings.SECRET_KEY_FALLBACKS[0])), base.SECRET_KEY_MIN_UNIQUE_CHARACTERS, ) self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[0]", id=base.W025.id), ], ) @override_settings( SECRET_KEY_FALLBACKS=[ ("abcdefghijklmnopqrstuvwx" * 2) + "ab", "badkey", ] ) def test_multiple_keys(self): self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[1]", id=base.W025.id), ], ) @override_settings( SECRET_KEY_FALLBACKS=[ ("abcdefghijklmnopqrstuvwx" * 2) + "ab", "badkey1", "badkey2", ] ) def test_multiple_bad_keys(self): self.assertEqual( base.check_secret_key_fallbacks(None), [ Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[1]", id=base.W025.id), Warning(base.W025.msg % "SECRET_KEY_FALLBACKS[2]", id=base.W025.id), ], ) class CheckDebugTest(SimpleTestCase): @override_settings(DEBUG=True) def test_debug_true(self): """ Warn if DEBUG is True. """ self.assertEqual(base.check_debug(None), [base.W018]) @override_settings(DEBUG=False) def test_debug_false(self): self.assertEqual(base.check_debug(None), []) class CheckAllowedHostsTest(SimpleTestCase): @override_settings(ALLOWED_HOSTS=[]) def test_allowed_hosts_empty(self): self.assertEqual(base.check_allowed_hosts(None), [base.W020]) @override_settings(ALLOWED_HOSTS=[".example.com"]) def test_allowed_hosts_set(self): self.assertEqual(base.check_allowed_hosts(None), []) class CheckReferrerPolicyTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_REFERRER_POLICY=None, ) def test_no_referrer_policy(self): self.assertEqual(base.check_referrer_policy(None), [base.W022]) @override_settings(MIDDLEWARE=[], SECURE_REFERRER_POLICY=None) def test_no_referrer_policy_no_middleware(self): """ Don't warn if SECURE_REFERRER_POLICY is None and SecurityMiddleware isn't in MIDDLEWARE. """ self.assertEqual(base.check_referrer_policy(None), []) @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"]) def test_with_referrer_policy(self): tests = ( "strict-origin", "strict-origin,origin", "strict-origin, origin", ["strict-origin", "origin"], ("strict-origin", "origin"), ) for value in tests: with self.subTest(value=value), override_settings( SECURE_REFERRER_POLICY=value ): self.assertEqual(base.check_referrer_policy(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_REFERRER_POLICY="invalid-value", ) def test_with_invalid_referrer_policy(self): self.assertEqual(base.check_referrer_policy(None), [base.E023]) def failure_view_with_invalid_signature(): pass class CSRFFailureViewTest(SimpleTestCase): @override_settings(CSRF_FAILURE_VIEW="") def test_failure_view_import_error(self): self.assertEqual( csrf.check_csrf_failure_view(None), [ Error( "The CSRF failure view '' could not be imported.", id="security.E102", ) ], ) @override_settings( CSRF_FAILURE_VIEW=( "check_framework.test_security.failure_view_with_invalid_signature" ), ) def test_failure_view_invalid_signature(self): msg = ( "The CSRF failure view " "'check_framework.test_security.failure_view_with_invalid_signature' " "does not take the correct number of arguments." ) self.assertEqual( csrf.check_csrf_failure_view(None), [Error(msg, id="security.E101")], ) class CheckCrossOriginOpenerPolicyTest(SimpleTestCase): @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CROSS_ORIGIN_OPENER_POLICY=None, ) def test_no_coop(self): self.assertEqual(base.check_cross_origin_opener_policy(None), []) @override_settings(MIDDLEWARE=["django.middleware.security.SecurityMiddleware"]) def test_with_coop(self): tests = ["same-origin", "same-origin-allow-popups", "unsafe-none"] for value in tests: with self.subTest(value=value), override_settings( SECURE_CROSS_ORIGIN_OPENER_POLICY=value, ): self.assertEqual(base.check_cross_origin_opener_policy(None), []) @override_settings( MIDDLEWARE=["django.middleware.security.SecurityMiddleware"], SECURE_CROSS_ORIGIN_OPENER_POLICY="invalid-value", ) def test_with_invalid_coop(self): self.assertEqual(base.check_cross_origin_opener_policy(None), [base.E024])
24984a95217463bf1040b5c1023160de5097fe46377bb7c5c7f3f5f7df4deaad
import os from unittest import mock from django.core.checks.async_checks import E001, check_async_unsafe from django.test import SimpleTestCase class AsyncCheckTests(SimpleTestCase): @mock.patch.dict(os.environ, {"DJANGO_ALLOW_ASYNC_UNSAFE": ""}) def test_no_allowed_async_unsafe(self): self.assertEqual(check_async_unsafe(None), []) @mock.patch.dict(os.environ, {"DJANGO_ALLOW_ASYNC_UNSAFE": "true"}) def test_allowed_async_unsafe_set(self): self.assertEqual(check_async_unsafe(None), [E001])
1a74a7000fec9a1bfab6b28652b6c1191a5589474185fb55a8f1ec016b93b9a8
from django.apps import AppConfig class CheckDefaultPKConfig(AppConfig): name = "check_framework" class CheckPKConfig(AppConfig): name = "check_framework" default_auto_field = "django.db.models.BigAutoField"
301dedb49cc8d9b96f3dd18c06d79790fb3ddf733cd6966567adeb23e4102b2f
from pathlib import Path from django.core.checks import Error from django.core.checks.files import check_setting_file_upload_temp_dir from django.test import SimpleTestCase class FilesCheckTests(SimpleTestCase): def test_file_upload_temp_dir(self): tests = [ None, "", Path.cwd(), str(Path.cwd()), ] for setting in tests: with self.subTest(setting), self.settings(FILE_UPLOAD_TEMP_DIR=setting): self.assertEqual(check_setting_file_upload_temp_dir(None), []) def test_file_upload_temp_dir_nonexistent(self): for setting in ["nonexistent", Path("nonexistent")]: with self.subTest(setting), self.settings(FILE_UPLOAD_TEMP_DIR=setting): self.assertEqual( check_setting_file_upload_temp_dir(None), [ Error( "The FILE_UPLOAD_TEMP_DIR setting refers to the " "nonexistent directory 'nonexistent'.", id="files.E001", ), ], )
4de30a27dbe09e1e9dfbc4dd1ec871fc9764a2a681b41010e0d7ef6e6af45232
from django.core.checks import Error from django.core.checks.compatibility.django_4_0 import check_csrf_trusted_origins from django.test import SimpleTestCase from django.test.utils import override_settings class CheckCSRFTrustedOrigins(SimpleTestCase): @override_settings(CSRF_TRUSTED_ORIGINS=["example.com"]) def test_invalid_url(self): self.assertEqual( check_csrf_trusted_origins(None), [ Error( "As of Django 4.0, the values in the CSRF_TRUSTED_ORIGINS " "setting must start with a scheme (usually http:// or " "https://) but found example.com. See the release notes for " "details.", id="4_0.E001", ) ], ) @override_settings( CSRF_TRUSTED_ORIGINS=["http://example.com", "https://example.com"], ) def test_valid_urls(self): self.assertEqual(check_csrf_trusted_origins(None), [])
214895d8a7421f4937733e7ac291947a1240bcb5afd70f22f3acf1a1ed77a2f7
from unittest import mock from django.db import connections, models from django.test import SimpleTestCase from django.test.utils import isolate_apps, override_settings class TestRouter: """ Routes to the 'other' database if the model name starts with 'Other'. """ def allow_migrate(self, db, app_label, model_name=None, **hints): return db == ("other" if model_name.startswith("other") else "default") @override_settings(DATABASE_ROUTERS=[TestRouter()]) @isolate_apps("check_framework") class TestMultiDBChecks(SimpleTestCase): def _patch_check_field_on(self, db): return mock.patch.object(connections[db].validation, "check_field") def test_checks_called_on_the_default_database(self): class Model(models.Model): field = models.CharField(max_length=100) model = Model() with self._patch_check_field_on("default") as mock_check_field_default: with self._patch_check_field_on("other") as mock_check_field_other: model.check(databases={"default", "other"}) self.assertTrue(mock_check_field_default.called) self.assertFalse(mock_check_field_other.called) def test_checks_called_on_the_other_database(self): class OtherModel(models.Model): field = models.CharField(max_length=100) model = OtherModel() with self._patch_check_field_on("other") as mock_check_field_other: with self._patch_check_field_on("default") as mock_check_field_default: model.check(databases={"default", "other"}) self.assertTrue(mock_check_field_other.called) self.assertFalse(mock_check_field_default.called)
94aa26d88d07d813a80a953a63e3f0b94e37ca93b4a76230d1cea32fb8dce119
from django.core.checks import Error from django.core.checks.translation import ( check_language_settings_consistent, check_setting_language_code, check_setting_languages, check_setting_languages_bidi, ) from django.test import SimpleTestCase, override_settings class TranslationCheckTests(SimpleTestCase): def setUp(self): self.valid_tags = ( "en", # language "mas", # language "sgn-ase", # language+extlang "fr-CA", # language+region "es-419", # language+region "zh-Hans", # language+script "ca-ES-valencia", # language+region+variant # FIXME: The following should be invalid: "sr@latin", # language+script ) self.invalid_tags = ( None, # invalid type: None. 123, # invalid type: int. b"en", # invalid type: bytes. "eü", # non-latin characters. "en_US", # locale format. "en--us", # empty subtag. "-en", # leading separator. "en-", # trailing separator. "en-US.UTF-8", # language tag w/ locale encoding. "en_US.UTF-8", # locale format - language w/ region and encoding. "ca_ES@valencia", # locale format - language w/ region and variant. # FIXME: The following should be invalid: # 'sr@latin', # locale instead of language tag. ) def test_valid_language_code(self): for tag in self.valid_tags: with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): self.assertEqual(check_setting_language_code(None), []) def test_invalid_language_code(self): msg = "You have provided an invalid value for the LANGUAGE_CODE setting: %r." for tag in self.invalid_tags: with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): self.assertEqual( check_setting_language_code(None), [ Error(msg % tag, id="translation.E001"), ], ) def test_valid_languages(self): for tag in self.valid_tags: with self.subTest(tag), self.settings(LANGUAGES=[(tag, tag)]): self.assertEqual(check_setting_languages(None), []) def test_invalid_languages(self): msg = "You have provided an invalid language code in the LANGUAGES setting: %r." for tag in self.invalid_tags: with self.subTest(tag), self.settings(LANGUAGES=[(tag, tag)]): self.assertEqual( check_setting_languages(None), [ Error(msg % tag, id="translation.E002"), ], ) def test_valid_languages_bidi(self): for tag in self.valid_tags: with self.subTest(tag), self.settings(LANGUAGES_BIDI=[tag]): self.assertEqual(check_setting_languages_bidi(None), []) def test_invalid_languages_bidi(self): msg = ( "You have provided an invalid language code in the LANGUAGES_BIDI setting: " "%r." ) for tag in self.invalid_tags: with self.subTest(tag), self.settings(LANGUAGES_BIDI=[tag]): self.assertEqual( check_setting_languages_bidi(None), [ Error(msg % tag, id="translation.E003"), ], ) @override_settings(USE_I18N=True, LANGUAGES=[("en", "English")]) def test_inconsistent_language_settings(self): msg = ( "You have provided a value for the LANGUAGE_CODE setting that is " "not in the LANGUAGES setting." ) for tag in ["fr", "fr-CA", "fr-357"]: with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): self.assertEqual( check_language_settings_consistent(None), [ Error(msg, id="translation.E004"), ], ) @override_settings( USE_I18N=True, LANGUAGES=[ ("de", "German"), ("es", "Spanish"), ("fr", "French"), ("ca", "Catalan"), ], ) def test_valid_variant_consistent_language_settings(self): tests = [ # language + region. "fr-CA", "es-419", "de-at", # language + region + variant. "ca-ES-valencia", ] for tag in tests: with self.subTest(tag), self.settings(LANGUAGE_CODE=tag): self.assertEqual(check_language_settings_consistent(None), [])
14e7042d08ee5e4a2ffc362c7649ff09a724c2a3e2e64dfa5ecf0ce6f5519d03
from django.conf import settings from django.core.checks.messages import Error, Warning from django.core.checks.urls import ( E006, check_url_config, check_url_namespaces_unique, check_url_settings, get_warning_for_invalid_pattern, ) from django.test import SimpleTestCase from django.test.utils import override_settings class CheckUrlConfigTests(SimpleTestCase): @override_settings(ROOT_URLCONF="check_framework.urls.no_warnings") def test_no_warnings(self): result = check_url_config(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF="check_framework.urls.no_warnings_i18n") def test_no_warnings_i18n(self): self.assertEqual(check_url_config(None), []) @override_settings(ROOT_URLCONF="check_framework.urls.warning_in_include") def test_check_resolver_recursive(self): # The resolver is checked recursively (examining URL patterns in include()). result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "urls.W001") @override_settings(ROOT_URLCONF="check_framework.urls.include_with_dollar") def test_include_with_dollar(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "urls.W001") self.assertEqual( warning.msg, ( "Your URL pattern '^include-with-dollar$' uses include with a " "route ending with a '$'. Remove the dollar from the route to " "avoid problems including URLs." ), ) @override_settings(ROOT_URLCONF="check_framework.urls.contains_tuple") def test_contains_tuple_not_url_instance(self): result = check_url_config(None) warning = result[0] self.assertEqual(warning.id, "urls.E004") self.assertRegex( warning.msg, ( r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) " r"is invalid. Ensure that urlpatterns is a list of path\(\) and/or " r"re_path\(\) instances\.$" ), ) @override_settings(ROOT_URLCONF="check_framework.urls.include_contains_tuple") def test_contains_included_tuple(self): result = check_url_config(None) warning = result[0] self.assertEqual(warning.id, "urls.E004") self.assertRegex( warning.msg, ( r"^Your URL pattern \('\^tuple/\$', <function <lambda> at 0x(\w+)>\) " r"is invalid. Ensure that urlpatterns is a list of path\(\) and/or " r"re_path\(\) instances\.$" ), ) @override_settings(ROOT_URLCONF="check_framework.urls.beginning_with_slash") def test_beginning_with_slash(self): msg = ( "Your URL pattern '%s' has a route beginning with a '/'. Remove " "this slash as it is unnecessary. If this pattern is targeted in " "an include(), ensure the include() pattern has a trailing '/'." ) warning1, warning2 = check_url_config(None) self.assertEqual(warning1.id, "urls.W002") self.assertEqual(warning1.msg, msg % "/path-starting-with-slash/") self.assertEqual(warning2.id, "urls.W002") self.assertEqual(warning2.msg, msg % "/url-starting-with-slash/$") @override_settings( ROOT_URLCONF="check_framework.urls.beginning_with_slash", APPEND_SLASH=False, ) def test_beginning_with_slash_append_slash(self): # It can be useful to start a URL pattern with a slash when # APPEND_SLASH=False (#27238). result = check_url_config(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF="check_framework.urls.name_with_colon") def test_name_with_colon(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "urls.W003") expected_msg = ( "Your URL pattern '^$' [name='name_with:colon'] has a name including a ':'." ) self.assertIn(expected_msg, warning.msg) @override_settings(ROOT_URLCONF=None) def test_no_root_urlconf_in_settings(self): delattr(settings, "ROOT_URLCONF") result = check_url_config(None) self.assertEqual(result, []) def test_get_warning_for_invalid_pattern_string(self): warning = get_warning_for_invalid_pattern("")[0] self.assertEqual( warning.hint, "Try removing the string ''. The list of urlpatterns should " "not have a prefix string as the first element.", ) def test_get_warning_for_invalid_pattern_tuple(self): warning = get_warning_for_invalid_pattern((r"^$", lambda x: x))[0] self.assertEqual(warning.hint, "Try using path() instead of a tuple.") def test_get_warning_for_invalid_pattern_other(self): warning = get_warning_for_invalid_pattern(object())[0] self.assertIsNone(warning.hint) @override_settings(ROOT_URLCONF="check_framework.urls.non_unique_namespaces") def test_check_non_unique_namespaces(self): result = check_url_namespaces_unique(None) self.assertEqual(len(result), 2) non_unique_namespaces = ["app-ns1", "app-1"] warning_messages = [ "URL namespace '{}' isn't unique. You may not be able to reverse " "all URLs in this namespace".format(namespace) for namespace in non_unique_namespaces ] for warning in result: self.assertIsInstance(warning, Warning) self.assertEqual("urls.W005", warning.id) self.assertIn(warning.msg, warning_messages) @override_settings(ROOT_URLCONF="check_framework.urls.unique_namespaces") def test_check_unique_namespaces(self): result = check_url_namespaces_unique(None) self.assertEqual(result, []) @override_settings(ROOT_URLCONF="check_framework.urls.cbv_as_view") def test_check_view_not_class(self): self.assertEqual( check_url_config(None), [ Error( "Your URL pattern 'missing_as_view' has an invalid view, pass " "EmptyCBV.as_view() instead of EmptyCBV.", id="urls.E009", ), ], ) class UpdatedToPathTests(SimpleTestCase): @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.contains_re_named_group" ) def test_contains_re_named_group(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "2_0.W001") expected_msg = "Your URL pattern '(?P<named_group>\\d+)' has a route" self.assertIn(expected_msg, warning.msg) @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.beginning_with_caret" ) def test_beginning_with_caret(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "2_0.W001") expected_msg = "Your URL pattern '^beginning-with-caret' has a route" self.assertIn(expected_msg, warning.msg) @override_settings( ROOT_URLCONF="check_framework.urls.path_compatibility.ending_with_dollar" ) def test_ending_with_dollar(self): result = check_url_config(None) self.assertEqual(len(result), 1) warning = result[0] self.assertEqual(warning.id, "2_0.W001") expected_msg = "Your URL pattern 'ending-with-dollar$' has a route" self.assertIn(expected_msg, warning.msg) class CheckCustomErrorHandlersTests(SimpleTestCase): @override_settings( ROOT_URLCONF="check_framework.urls.bad_function_based_error_handlers", ) def test_bad_function_based_handlers(self): result = check_url_config(None) self.assertEqual(len(result), 4) for code, num_params, error in zip([400, 403, 404, 500], [2, 2, 2, 1], result): with self.subTest("handler{}".format(code)): self.assertEqual( error, Error( "The custom handler{} view 'check_framework.urls." "bad_function_based_error_handlers.bad_handler' " "does not take the correct number of arguments " "(request{}).".format( code, ", exception" if num_params == 2 else "" ), id="urls.E007", ), ) @override_settings( ROOT_URLCONF="check_framework.urls.bad_class_based_error_handlers", ) def test_bad_class_based_handlers(self): result = check_url_config(None) self.assertEqual(len(result), 4) for code, num_params, error in zip([400, 403, 404, 500], [2, 2, 2, 1], result): with self.subTest("handler%s" % code): self.assertEqual( error, Error( "The custom handler%s view 'check_framework.urls." "bad_class_based_error_handlers.HandlerView.as_view." "<locals>.view' does not take the correct number of " "arguments (request%s)." % ( code, ", exception" if num_params == 2 else "", ), id="urls.E007", ), ) @override_settings( ROOT_URLCONF="check_framework.urls.bad_error_handlers_invalid_path" ) def test_bad_handlers_invalid_path(self): result = check_url_config(None) paths = [ "django.views.bad_handler", "django.invalid_module.bad_handler", "invalid_module.bad_handler", "django", ] hints = [ "Could not import '{}'. View does not exist in module django.views.", "Could not import '{}'. Parent module django.invalid_module does not " "exist.", "No module named 'invalid_module'", "Could not import '{}'. The path must be fully qualified.", ] for code, path, hint, error in zip([400, 403, 404, 500], paths, hints, result): with self.subTest("handler{}".format(code)): self.assertEqual( error, Error( "The custom handler{} view '{}' could not be imported.".format( code, path ), hint=hint.format(path), id="urls.E008", ), ) @override_settings( ROOT_URLCONF="check_framework.urls.good_function_based_error_handlers", ) def test_good_function_based_handlers(self): result = check_url_config(None) self.assertEqual(result, []) @override_settings( ROOT_URLCONF="check_framework.urls.good_class_based_error_handlers", ) def test_good_class_based_handlers(self): result = check_url_config(None) self.assertEqual(result, []) class CheckURLSettingsTests(SimpleTestCase): @override_settings(STATIC_URL="a/", MEDIA_URL="b/") def test_slash_no_errors(self): self.assertEqual(check_url_settings(None), []) @override_settings(STATIC_URL="", MEDIA_URL="") def test_empty_string_no_errors(self): self.assertEqual(check_url_settings(None), []) @override_settings(STATIC_URL="noslash") def test_static_url_no_slash(self): self.assertEqual(check_url_settings(None), [E006("STATIC_URL")]) @override_settings(STATIC_URL="slashes//") def test_static_url_double_slash_allowed(self): # The check allows for a double slash, presuming the user knows what # they are doing. self.assertEqual(check_url_settings(None), []) @override_settings(MEDIA_URL="noslash") def test_media_url_no_slash(self): self.assertEqual(check_url_settings(None), [E006("MEDIA_URL")])
9c8ea300581e49c6b5598057eca3705b46243be6adcdb3a0da376230adba2c97
from copy import copy, deepcopy from django.core.checks import Error from django.core.checks.templates import ( E001, E002, E003, check_for_template_tags_with_the_same_name, check_setting_app_dirs_loaders, check_string_if_invalid_is_string, ) from django.test import SimpleTestCase from django.test.utils import override_settings class CheckTemplateSettingsAppDirsTest(SimpleTestCase): TEMPLATES_APP_DIRS_AND_LOADERS = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, "OPTIONS": { "loaders": ["django.template.loaders.filesystem.Loader"], }, }, ] @override_settings(TEMPLATES=TEMPLATES_APP_DIRS_AND_LOADERS) def test_app_dirs_and_loaders(self): """ Error if template loaders are specified and APP_DIRS is True. """ self.assertEqual(check_setting_app_dirs_loaders(None), [E001]) def test_app_dirs_removed(self): TEMPLATES = deepcopy(self.TEMPLATES_APP_DIRS_AND_LOADERS) del TEMPLATES[0]["APP_DIRS"] with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(check_setting_app_dirs_loaders(None), []) def test_loaders_removed(self): TEMPLATES = deepcopy(self.TEMPLATES_APP_DIRS_AND_LOADERS) del TEMPLATES[0]["OPTIONS"]["loaders"] with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(check_setting_app_dirs_loaders(None), []) class CheckTemplateStringIfInvalidTest(SimpleTestCase): TEMPLATES_STRING_IF_INVALID = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "string_if_invalid": False, }, }, { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "string_if_invalid": 42, }, }, ] @classmethod def setUpClass(cls): super().setUpClass() cls.error1 = copy(E002) cls.error2 = copy(E002) string_if_invalid1 = cls.TEMPLATES_STRING_IF_INVALID[0]["OPTIONS"][ "string_if_invalid" ] string_if_invalid2 = cls.TEMPLATES_STRING_IF_INVALID[1]["OPTIONS"][ "string_if_invalid" ] cls.error1.msg = cls.error1.msg.format( string_if_invalid1, type(string_if_invalid1).__name__ ) cls.error2.msg = cls.error2.msg.format( string_if_invalid2, type(string_if_invalid2).__name__ ) @override_settings(TEMPLATES=TEMPLATES_STRING_IF_INVALID) def test_string_if_invalid_not_string(self): self.assertEqual( check_string_if_invalid_is_string(None), [self.error1, self.error2] ) def test_string_if_invalid_first_is_string(self): TEMPLATES = deepcopy(self.TEMPLATES_STRING_IF_INVALID) TEMPLATES[0]["OPTIONS"]["string_if_invalid"] = "test" with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(check_string_if_invalid_is_string(None), [self.error2]) def test_string_if_invalid_both_are_strings(self): TEMPLATES = deepcopy(self.TEMPLATES_STRING_IF_INVALID) TEMPLATES[0]["OPTIONS"]["string_if_invalid"] = "test" TEMPLATES[1]["OPTIONS"]["string_if_invalid"] = "test" with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(check_string_if_invalid_is_string(None), []) def test_string_if_invalid_not_specified(self): TEMPLATES = deepcopy(self.TEMPLATES_STRING_IF_INVALID) del TEMPLATES[1]["OPTIONS"]["string_if_invalid"] with self.settings(TEMPLATES=TEMPLATES): self.assertEqual(check_string_if_invalid_is_string(None), [self.error1]) class CheckTemplateTagLibrariesWithSameName(SimpleTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.error_same_tags = Error( E003.msg.format( "'same_tags'", "'check_framework.template_test_apps.same_tags_app_1." "templatetags.same_tags', " "'check_framework.template_test_apps.same_tags_app_2." "templatetags.same_tags'", ), id=E003.id, ) @staticmethod def get_settings(module_name, module_path): return { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "libraries": { module_name: f"check_framework.template_test_apps.{module_path}", }, }, } @override_settings( INSTALLED_APPS=[ "check_framework.template_test_apps.same_tags_app_1", "check_framework.template_test_apps.same_tags_app_2", ] ) def test_template_tags_with_same_name(self): self.assertEqual( check_for_template_tags_with_the_same_name(None), [self.error_same_tags], ) def test_template_tags_with_same_library_name(self): with self.settings( TEMPLATES=[ self.get_settings( "same_tags", "same_tags_app_1.templatetags.same_tags" ), self.get_settings( "same_tags", "same_tags_app_2.templatetags.same_tags" ), ] ): self.assertEqual( check_for_template_tags_with_the_same_name(None), [self.error_same_tags], ) @override_settings( INSTALLED_APPS=["check_framework.template_test_apps.same_tags_app_1"] ) def test_template_tags_with_same_library_name_and_module_name(self): with self.settings( TEMPLATES=[ self.get_settings( "same_tags", "different_tags_app.templatetags.different_tags", ), ] ): self.assertEqual( check_for_template_tags_with_the_same_name(None), [ Error( E003.msg.format( "'same_tags'", "'check_framework.template_test_apps.different_tags_app." "templatetags.different_tags', " "'check_framework.template_test_apps.same_tags_app_1." "templatetags.same_tags'", ), id=E003.id, ) ], ) def test_template_tags_with_different_library_name(self): with self.settings( TEMPLATES=[ self.get_settings( "same_tags", "same_tags_app_1.templatetags.same_tags" ), self.get_settings( "not_same_tags", "same_tags_app_2.templatetags.same_tags" ), ] ): self.assertEqual(check_for_template_tags_with_the_same_name(None), []) @override_settings( INSTALLED_APPS=[ "check_framework.template_test_apps.same_tags_app_1", "check_framework.template_test_apps.different_tags_app", ] ) def test_template_tags_with_different_name(self): self.assertEqual(check_for_template_tags_with_the_same_name(None), [])
946b46e19b260f9d15d6fc30690d8aed38d5ebf8b0b4b3fbbf3946a2dbc7a50f
import unittest from unittest import mock from django.core.checks.database import check_database_backends from django.db import connection, connections from django.test import TestCase class DatabaseCheckTests(TestCase): databases = {"default", "other"} @mock.patch("django.db.backends.base.validation.BaseDatabaseValidation.check") def test_database_checks_called(self, mocked_check): check_database_backends() self.assertFalse(mocked_check.called) check_database_backends(databases=self.databases) self.assertTrue(mocked_check.called) @unittest.skipUnless(connection.vendor == "mysql", "Test only for MySQL") def test_mysql_strict_mode(self): def _clean_sql_mode(): for alias in self.databases: if hasattr(connections[alias], "sql_mode"): del connections[alias].sql_mode _clean_sql_mode() good_sql_modes = [ "STRICT_TRANS_TABLES,STRICT_ALL_TABLES", "STRICT_TRANS_TABLES", "STRICT_ALL_TABLES", ] for sql_mode in good_sql_modes: with mock.patch.object( connection, "mysql_server_data", {"sql_mode": sql_mode}, ): self.assertEqual(check_database_backends(databases=self.databases), []) _clean_sql_mode() bad_sql_modes = ["", "WHATEVER"] for sql_mode in bad_sql_modes: mocker_default = mock.patch.object( connection, "mysql_server_data", {"sql_mode": sql_mode}, ) mocker_other = mock.patch.object( connections["other"], "mysql_server_data", {"sql_mode": sql_mode}, ) with mocker_default, mocker_other: # One warning for each database alias result = check_database_backends(databases=self.databases) self.assertEqual(len(result), 2) self.assertEqual([r.id for r in result], ["mysql.W002", "mysql.W002"]) _clean_sql_mode()
6adf2b6883458ba4945a00c4755566d0ee21836ba77b8affff9cb42e885a2f8b
import datetime from decimal import Decimal from django.contrib.humanize.templatetags import humanize from django.template import Context, Template, defaultfilters from django.test import SimpleTestCase, modify_settings, override_settings from django.utils import translation from django.utils.html import escape from django.utils.timezone import get_fixed_timezone, utc from django.utils.translation import gettext as _ # Mock out datetime in some tests so they don't fail occasionally when they # run too slow. Use a fixed datetime for datetime.now(). DST change in # America/Chicago (the default time zone) happened on March 11th in 2012. now = datetime.datetime(2012, 3, 9, 22, 30) class MockDateTime(datetime.datetime): @classmethod def now(cls, tz=None): if tz is None or tz.utcoffset(now) is None: return now else: # equals now.replace(tzinfo=utc) return now.replace(tzinfo=tz) + tz.utcoffset(now) @modify_settings(INSTALLED_APPS={"append": "django.contrib.humanize"}) class HumanizeTests(SimpleTestCase): def humanize_tester( self, test_list, result_list, method, normalize_result_func=escape ): for test_content, result in zip(test_list, result_list): with self.subTest(test_content): t = Template("{%% load humanize %%}{{ test_content|%s }}" % method) rendered = t.render(Context(locals())).strip() self.assertEqual( rendered, normalize_result_func(result), msg="%s test failed, produced '%s', should've produced '%s'" % (method, rendered, result), ) def test_ordinal(self): test_list = ( "1", "2", "3", "4", "11", "12", "13", "101", "102", "103", "111", "something else", None, ) result_list = ( "1st", "2nd", "3rd", "4th", "11th", "12th", "13th", "101st", "102nd", "103rd", "111th", "something else", None, ) with translation.override("en"): self.humanize_tester(test_list, result_list, "ordinal") def test_i18n_html_ordinal(self): """Allow html in output on i18n strings""" test_list = ( "1", "2", "3", "4", "11", "12", "13", "101", "102", "103", "111", "something else", None, ) result_list = ( "1<sup>er</sup>", "2<sup>e</sup>", "3<sup>e</sup>", "4<sup>e</sup>", "11<sup>e</sup>", "12<sup>e</sup>", "13<sup>e</sup>", "101<sup>er</sup>", "102<sup>e</sup>", "103<sup>e</sup>", "111<sup>e</sup>", "something else", "None", ) with translation.override("fr-fr"): self.humanize_tester(test_list, result_list, "ordinal", lambda x: x) def test_intcomma(self): test_list = ( 100, 1000, 10123, 10311, 1000000, 1234567.25, "100", "1000", "10123", "10311", "1000000", "1234567.1234567", Decimal("1234567.1234567"), None, "1234567", "1234567.12", ) result_list = ( "100", "1,000", "10,123", "10,311", "1,000,000", "1,234,567.25", "100", "1,000", "10,123", "10,311", "1,000,000", "1,234,567.1234567", "1,234,567.1234567", None, "1,234,567", "1,234,567.12", ) with translation.override("en"): self.humanize_tester(test_list, result_list, "intcomma") def test_l10n_intcomma(self): test_list = ( 100, 1000, 10123, 10311, 1000000, 1234567.25, "100", "1000", "10123", "10311", "1000000", "1234567.1234567", Decimal("1234567.1234567"), None, "1234567", "1234567.12", ) result_list = ( "100", "1,000", "10,123", "10,311", "1,000,000", "1,234,567.25", "100", "1,000", "10,123", "10,311", "1,000,000", "1,234,567.1234567", "1,234,567.1234567", None, "1,234,567", "1,234,567.12", ) with self.settings(USE_THOUSAND_SEPARATOR=False): with translation.override("en"): self.humanize_tester(test_list, result_list, "intcomma") def test_intcomma_without_number_grouping(self): # Regression for #17414 with translation.override("ja"): self.humanize_tester([100], ["100"], "intcomma") def test_intword(self): # Positive integers. test_list_positive = ( "100", "1000000", "1200000", "1290000", "1000000000", "2000000000", "6000000000000", "1300000000000000", "3500000000000000000000", "8100000000000000000000000000000000", ("1" + "0" * 100), ("1" + "0" * 104), ) result_list_positive = ( "100", "1.0 million", "1.2 million", "1.3 million", "1.0 billion", "2.0 billion", "6.0 trillion", "1.3 quadrillion", "3.5 sextillion", "8.1 decillion", "1.0 googol", ("1" + "0" * 104), ) # Negative integers. test_list_negative = ("-" + test for test in test_list_positive) result_list_negative = ("-" + result for result in result_list_positive) with translation.override("en"): self.humanize_tester( (*test_list_positive, *test_list_negative, None), (*result_list_positive, *result_list_negative, None), "intword", ) def test_i18n_intcomma(self): test_list = ( 100, 1000, 10123, 10311, 1000000, 1234567.25, "100", "1000", "10123", "10311", "1000000", None, ) result_list = ( "100", "1.000", "10.123", "10.311", "1.000.000", "1.234.567,25", "100", "1.000", "10.123", "10.311", "1.000.000", None, ) with self.settings(USE_THOUSAND_SEPARATOR=True): with translation.override("de"): self.humanize_tester(test_list, result_list, "intcomma") def test_i18n_intword(self): # Positive integers. test_list_positive = ( "100", "1000000", "1200000", "1290000", "1000000000", "2000000000", "6000000000000", ) result_list_positive = ( "100", "1,0 Million", "1,2 Millionen", "1,3 Millionen", "1,0 Milliarde", "2,0 Milliarden", "6,0 Billionen", ) # Negative integers. test_list_negative = ("-" + test for test in test_list_positive) result_list_negative = ("-" + result for result in result_list_positive) with self.settings(USE_THOUSAND_SEPARATOR=True): with translation.override("de"): self.humanize_tester( (*test_list_positive, *test_list_negative), (*result_list_positive, *result_list_negative), "intword", ) def test_apnumber(self): test_list = [str(x) for x in range(1, 11)] test_list.append(None) result_list = ( "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "10", None, ) with translation.override("en"): self.humanize_tester(test_list, result_list, "apnumber") def test_naturalday(self): today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) tomorrow = today + datetime.timedelta(days=1) someday = today - datetime.timedelta(days=10) notdate = "I'm not a date value" test_list = (today, yesterday, tomorrow, someday, notdate, None) someday_result = defaultfilters.date(someday) result_list = ( _("today"), _("yesterday"), _("tomorrow"), someday_result, "I'm not a date value", None, ) self.humanize_tester(test_list, result_list, "naturalday") def test_naturalday_tz(self): today = datetime.date.today() tz_one = get_fixed_timezone(-720) tz_two = get_fixed_timezone(720) # Can be today or yesterday date_one = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_one) naturalday_one = humanize.naturalday(date_one) # Can be today or tomorrow date_two = datetime.datetime(today.year, today.month, today.day, tzinfo=tz_two) naturalday_two = humanize.naturalday(date_two) # As 24h of difference they will never be the same self.assertNotEqual(naturalday_one, naturalday_two) def test_naturalday_uses_localtime(self): # Regression for #18504 # This is 2012-03-08HT19:30:00-06:00 in America/Chicago dt = datetime.datetime(2012, 3, 9, 1, 30, tzinfo=utc) orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime try: with override_settings(TIME_ZONE="America/Chicago", USE_TZ=True): with translation.override("en"): self.humanize_tester([dt], ["yesterday"], "naturalday") finally: humanize.datetime = orig_humanize_datetime def test_naturaltime(self): class naive(datetime.tzinfo): def utcoffset(self, dt): return None test_list = [ "test", now, now - datetime.timedelta(microseconds=1), now - datetime.timedelta(seconds=1), now - datetime.timedelta(seconds=30), now - datetime.timedelta(minutes=1, seconds=30), now - datetime.timedelta(minutes=2), now - datetime.timedelta(hours=1, minutes=30, seconds=30), now - datetime.timedelta(hours=23, minutes=50, seconds=50), now - datetime.timedelta(days=1), now - datetime.timedelta(days=500), now + datetime.timedelta(seconds=1), now + datetime.timedelta(seconds=30), now + datetime.timedelta(minutes=1, seconds=30), now + datetime.timedelta(minutes=2), now + datetime.timedelta(hours=1, minutes=30, seconds=30), now + datetime.timedelta(hours=23, minutes=50, seconds=50), now + datetime.timedelta(days=1), now + datetime.timedelta(days=2, hours=6), now + datetime.timedelta(days=500), now.replace(tzinfo=naive()), now.replace(tzinfo=utc), ] result_list = [ "test", "now", "now", "a second ago", "30\xa0seconds ago", "a minute ago", "2\xa0minutes ago", "an hour ago", "23\xa0hours ago", "1\xa0day ago", "1\xa0year, 4\xa0months ago", "a second from now", "30\xa0seconds from now", "a minute from now", "2\xa0minutes from now", "an hour from now", "23\xa0hours from now", "1\xa0day from now", "2\xa0days, 6\xa0hours from now", "1\xa0year, 4\xa0months from now", "now", "now", ] # Because of the DST change, 2 days and 6 hours after the chosen # date in naive arithmetic is only 2 days and 5 hours after in # aware arithmetic. result_list_with_tz_support = result_list[:] assert result_list_with_tz_support[-4] == "2\xa0days, 6\xa0hours from now" result_list_with_tz_support[-4] == "2\xa0days, 5\xa0hours from now" orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime try: with translation.override("en"): self.humanize_tester(test_list, result_list, "naturaltime") with override_settings(USE_TZ=True): self.humanize_tester( test_list, result_list_with_tz_support, "naturaltime" ) finally: humanize.datetime = orig_humanize_datetime def test_naturaltime_as_documented(self): """ #23340 -- Verify the documented behavior of humanize.naturaltime. """ time_format = "%d %b %Y %H:%M:%S" documented_now = datetime.datetime.strptime("17 Feb 2007 16:30:00", time_format) test_data = ( ("17 Feb 2007 16:30:00", "now"), ("17 Feb 2007 16:29:31", "29 seconds ago"), ("17 Feb 2007 16:29:00", "a minute ago"), ("17 Feb 2007 16:25:35", "4 minutes ago"), ("17 Feb 2007 15:30:29", "59 minutes ago"), ("17 Feb 2007 15:30:01", "59 minutes ago"), ("17 Feb 2007 15:30:00", "an hour ago"), ("17 Feb 2007 13:31:29", "2 hours ago"), ("16 Feb 2007 13:31:29", "1 day, 2 hours ago"), ("16 Feb 2007 13:30:01", "1 day, 2 hours ago"), ("16 Feb 2007 13:30:00", "1 day, 3 hours ago"), ("17 Feb 2007 16:30:30", "30 seconds from now"), ("17 Feb 2007 16:30:29", "29 seconds from now"), ("17 Feb 2007 16:31:00", "a minute from now"), ("17 Feb 2007 16:34:35", "4 minutes from now"), ("17 Feb 2007 17:30:29", "an hour from now"), ("17 Feb 2007 18:31:29", "2 hours from now"), ("18 Feb 2007 16:31:29", "1 day from now"), ("26 Feb 2007 18:31:29", "1 week, 2 days from now"), ) class DocumentedMockDateTime(datetime.datetime): @classmethod def now(cls, tz=None): if tz is None or tz.utcoffset(documented_now) is None: return documented_now else: return documented_now.replace(tzinfo=tz) + tz.utcoffset(now) orig_humanize_datetime = humanize.datetime humanize.datetime = DocumentedMockDateTime try: for test_time_string, expected_natural_time in test_data: with self.subTest(test_time_string): test_time = datetime.datetime.strptime( test_time_string, time_format ) natural_time = humanize.naturaltime(test_time).replace("\xa0", " ") self.assertEqual(expected_natural_time, natural_time) finally: humanize.datetime = orig_humanize_datetime def test_inflection_for_timedelta(self): """ Translation of '%d day'/'%d month'/… may differ depending on the context of the string it is inserted in. """ test_list = [ # "%(delta)s ago" translations now - datetime.timedelta(days=1), now - datetime.timedelta(days=2), now - datetime.timedelta(days=30), now - datetime.timedelta(days=60), now - datetime.timedelta(days=500), now - datetime.timedelta(days=865), # "%(delta)s from now" translations now + datetime.timedelta(days=1), now + datetime.timedelta(days=2), now + datetime.timedelta(days=30), now + datetime.timedelta(days=60), now + datetime.timedelta(days=500), now + datetime.timedelta(days=865), ] result_list = [ "před 1\xa0dnem", "před 2\xa0dny", "před 1\xa0měsícem", "před 2\xa0měsíci", "před 1\xa0rokem, 4\xa0měsíci", "před 2\xa0lety, 4\xa0měsíci", "za 1\xa0den", "za 2\xa0dny", "za 1\xa0měsíc", "za 2\xa0měsíce", "za 1\xa0rok, 4\xa0měsíce", "za 2\xa0roky, 4\xa0měsíce", ] orig_humanize_datetime, humanize.datetime = humanize.datetime, MockDateTime try: # Choose a language with different # naturaltime-past/naturaltime-future translations. with translation.override("cs"): self.humanize_tester(test_list, result_list, "naturaltime") finally: humanize.datetime = orig_humanize_datetime
9f43e137ef7b76efcd2c6c95fabdc72067fd85125a4c19f8fecf89a47a0e6179
from functools import update_wrapper, wraps from unittest import TestCase, mock from django.contrib.admin.views.decorators import staff_member_required from django.contrib.auth.decorators import ( login_required, permission_required, user_passes_test, ) from django.http import HttpRequest, HttpResponse, HttpResponseNotAllowed from django.middleware.clickjacking import XFrameOptionsMiddleware from django.test import SimpleTestCase from django.utils.decorators import method_decorator from django.utils.functional import keep_lazy, keep_lazy_text, lazy from django.utils.safestring import mark_safe from django.views.decorators.cache import cache_control, cache_page, never_cache from django.views.decorators.clickjacking import ( xframe_options_deny, xframe_options_exempt, xframe_options_sameorigin, ) from django.views.decorators.http import ( condition, require_GET, require_http_methods, require_POST, require_safe, ) from django.views.decorators.vary import vary_on_cookie, vary_on_headers def fully_decorated(request): """Expected __doc__""" return HttpResponse("<html><body>dummy</body></html>") fully_decorated.anything = "Expected __dict__" def compose(*functions): # compose(f, g)(*args, **kwargs) == f(g(*args, **kwargs)) functions = list(reversed(functions)) def _inner(*args, **kwargs): result = functions[0](*args, **kwargs) for f in functions[1:]: result = f(result) return result return _inner full_decorator = compose( # django.views.decorators.http require_http_methods(["GET"]), require_GET, require_POST, require_safe, condition(lambda r: None, lambda r: None), # django.views.decorators.vary vary_on_headers("Accept-language"), vary_on_cookie, # django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 user_passes_test(lambda u: True), login_required, permission_required("change_world"), # django.contrib.admin.views.decorators staff_member_required, # django.utils.functional keep_lazy(HttpResponse), keep_lazy_text, lazy, # django.utils.safestring mark_safe, ) fully_decorated = full_decorator(fully_decorated) class DecoratorsTest(TestCase): def test_attributes(self): """ Built-in decorators set certain attributes of the wrapped function. """ self.assertEqual(fully_decorated.__name__, "fully_decorated") self.assertEqual(fully_decorated.__doc__, "Expected __doc__") self.assertEqual(fully_decorated.__dict__["anything"], "Expected __dict__") def test_user_passes_test_composition(self): """ The user_passes_test decorator can be applied multiple times (#9474). """ def test1(user): user.decorators_applied.append("test1") return True def test2(user): user.decorators_applied.append("test2") return True def callback(request): return request.user.decorators_applied callback = user_passes_test(test1)(callback) callback = user_passes_test(test2)(callback) class DummyUser: pass class DummyRequest: pass request = DummyRequest() request.user = DummyUser() request.user.decorators_applied = [] response = callback(request) self.assertEqual(response, ["test2", "test1"]) def test_cache_page(self): def my_view(request): return "response" my_view_cached = cache_page(123)(my_view) self.assertEqual(my_view_cached(HttpRequest()), "response") my_view_cached2 = cache_page(123, key_prefix="test")(my_view) self.assertEqual(my_view_cached2(HttpRequest()), "response") def test_require_safe_accepts_only_safe_methods(self): """ Test for the require_safe decorator. A view returns either a response or an exception. Refs #15637. """ def my_view(request): return HttpResponse("OK") my_safe_view = require_safe(my_view) request = HttpRequest() request.method = "GET" self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = "HEAD" self.assertIsInstance(my_safe_view(request), HttpResponse) request.method = "POST" self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = "PUT" self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) request.method = "DELETE" self.assertIsInstance(my_safe_view(request), HttpResponseNotAllowed) # For testing method_decorator, a decorator that assumes a single argument. # We will get type arguments if there is a mismatch in the number of arguments. def simple_dec(func): def wrapper(arg): return func("test:" + arg) return wraps(func)(wrapper) simple_dec_m = method_decorator(simple_dec) # For testing method_decorator, two decorators that add an attribute to the function def myattr_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr = True return wrapper myattr_dec_m = method_decorator(myattr_dec) def myattr2_dec(func): def wrapper(*args, **kwargs): return func(*args, **kwargs) wrapper.myattr2 = True return wrapper myattr2_dec_m = method_decorator(myattr2_dec) class ClsDec: def __init__(self, myattr): self.myattr = myattr def __call__(self, f): def wrapped(): return f() and self.myattr return update_wrapper(wrapped, f) class MethodDecoratorTests(SimpleTestCase): """ Tests for method_decorator """ def test_preserve_signature(self): class Test: @simple_dec_m def say(self, arg): return arg self.assertEqual("test:hello", Test().say("hello")) def test_preserve_attributes(self): # Sanity check myattr_dec and myattr2_dec @myattr_dec def func(): pass self.assertIs(getattr(func, "myattr", False), True) @myattr2_dec def func(): pass self.assertIs(getattr(func, "myattr2", False), True) @myattr_dec @myattr2_dec def func(): pass self.assertIs(getattr(func, "myattr", False), True) self.assertIs(getattr(func, "myattr2", False), False) # Decorate using method_decorator() on the method. class TestPlain: @myattr_dec_m @myattr2_dec_m def method(self): "A method" pass # Decorate using method_decorator() on both the class and the method. # The decorators applied to the methods are applied before the ones # applied to the class. @method_decorator(myattr_dec_m, "method") class TestMethodAndClass: @method_decorator(myattr2_dec_m) def method(self): "A method" pass # Decorate using an iterable of function decorators. @method_decorator((myattr_dec, myattr2_dec), "method") class TestFunctionIterable: def method(self): "A method" pass # Decorate using an iterable of method decorators. decorators = (myattr_dec_m, myattr2_dec_m) @method_decorator(decorators, "method") class TestMethodIterable: def method(self): "A method" pass tests = ( TestPlain, TestMethodAndClass, TestFunctionIterable, TestMethodIterable, ) for Test in tests: with self.subTest(Test=Test): self.assertIs(getattr(Test().method, "myattr", False), True) self.assertIs(getattr(Test().method, "myattr2", False), True) self.assertIs(getattr(Test.method, "myattr", False), True) self.assertIs(getattr(Test.method, "myattr2", False), True) self.assertEqual(Test.method.__doc__, "A method") self.assertEqual(Test.method.__name__, "method") def test_new_attribute(self): """A decorator that sets a new attribute on the method.""" def decorate(func): func.x = 1 return func class MyClass: @method_decorator(decorate) def method(self): return True obj = MyClass() self.assertEqual(obj.method.x, 1) self.assertIs(obj.method(), True) def test_bad_iterable(self): decorators = {myattr_dec_m, myattr2_dec_m} msg = "'set' object is not subscriptable" with self.assertRaisesMessage(TypeError, msg): @method_decorator(decorators, "method") class TestIterable: def method(self): "A method" pass # Test for argumented decorator def test_argumented(self): class Test: @method_decorator(ClsDec(False)) def method(self): return True self.assertIs(Test().method(), False) def test_descriptors(self): def original_dec(wrapped): def _wrapped(arg): return wrapped(arg) return _wrapped method_dec = method_decorator(original_dec) class bound_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __call__(self, arg): return self.wrapped(arg) def __get__(self, instance, cls=None): return self class descriptor_wrapper: def __init__(self, wrapped): self.wrapped = wrapped self.__name__ = wrapped.__name__ def __get__(self, instance, cls=None): return bound_wrapper(self.wrapped.__get__(instance, cls)) class Test: @method_dec @descriptor_wrapper def method(self, arg): return arg self.assertEqual(Test().method(1), 1) def test_class_decoration(self): """ @method_decorator can be used to decorate a class and its methods. """ def deco(func): def _wrapper(*args, **kwargs): return True return _wrapper @method_decorator(deco, name="method") class Test: def method(self): return False self.assertTrue(Test().method()) def test_tuple_of_decorators(self): """ @method_decorator can accept a tuple of decorators. """ def add_question_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "?" return _wrapper def add_exclamation_mark(func): def _wrapper(*args, **kwargs): return func(*args, **kwargs) + "!" return _wrapper # The order should be consistent with the usual order in which # decorators are applied, e.g. # @add_exclamation_mark # @add_question_mark # def func(): # ... decorators = (add_exclamation_mark, add_question_mark) @method_decorator(decorators, name="method") class TestFirst: def method(self): return "hello world" class TestSecond: @method_decorator(decorators) def method(self): return "hello world" self.assertEqual(TestFirst().method(), "hello world?!") self.assertEqual(TestSecond().method(), "hello world?!") def test_invalid_non_callable_attribute_decoration(self): """ @method_decorator on a non-callable attribute raises an error. """ msg = ( "Cannot decorate 'prop' as it isn't a callable attribute of " "<class 'Test'> (1)" ) with self.assertRaisesMessage(TypeError, msg): @method_decorator(lambda: None, name="prop") class Test: prop = 1 @classmethod def __module__(cls): return "tests" def test_invalid_method_name_to_decorate(self): """ @method_decorator on a nonexistent method raises an error. """ msg = ( "The keyword argument `name` must be the name of a method of the " "decorated class: <class 'Test'>. Got 'nonexistent_method' instead" ) with self.assertRaisesMessage(ValueError, msg): @method_decorator(lambda: None, name="nonexistent_method") class Test: @classmethod def __module__(cls): return "tests" def test_wrapper_assignments(self): """@method_decorator preserves wrapper assignments.""" func_name = None func_module = None def decorator(func): @wraps(func) def inner(*args, **kwargs): nonlocal func_name, func_module func_name = getattr(func, "__name__", None) func_module = getattr(func, "__module__", None) return func(*args, **kwargs) return inner class Test: @method_decorator(decorator) def method(self): return "tests" Test().method() self.assertEqual(func_name, "method") self.assertIsNotNone(func_module) class XFrameOptionsDecoratorsTests(TestCase): """ Tests for the X-Frame-Options decorators. """ def test_deny_decorator(self): """ Ensures @xframe_options_deny properly sets the X-Frame-Options header. """ @xframe_options_deny def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "DENY") def test_sameorigin_decorator(self): """ Ensures @xframe_options_sameorigin properly sets the X-Frame-Options header. """ @xframe_options_sameorigin def a_view(request): return HttpResponse() r = a_view(HttpRequest()) self.assertEqual(r.headers["X-Frame-Options"], "SAMEORIGIN") def test_exempt_decorator(self): """ Ensures @xframe_options_exempt properly instructs the XFrameOptionsMiddleware to NOT set the header. """ @xframe_options_exempt def a_view(request): return HttpResponse() req = HttpRequest() resp = a_view(req) self.assertIsNone(resp.get("X-Frame-Options", None)) self.assertTrue(resp.xframe_options_exempt) # Since the real purpose of the exempt decorator is to suppress # the middleware's functionality, let's make sure it actually works... r = XFrameOptionsMiddleware(a_view)(req) self.assertIsNone(r.get("X-Frame-Options", None)) class HttpRequestProxy: def __init__(self, request): self._request = request def __getattr__(self, attr): """Proxy to the underlying HttpRequest object.""" return getattr(self._request, attr) class NeverCacheDecoratorTest(SimpleTestCase): @mock.patch("time.time") def test_never_cache_decorator_headers(self, mocked_time): @never_cache def a_view(request): return HttpResponse() mocked_time.return_value = 1167616461.0 response = a_view(HttpRequest()) self.assertEqual( response.headers["Expires"], "Mon, 01 Jan 2007 01:54:21 GMT", ) self.assertEqual( response.headers["Cache-Control"], "max-age=0, no-cache, no-store, must-revalidate, private", ) def test_never_cache_decorator_expires_not_overridden(self): @never_cache def a_view(request): return HttpResponse(headers={"Expires": "tomorrow"}) response = a_view(HttpRequest()) self.assertEqual(response.headers["Expires"], "tomorrow") def test_never_cache_decorator_http_request(self): class MyClass: @never_cache def a_view(self, request): return HttpResponse() request = HttpRequest() msg = ( "never_cache didn't receive an HttpRequest. If you are decorating " "a classmethod, be sure to use @method_decorator." ) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(request) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequestProxy(request)) def test_never_cache_decorator_http_request_proxy(self): class MyClass: @method_decorator(never_cache) def a_view(self, request): return HttpResponse() request = HttpRequest() response = MyClass().a_view(HttpRequestProxy(request)) self.assertIn("Cache-Control", response.headers) self.assertIn("Expires", response.headers) class CacheControlDecoratorTest(SimpleTestCase): def test_cache_control_decorator_http_request(self): class MyClass: @cache_control(a="b") def a_view(self, request): return HttpResponse() msg = ( "cache_control didn't receive an HttpRequest. If you are " "decorating a classmethod, be sure to use @method_decorator." ) request = HttpRequest() with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(request) with self.assertRaisesMessage(TypeError, msg): MyClass().a_view(HttpRequestProxy(request)) def test_cache_control_decorator_http_request_proxy(self): class MyClass: @method_decorator(cache_control(a="b")) def a_view(self, request): return HttpResponse() request = HttpRequest() response = MyClass().a_view(HttpRequestProxy(request)) self.assertEqual(response.headers["Cache-Control"], "a=b")
7e6e944dfef8e90aca2bd06d199000a1f3bd7a7a22ef654d485143eea9cc4bff
import datetime from django.contrib.auth.models import User from django.test import TestCase from .models import Order, RevisionableModel, TestObject class ExtraRegressTests(TestCase): @classmethod def setUpTestData(cls): cls.u = User.objects.create_user( username="fred", password="secret", email="[email protected]" ) def test_regression_7314_7372(self): """ Regression tests for #7314 and #7372 """ rm = RevisionableModel.objects.create( title="First Revision", when=datetime.datetime(2008, 9, 28, 10, 30, 0) ) self.assertEqual(rm.pk, rm.base.pk) rm2 = rm.new_revision() rm2.title = "Second Revision" rm.when = datetime.datetime(2008, 9, 28, 14, 25, 0) rm2.save() self.assertEqual(rm2.title, "Second Revision") self.assertEqual(rm2.base.title, "First Revision") self.assertNotEqual(rm2.pk, rm.pk) self.assertEqual(rm2.base.pk, rm.pk) # Queryset to match most recent revision: qs = RevisionableModel.objects.extra( where=[ "%(table)s.id IN " "(SELECT MAX(rev.id) FROM %(table)s rev GROUP BY rev.base_id)" % { "table": RevisionableModel._meta.db_table, } ] ) self.assertQuerysetEqual( qs, [("Second Revision", "First Revision")], transform=lambda r: (r.title, r.base.title), ) # Queryset to search for string in title: qs2 = RevisionableModel.objects.filter(title__contains="Revision") self.assertQuerysetEqual( qs2, [ ("First Revision", "First Revision"), ("Second Revision", "First Revision"), ], transform=lambda r: (r.title, r.base.title), ordered=False, ) # Following queryset should return the most recent revision: self.assertQuerysetEqual( qs & qs2, [("Second Revision", "First Revision")], transform=lambda r: (r.title, r.base.title), ordered=False, ) def test_extra_stay_tied(self): # Extra select parameters should stay tied to their corresponding # select portions. Applies when portions are updated or otherwise # moved around. qs = User.objects.extra( select={"alpha": "%s", "beta": "2", "gamma": "%s"}, select_params=(1, 3) ) qs = qs.extra(select={"beta": 4}) qs = qs.extra(select={"alpha": "%s"}, select_params=[5]) self.assertEqual( list(qs.filter(id=self.u.id).values("alpha", "beta", "gamma")), [{"alpha": 5, "beta": 4, "gamma": 3}], ) def test_regression_7957(self): """ Regression test for #7957: Combining extra() calls should leave the corresponding parameters associated with the right extra() bit. I.e. internal dictionary must remain sorted. """ self.assertEqual( ( User.objects.extra(select={"alpha": "%s"}, select_params=(1,)) .extra(select={"beta": "%s"}, select_params=(2,))[0] .alpha ), 1, ) self.assertEqual( ( User.objects.extra(select={"beta": "%s"}, select_params=(1,)) .extra(select={"alpha": "%s"}, select_params=(2,))[0] .alpha ), 2, ) def test_regression_7961(self): """ Regression test for #7961: When not using a portion of an extra(...) in a query, remove any corresponding parameters from the query as well. """ self.assertEqual( list( User.objects.extra(select={"alpha": "%s"}, select_params=(-6,)) .filter(id=self.u.id) .values_list("id", flat=True) ), [self.u.id], ) def test_regression_8063(self): """ Regression test for #8063: limiting a query shouldn't discard any extra() bits. """ qs = User.objects.extra(where=["id=%s"], params=[self.u.id]) self.assertSequenceEqual(qs, [self.u]) self.assertSequenceEqual(qs[:1], [self.u]) def test_regression_8039(self): """ Regression test for #8039: Ordering sometimes removed relevant tables from extra(). This test is the critical case: ordering uses a table, but then removes the reference because of an optimization. The table should still be present because of the extra() call. """ self.assertQuerysetEqual( ( Order.objects.extra( where=["username=%s"], params=["fred"], tables=["auth_user"] ).order_by("created_by") ), [], ) def test_regression_8819(self): """ Regression test for #8819: Fields in the extra(select=...) list should be available to extra(order_by=...). """ self.assertSequenceEqual( User.objects.filter(pk=self.u.id) .extra(select={"extra_field": 1}) .distinct(), [self.u], ) self.assertSequenceEqual( User.objects.filter(pk=self.u.id).extra( select={"extra_field": 1}, order_by=["extra_field"] ), [self.u], ) self.assertSequenceEqual( User.objects.filter(pk=self.u.id) .extra(select={"extra_field": 1}, order_by=["extra_field"]) .distinct(), [self.u], ) def test_dates_query(self): """ When calling the dates() method on a queryset with extra selection columns, we can (and should) ignore those columns. They don't change the result and cause incorrect SQL to be produced otherwise. """ RevisionableModel.objects.create( title="First Revision", when=datetime.datetime(2008, 9, 28, 10, 30, 0) ) self.assertSequenceEqual( RevisionableModel.objects.extra(select={"the_answer": "id"}).datetimes( "when", "month" ), [datetime.datetime(2008, 9, 1, 0, 0)], ) def test_values_with_extra(self): """ Regression test for #10256... If there is a values() clause, Extra columns are only returned if they are explicitly mentioned. """ obj = TestObject(first="first", second="second", third="third") obj.save() self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values() ), [ { "bar": "second", "third": "third", "second": "second", "whiz": "third", "foo": "first", "id": obj.pk, "first": "first", } ], ) # Extra clauses after an empty values clause are still included self.assertEqual( list( TestObject.objects.values().extra( select={"foo": "first", "bar": "second", "whiz": "third"} ) ), [ { "bar": "second", "third": "third", "second": "second", "whiz": "third", "foo": "first", "id": obj.pk, "first": "first", } ], ) # Extra columns are ignored if not mentioned in the values() clause self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values("first", "second") ), [{"second": "second", "first": "first"}], ) # Extra columns after a non-empty values() clause are ignored self.assertEqual( list( TestObject.objects.values("first", "second").extra( select={"foo": "first", "bar": "second", "whiz": "third"} ) ), [{"second": "second", "first": "first"}], ) # Extra columns can be partially returned self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values("first", "second", "foo") ), [{"second": "second", "foo": "first", "first": "first"}], ) # Also works if only extra columns are included self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values("foo", "whiz") ), [{"foo": "first", "whiz": "third"}], ) # Values list works the same way # All columns are returned for an empty values_list() self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values_list() ), [("first", "second", "third", obj.pk, "first", "second", "third")], ) # Extra columns after an empty values_list() are still included self.assertEqual( list( TestObject.objects.values_list().extra( select={"foo": "first", "bar": "second", "whiz": "third"} ) ), [("first", "second", "third", obj.pk, "first", "second", "third")], ) # Extra columns ignored completely if not mentioned in values_list() self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values_list("first", "second") ), [("first", "second")], ) # Extra columns after a non-empty values_list() clause are ignored completely self.assertEqual( list( TestObject.objects.values_list("first", "second").extra( select={"foo": "first", "bar": "second", "whiz": "third"} ) ), [("first", "second")], ) self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values_list("second", flat=True) ), ["second"], ) # Only the extra columns specified in the values_list() are returned self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values_list("first", "second", "whiz") ), [("first", "second", "third")], ) # ...also works if only extra columns are included self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values_list("foo", "whiz") ), [("first", "third")], ) self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values_list("whiz", flat=True) ), ["third"], ) # ... and values are returned in the order they are specified self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values_list("whiz", "foo") ), [("third", "first")], ) self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values_list("first", "id") ), [("first", obj.pk)], ) self.assertEqual( list( TestObject.objects.extra( select={"foo": "first", "bar": "second", "whiz": "third"} ).values_list("whiz", "first", "bar", "id") ), [("third", "first", "second", obj.pk)], ) def test_regression_10847(self): """ Regression for #10847: the list of extra columns can always be accurately evaluated. Using an inner query ensures that as_sql() is producing correct output without requiring full evaluation and execution of the inner query. """ obj = TestObject(first="first", second="second", third="third") obj.save() self.assertEqual( list(TestObject.objects.extra(select={"extra": 1}).values("pk")), [{"pk": obj.pk}], ) self.assertSequenceEqual( TestObject.objects.filter( pk__in=TestObject.objects.extra(select={"extra": 1}).values("pk") ), [obj], ) self.assertEqual( list(TestObject.objects.values("pk").extra(select={"extra": 1})), [{"pk": obj.pk}], ) self.assertSequenceEqual( TestObject.objects.filter( pk__in=TestObject.objects.values("pk").extra(select={"extra": 1}) ), [obj], ) self.assertSequenceEqual( TestObject.objects.filter(pk=obj.pk) | TestObject.objects.extra(where=["id > %s"], params=[obj.pk]), [obj], ) def test_regression_17877(self): """ Extra WHERE clauses get correctly ANDed, even when they contain OR operations. """ # Test Case 1: should appear in queryset. t1 = TestObject.objects.create(first="a", second="a", third="a") # Test Case 2: should appear in queryset. t2 = TestObject.objects.create(first="b", second="a", third="a") # Test Case 3: should not appear in queryset, bug case. t = TestObject(first="a", second="a", third="b") t.save() # Test Case 4: should not appear in queryset. t = TestObject(first="b", second="a", third="b") t.save() # Test Case 5: should not appear in queryset. t = TestObject(first="b", second="b", third="a") t.save() # Test Case 6: should not appear in queryset, bug case. t = TestObject(first="a", second="b", third="b") t.save() self.assertCountEqual( TestObject.objects.extra( where=["first = 'a' OR second = 'a'", "third = 'a'"], ), [t1, t2], ) def test_extra_values_distinct_ordering(self): t1 = TestObject.objects.create(first="a", second="a", third="a") t2 = TestObject.objects.create(first="a", second="b", third="b") qs = ( TestObject.objects.extra(select={"second_extra": "second"}) .values_list("id", flat=True) .distinct() ) self.assertSequenceEqual(qs.order_by("second_extra"), [t1.pk, t2.pk]) self.assertSequenceEqual(qs.order_by("-second_extra"), [t2.pk, t1.pk]) # Note: the extra ordering must appear in select clause, so we get two # non-distinct results here (this is on purpose, see #7070). # Extra select doesn't appear in result values. self.assertSequenceEqual( qs.order_by("-second_extra").values_list("first"), [("a",), ("a",)] )
d1d7bac8832fc27804a6413e69b001c8e4552d2119befa708485e23911da7881
import copy import datetime from django.contrib.auth.models import User from django.db import models class RevisionableModel(models.Model): base = models.ForeignKey("self", models.SET_NULL, null=True) title = models.CharField(blank=True, max_length=255) when = models.DateTimeField(default=datetime.datetime.now) def save(self, *args, force_insert=None, force_update=None, **kwargs): super().save( *args, force_insert=force_insert, force_update=force_update, **kwargs ) if not self.base: self.base = self super().save(*args, **kwargs) def new_revision(self): new_revision = copy.copy(self) new_revision.pk = None return new_revision class Order(models.Model): created_by = models.ForeignKey(User, models.CASCADE) text = models.TextField() class TestObject(models.Model): first = models.CharField(max_length=20) second = models.CharField(max_length=20) third = models.CharField(max_length=20) def __str__(self): return "TestObject: %s,%s,%s" % (self.first, self.second, self.third)
8a9c33772ed366d968ef3383d9afde989fa49080638e9bbaea8f0f345ce852d3
from django.contrib.admin.utils import quote from django.contrib.admin.views.main import IS_POPUP_VAR from django.contrib.auth.models import User from django.template.response import TemplateResponse from django.test import TestCase, override_settings from django.urls import reverse from .models import Action, Car, Person @override_settings( ROOT_URLCONF="admin_custom_urls.urls", ) class AdminCustomUrlsTest(TestCase): """ Remember that: * The Action model has a CharField PK. * The ModelAdmin for Action customizes the add_view URL, it's '<app name>/<model name>/!add/' """ @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]" ) Action.objects.create(name="delete", description="Remove things.") Action.objects.create(name="rename", description="Gives things other names.") Action.objects.create(name="add", description="Add things.") Action.objects.create( name="path/to/file/", description="An action with '/' in its name." ) Action.objects.create( name="path/to/html/document.html", description="An action with a name similar to a HTML doc path.", ) Action.objects.create( name="javascript:alert('Hello world');\">Click here</a>", description="An action with a name suspected of being a XSS attempt", ) def setUp(self): self.client.force_login(self.superuser) def test_basic_add_GET(self): """ Ensure GET on the add_view works. """ add_url = reverse("admin_custom_urls:admin_custom_urls_action_add") self.assertTrue(add_url.endswith("/!add/")) response = self.client.get(add_url) self.assertIsInstance(response, TemplateResponse) self.assertEqual(response.status_code, 200) def test_add_with_GET_args(self): """ Ensure GET on the add_view plus specifying a field value in the query string works. """ response = self.client.get( reverse("admin_custom_urls:admin_custom_urls_action_add"), {"name": "My Action"}, ) self.assertContains(response, 'value="My Action"') def test_basic_add_POST(self): """ Ensure POST on add_view works. """ post_data = { IS_POPUP_VAR: "1", "name": "Action added through a popup", "description": "Description of added action", } response = self.client.post( reverse("admin_custom_urls:admin_custom_urls_action_add"), post_data ) self.assertContains(response, "Action added through a popup") def test_admin_URLs_no_clash(self): # Should get the change_view for model instance with PK 'add', not show # the add_view url = reverse( "admin_custom_urls:%s_action_change" % Action._meta.app_label, args=(quote("add"),), ) response = self.client.get(url) self.assertContains(response, "Change action") # Should correctly get the change_view for the model instance with the # funny-looking PK (the one with a 'path/to/html/document.html' value) url = reverse( "admin_custom_urls:%s_action_change" % Action._meta.app_label, args=(quote("path/to/html/document.html"),), ) response = self.client.get(url) self.assertContains(response, "Change action") self.assertContains(response, 'value="path/to/html/document.html"') def test_post_save_add_redirect(self): """ ModelAdmin.response_post_save_add() controls the redirection after the 'Save' button has been pressed when adding a new object. """ post_data = {"name": "John Doe"} self.assertEqual(Person.objects.count(), 0) response = self.client.post( reverse("admin_custom_urls:admin_custom_urls_person_add"), post_data ) persons = Person.objects.all() self.assertEqual(len(persons), 1) redirect_url = reverse( "admin_custom_urls:admin_custom_urls_person_history", args=[persons[0].pk] ) self.assertRedirects(response, redirect_url) def test_post_save_change_redirect(self): """ ModelAdmin.response_post_save_change() controls the redirection after the 'Save' button has been pressed when editing an existing object. """ Person.objects.create(name="John Doe") self.assertEqual(Person.objects.count(), 1) person = Person.objects.all()[0] post_url = reverse( "admin_custom_urls:admin_custom_urls_person_change", args=[person.pk] ) response = self.client.post(post_url, {"name": "Jack Doe"}) self.assertRedirects( response, reverse( "admin_custom_urls:admin_custom_urls_person_delete", args=[person.pk] ), ) def test_post_url_continue(self): """ The ModelAdmin.response_add()'s parameter `post_url_continue` controls the redirection after an object has been created. """ post_data = {"name": "SuperFast", "_continue": "1"} self.assertEqual(Car.objects.count(), 0) response = self.client.post( reverse("admin_custom_urls:admin_custom_urls_car_add"), post_data ) cars = Car.objects.all() self.assertEqual(len(cars), 1) self.assertRedirects( response, reverse( "admin_custom_urls:admin_custom_urls_car_history", args=[cars[0].pk] ), )
3b52e7e2e939c42eb372735cc2ccff2f033bc46ff004772308995b562512281d
from functools import update_wrapper from django.contrib import admin from django.db import models from django.http import HttpResponseRedirect from django.urls import reverse class Action(models.Model): name = models.CharField(max_length=50, primary_key=True) description = models.CharField(max_length=70) def __str__(self): return self.name class ActionAdmin(admin.ModelAdmin): """ A ModelAdmin for the Action model that changes the URL of the add_view to '<app name>/<model name>/!add/' The Action model has a CharField PK. """ list_display = ("name", "description") def remove_url(self, name): """ Remove all entries named 'name' from the ModelAdmin instance URL patterns list """ return [url for url in super().get_urls() if url.name != name] def get_urls(self): # Add the URL of our custom 'add_view' view to the front of the URLs # list. Remove the existing one(s) first from django.urls import re_path def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = self.model._meta.app_label, self.model._meta.model_name view_name = "%s_%s_add" % info return [ re_path("^!add/$", wrap(self.add_view), name=view_name), ] + self.remove_url(view_name) class Person(models.Model): name = models.CharField(max_length=20) class PersonAdmin(admin.ModelAdmin): def response_post_save_add(self, request, obj): return HttpResponseRedirect( reverse("admin:admin_custom_urls_person_history", args=[obj.pk]) ) def response_post_save_change(self, request, obj): return HttpResponseRedirect( reverse("admin:admin_custom_urls_person_delete", args=[obj.pk]) ) class Car(models.Model): name = models.CharField(max_length=20) class CarAdmin(admin.ModelAdmin): def response_add(self, request, obj, post_url_continue=None): return super().response_add( request, obj, post_url_continue=reverse( "admin:admin_custom_urls_car_history", args=[obj.pk] ), ) site = admin.AdminSite(name="admin_custom_urls") site.register(Action, ActionAdmin) site.register(Person, PersonAdmin) site.register(Car, CarAdmin)
2d8482161501b204a5659c188eb9aa18612fd5691de1f994466b009dc27a5261
from django.urls import path from .models import site urlpatterns = [ path("admin/", site.urls), ]
a9473cbb9cef5a22737977f9c0292aa8a0ad0c93568c5d0092dcf89a103c1ed0
import os import shutil import tempfile from django import conf from django.test import SimpleTestCase from django.test.utils import extend_sys_path class TestStartProjectSettings(SimpleTestCase): def setUp(self): self.temp_dir = tempfile.TemporaryDirectory() self.addCleanup(self.temp_dir.cleanup) template_settings_py = os.path.join( os.path.dirname(conf.__file__), "project_template", "project_name", "settings.py-tpl", ) test_settings_py = os.path.join(self.temp_dir.name, "test_settings.py") shutil.copyfile(template_settings_py, test_settings_py) def test_middleware_headers(self): """ Ensure headers sent by the default MIDDLEWARE don't inadvertently change. For example, we never want "Vary: Cookie" to appear in the list since it prevents the caching of responses. """ with extend_sys_path(self.temp_dir.name): from test_settings import MIDDLEWARE with self.settings( MIDDLEWARE=MIDDLEWARE, ROOT_URLCONF="project_template.urls", ): response = self.client.get("/empty/") headers = sorted(response.serialize_headers().split(b"\r\n")) self.assertEqual( headers, [ b"Content-Length: 0", b"Content-Type: text/html; charset=utf-8", b"Cross-Origin-Opener-Policy: same-origin", b"Referrer-Policy: same-origin", b"X-Content-Type-Options: nosniff", b"X-Frame-Options: DENY", ], )
b8f23beb7fac234429312323c81905c4456e7ce29b89fdf224790f8d5c4dc980
from django.urls import path from . import views urlpatterns = [ path("empty/", views.empty_view), ]
cca97f4692f8cbba472c506348981595b92a274792d98f1e7192bdc14df973ee
from datetime import datetime from django.test import SimpleTestCase, override_settings FULL_RESPONSE = "Test conditional get response" LAST_MODIFIED = datetime(2007, 10, 21, 23, 21, 47) LAST_MODIFIED_STR = "Sun, 21 Oct 2007 23:21:47 GMT" LAST_MODIFIED_NEWER_STR = "Mon, 18 Oct 2010 16:56:23 GMT" LAST_MODIFIED_INVALID_STR = "Mon, 32 Oct 2010 16:56:23 GMT" EXPIRED_LAST_MODIFIED_STR = "Sat, 20 Oct 2007 23:21:47 GMT" ETAG = '"b4246ffc4f62314ca13147c9d4f76974"' WEAK_ETAG = 'W/"b4246ffc4f62314ca13147c9d4f76974"' # weak match to ETAG EXPIRED_ETAG = '"7fae4cd4b0f81e7d2914700043aa8ed6"' @override_settings(ROOT_URLCONF="conditional_processing.urls") class ConditionalGet(SimpleTestCase): def assertFullResponse(self, response, check_last_modified=True, check_etag=True): self.assertEqual(response.status_code, 200) self.assertEqual(response.content, FULL_RESPONSE.encode()) if response.request["REQUEST_METHOD"] in ("GET", "HEAD"): if check_last_modified: self.assertEqual(response.headers["Last-Modified"], LAST_MODIFIED_STR) if check_etag: self.assertEqual(response.headers["ETag"], ETAG) else: self.assertNotIn("Last-Modified", response.headers) self.assertNotIn("ETag", response.headers) def assertNotModified(self, response): self.assertEqual(response.status_code, 304) self.assertEqual(response.content, b"") def test_without_conditions(self): response = self.client.get("/condition/") self.assertFullResponse(response) def test_if_modified_since(self): self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.get("/condition/") self.assertNotModified(response) response = self.client.put("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_NEWER_STR response = self.client.get("/condition/") self.assertNotModified(response) response = self.client.put("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_INVALID_STR response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR response = self.client.get("/condition/") self.assertFullResponse(response) def test_if_unmodified_since(self): self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_NEWER_STR response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_INVALID_STR response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR response = self.client.get("/condition/") self.assertEqual(response.status_code, 412) def test_if_none_match(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/") self.assertNotModified(response) response = self.client.put("/condition/") self.assertEqual(response.status_code, 412) self.client.defaults["HTTP_IF_NONE_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/") self.assertFullResponse(response) # Several etags in If-None-Match is a bit exotic but why not? self.client.defaults["HTTP_IF_NONE_MATCH"] = "%s, %s" % (ETAG, EXPIRED_ETAG) response = self.client.get("/condition/") self.assertNotModified(response) def test_weak_if_none_match(self): """ If-None-Match comparisons use weak matching, so weak and strong ETags with the same value result in a 304 response. """ self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/weak_etag/") self.assertNotModified(response) response = self.client.put("/condition/weak_etag/") self.assertEqual(response.status_code, 412) self.client.defaults["HTTP_IF_NONE_MATCH"] = WEAK_ETAG response = self.client.get("/condition/weak_etag/") self.assertNotModified(response) response = self.client.put("/condition/weak_etag/") self.assertEqual(response.status_code, 412) response = self.client.get("/condition/") self.assertNotModified(response) response = self.client.put("/condition/") self.assertEqual(response.status_code, 412) def test_all_if_none_match(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = "*" response = self.client.get("/condition/") self.assertNotModified(response) response = self.client.put("/condition/") self.assertEqual(response.status_code, 412) response = self.client.get("/condition/no_etag/") self.assertFullResponse(response, check_last_modified=False, check_etag=False) def test_if_match(self): self.client.defaults["HTTP_IF_MATCH"] = ETAG response = self.client.put("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_MATCH"] = EXPIRED_ETAG response = self.client.put("/condition/") self.assertEqual(response.status_code, 412) def test_weak_if_match(self): """ If-Match comparisons use strong matching, so any comparison involving a weak ETag return a 412 response. """ self.client.defaults["HTTP_IF_MATCH"] = ETAG response = self.client.get("/condition/weak_etag/") self.assertEqual(response.status_code, 412) self.client.defaults["HTTP_IF_MATCH"] = WEAK_ETAG response = self.client.get("/condition/weak_etag/") self.assertEqual(response.status_code, 412) response = self.client.get("/condition/") self.assertEqual(response.status_code, 412) def test_all_if_match(self): self.client.defaults["HTTP_IF_MATCH"] = "*" response = self.client.get("/condition/") self.assertFullResponse(response) response = self.client.get("/condition/no_etag/") self.assertEqual(response.status_code, 412) def test_both_headers(self): # see https://tools.ietf.org/html/rfc7232#section-6 self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/") self.assertNotModified(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/") self.assertNotModified(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR self.client.defaults["HTTP_IF_NONE_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR self.client.defaults["HTTP_IF_NONE_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/") self.assertFullResponse(response) def test_both_headers_2(self): self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_STR self.client.defaults["HTTP_IF_MATCH"] = ETAG response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR self.client.defaults["HTTP_IF_MATCH"] = ETAG response = self.client.get("/condition/") self.assertFullResponse(response) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR self.client.defaults["HTTP_IF_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/") self.assertEqual(response.status_code, 412) self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_STR self.client.defaults["HTTP_IF_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/") self.assertEqual(response.status_code, 412) def test_single_condition_1(self): self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.get("/condition/last_modified/") self.assertNotModified(response) response = self.client.get("/condition/etag/") self.assertFullResponse(response, check_last_modified=False) def test_single_condition_2(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/etag/") self.assertNotModified(response) response = self.client.get("/condition/last_modified/") self.assertFullResponse(response, check_etag=False) def test_single_condition_3(self): self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR response = self.client.get("/condition/last_modified/") self.assertFullResponse(response, check_etag=False) def test_single_condition_4(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/etag/") self.assertFullResponse(response, check_last_modified=False) def test_single_condition_5(self): self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.get("/condition/last_modified2/") self.assertNotModified(response) response = self.client.get("/condition/etag2/") self.assertFullResponse(response, check_last_modified=False) def test_single_condition_6(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/etag2/") self.assertNotModified(response) response = self.client.get("/condition/last_modified2/") self.assertFullResponse(response, check_etag=False) def test_single_condition_7(self): self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR response = self.client.get("/condition/last_modified/") self.assertEqual(response.status_code, 412) response = self.client.get("/condition/etag/") self.assertEqual(response.status_code, 412) def test_single_condition_8(self): self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.get("/condition/last_modified/") self.assertFullResponse(response, check_etag=False) def test_single_condition_9(self): self.client.defaults["HTTP_IF_UNMODIFIED_SINCE"] = EXPIRED_LAST_MODIFIED_STR response = self.client.get("/condition/last_modified2/") self.assertEqual(response.status_code, 412) response = self.client.get("/condition/etag2/") self.assertEqual(response.status_code, 412) def test_single_condition_head(self): self.client.defaults["HTTP_IF_MODIFIED_SINCE"] = LAST_MODIFIED_STR response = self.client.head("/condition/") self.assertNotModified(response) def test_unquoted(self): """ The same quoted ETag should be set on the header regardless of whether etag_func() in condition() returns a quoted or an unquoted ETag. """ response_quoted = self.client.get("/condition/etag/") response_unquoted = self.client.get("/condition/unquoted_etag/") self.assertEqual(response_quoted["ETag"], response_unquoted["ETag"]) # It's possible that the matching algorithm could use the wrong value even # if the ETag header is set correctly correctly (as tested by # test_unquoted()), so check that the unquoted value is matched. def test_unquoted_if_none_match(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = ETAG response = self.client.get("/condition/unquoted_etag/") self.assertNotModified(response) response = self.client.put("/condition/unquoted_etag/") self.assertEqual(response.status_code, 412) self.client.defaults["HTTP_IF_NONE_MATCH"] = EXPIRED_ETAG response = self.client.get("/condition/unquoted_etag/") self.assertFullResponse(response, check_last_modified=False) def test_invalid_etag(self): self.client.defaults["HTTP_IF_NONE_MATCH"] = '"""' response = self.client.get("/condition/etag/") self.assertFullResponse(response, check_last_modified=False)
2b2a928a03004124d674f1f3f12722f3c5a7057eb6932f612b1876ad2d98354c
from django.urls import path from . import views urlpatterns = [ path("condition/", views.index), path("condition/last_modified/", views.last_modified_view1), path("condition/last_modified2/", views.last_modified_view2), path("condition/etag/", views.etag_view1), path("condition/etag2/", views.etag_view2), path("condition/unquoted_etag/", views.etag_view_unquoted), path("condition/weak_etag/", views.etag_view_weak), path("condition/no_etag/", views.etag_view_none), ]
bca54f129658d569af3645a5b483c55a48b453c2a99adf321a66d3ae61969be9
""" Callable defaults You can pass callable objects as the ``default`` parameter to a field. When the object is created without an explicit value passed in, Django will call the method to determine the default value. This example uses ``datetime.datetime.now`` as the default for the ``pub_date`` field. """ from datetime import datetime from django.db import models class Article(models.Model): headline = models.CharField(max_length=100, default="Default headline") pub_date = models.DateTimeField(default=datetime.now) def __str__(self): return self.headline
1aa72c50cae9ea348ccf80bfaf37e823a245ddf46df83ae2fe4cc4d11d196f88
from django.db import models from django.test import TestCase from .models import ( Book, Car, ConfusedBook, CustomManager, CustomQuerySet, DeconstructibleCustomManager, FastCarAsBase, FastCarAsDefault, FunPerson, OneToOneRestrictedModel, Person, PersonFromAbstract, PersonManager, PublishedBookManager, RelatedModel, RestrictedModel, ) class CustomManagerTests(TestCase): custom_manager_names = [ "custom_queryset_default_manager", "custom_queryset_custom_manager", ] @classmethod def setUpTestData(cls): cls.b1 = Book.published_objects.create( title="How to program", author="Rodney Dangerfield", is_published=True ) cls.b2 = Book.published_objects.create( title="How to be smart", author="Albert Einstein", is_published=False ) cls.p1 = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True) cls.droopy = Person.objects.create( first_name="Droopy", last_name="Dog", fun=False ) def test_custom_manager_basic(self): """ Test a custom Manager method. """ self.assertQuerysetEqual(Person.objects.get_fun_people(), ["Bugs Bunny"], str) def test_queryset_copied_to_default(self): """ The methods of a custom QuerySet are properly copied onto the default Manager. """ for manager_name in self.custom_manager_names: with self.subTest(manager_name=manager_name): manager = getattr(Person, manager_name) # Public methods are copied manager.public_method() # Private methods are not copied with self.assertRaises(AttributeError): manager._private_method() def test_manager_honors_queryset_only(self): for manager_name in self.custom_manager_names: with self.subTest(manager_name=manager_name): manager = getattr(Person, manager_name) # Methods with queryset_only=False are copied even if they are private. manager._optin_private_method() # Methods with queryset_only=True aren't copied even if they are public. msg = ( "%r object has no attribute 'optout_public_method'" % manager.__class__.__name__ ) with self.assertRaisesMessage(AttributeError, msg): manager.optout_public_method() def test_manager_use_queryset_methods(self): """ Custom manager will use the queryset methods """ for manager_name in self.custom_manager_names: with self.subTest(manager_name=manager_name): manager = getattr(Person, manager_name) queryset = manager.filter() self.assertQuerysetEqual(queryset, ["Bugs Bunny"], str) self.assertIs(queryset._filter_CustomQuerySet, True) # Specialized querysets inherit from our custom queryset. queryset = manager.values_list("first_name", flat=True).filter() self.assertEqual(list(queryset), ["Bugs"]) self.assertIs(queryset._filter_CustomQuerySet, True) self.assertIsInstance(queryset.values(), CustomQuerySet) self.assertIsInstance(queryset.values().values(), CustomQuerySet) self.assertIsInstance(queryset.values_list().values(), CustomQuerySet) def test_init_args(self): """ The custom manager __init__() argument has been set. """ self.assertEqual(Person.custom_queryset_custom_manager.init_arg, "hello") def test_manager_attributes(self): """ Custom manager method is only available on the manager and not on querysets. """ Person.custom_queryset_custom_manager.manager_only() msg = "'CustomQuerySet' object has no attribute 'manager_only'" with self.assertRaisesMessage(AttributeError, msg): Person.custom_queryset_custom_manager.all().manager_only() def test_queryset_and_manager(self): """ Queryset method doesn't override the custom manager method. """ queryset = Person.custom_queryset_custom_manager.filter() self.assertQuerysetEqual(queryset, ["Bugs Bunny"], str) self.assertIs(queryset._filter_CustomManager, True) def test_related_manager(self): """ The related managers extend the default manager. """ self.assertIsInstance(self.droopy.books, PublishedBookManager) self.assertIsInstance(self.b2.authors, PersonManager) def test_no_objects(self): """ The default manager, "objects", doesn't exist, because a custom one was provided. """ msg = "type object 'Book' has no attribute 'objects'" with self.assertRaisesMessage(AttributeError, msg): Book.objects def test_filtering(self): """ Custom managers respond to usual filtering methods """ self.assertQuerysetEqual( Book.published_objects.all(), [ "How to program", ], lambda b: b.title, ) def test_fk_related_manager(self): Person.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1 ) Person.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1 ) FunPerson.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1 ) FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1 ) self.assertQuerysetEqual( self.b1.favorite_books.order_by("first_name").all(), [ "Bugs", "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.fun_people_favorite_books.all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.favorite_books(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.favorite_books(manager="fun_people").all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) def test_fk_related_manager_reused(self): self.assertIs(self.b1.favorite_books, self.b1.favorite_books) self.assertIn("favorite_books", self.b1._state.related_managers_cache) def test_gfk_related_manager(self): Person.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1 ) Person.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1 ) FunPerson.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1 ) FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1 ) self.assertQuerysetEqual( self.b1.favorite_things.all(), [ "Bugs", "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.fun_people_favorite_things.all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.favorite_things(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.favorite_things(manager="fun_people").all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) def test_gfk_related_manager_reused(self): self.assertIs( self.b1.fun_people_favorite_things, self.b1.fun_people_favorite_things, ) self.assertIn( "fun_people_favorite_things", self.b1._state.related_managers_cache, ) def test_gfk_related_manager_not_reused_when_alternate(self): self.assertIsNot( self.b1.favorite_things(manager="fun_people"), self.b1.favorite_things(manager="fun_people"), ) def test_gfk_related_manager_no_overlap_when_not_hidden(self): """ If a GenericRelation defines a related_query_name (and thus the related_name) which shadows another GenericRelation, it should not cause those separate managers to clash. """ book = ConfusedBook.objects.create( title="How to program", author="Rodney Dangerfield", ) person = Person.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=book, ) fun_person = FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_thing=book, ) # The managers don't collide in the internal cache. self.assertIsNot(book.favorite_things, book.less_favorite_things) self.assertIs(book.favorite_things, book.favorite_things) self.assertIs(book.less_favorite_things, book.less_favorite_things) # Both managers are cached separately despite the collision in names. self.assertIn("favorite_things", book._state.related_managers_cache) self.assertIn("less_favorite_things", book._state.related_managers_cache) # "less_favorite_things" isn't available as a reverse related manager, # so never ends up in the cache. self.assertQuerysetEqual(fun_person.favorite_things.all(), [book]) with self.assertRaises(AttributeError): fun_person.less_favorite_things self.assertIn("favorite_things", fun_person._state.related_managers_cache) self.assertNotIn( "less_favorite_things", fun_person._state.related_managers_cache, ) # The GenericRelation doesn't exist for Person, only FunPerson, so the # exception prevents the cache from being polluted. with self.assertRaises(AttributeError): person.favorite_things self.assertNotIn("favorite_things", person._state.related_managers_cache) def test_m2m_related_manager(self): bugs = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True) self.b1.authors.add(bugs) droopy = Person.objects.create(first_name="Droopy", last_name="Dog", fun=False) self.b1.authors.add(droopy) bugs = FunPerson.objects.create(first_name="Bugs", last_name="Bunny", fun=True) self.b1.fun_authors.add(bugs) droopy = FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False ) self.b1.fun_authors.add(droopy) self.assertQuerysetEqual( self.b1.authors.order_by("first_name").all(), [ "Bugs", "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.fun_authors.order_by("first_name").all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.authors(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.authors(manager="fun_people").all(), [ "Bugs", ], lambda c: c.first_name, ordered=False, ) def test_m2m_related_forward_manager_reused(self): self.assertIs(self.b1.authors, self.b1.authors) self.assertIn("authors", self.b1._state.related_managers_cache) def test_m2m_related_revers_manager_reused(self): bugs = Person.objects.create(first_name="Bugs", last_name="Bunny") self.b1.authors.add(bugs) self.assertIs(bugs.books, bugs.books) self.assertIn("books", bugs._state.related_managers_cache) def test_removal_through_default_fk_related_manager(self, bulk=True): bugs = FunPerson.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1 ) droopy = FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1 ) self.b1.fun_people_favorite_books.remove(droopy, bulk=bulk) self.assertQuerysetEqual( FunPerson._base_manager.filter(favorite_book=self.b1), [ "Bugs", "Droopy", ], lambda c: c.first_name, ordered=False, ) self.b1.fun_people_favorite_books.remove(bugs, bulk=bulk) self.assertQuerysetEqual( FunPerson._base_manager.filter(favorite_book=self.b1), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) bugs.favorite_book = self.b1 bugs.save() self.b1.fun_people_favorite_books.clear(bulk=bulk) self.assertQuerysetEqual( FunPerson._base_manager.filter(favorite_book=self.b1), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) def test_slow_removal_through_default_fk_related_manager(self): self.test_removal_through_default_fk_related_manager(bulk=False) def test_removal_through_specified_fk_related_manager(self, bulk=True): Person.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_book=self.b1 ) droopy = Person.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_book=self.b1 ) # The fun manager DOESN'T remove boring people. self.b1.favorite_books(manager="fun_people").remove(droopy, bulk=bulk) self.assertQuerysetEqual( self.b1.favorite_books(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) # The boring manager DOES remove boring people. self.b1.favorite_books(manager="boring_people").remove(droopy, bulk=bulk) self.assertQuerysetEqual( self.b1.favorite_books(manager="boring_people").all(), [], lambda c: c.first_name, ordered=False, ) droopy.favorite_book = self.b1 droopy.save() # The fun manager ONLY clears fun people. self.b1.favorite_books(manager="fun_people").clear(bulk=bulk) self.assertQuerysetEqual( self.b1.favorite_books(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.favorite_books(manager="fun_people").all(), [], lambda c: c.first_name, ordered=False, ) def test_slow_removal_through_specified_fk_related_manager(self): self.test_removal_through_specified_fk_related_manager(bulk=False) def test_removal_through_default_gfk_related_manager(self, bulk=True): bugs = FunPerson.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1 ) droopy = FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1 ) self.b1.fun_people_favorite_things.remove(droopy, bulk=bulk) self.assertQuerysetEqual( FunPerson._base_manager.order_by("first_name").filter( favorite_thing_id=self.b1.pk ), [ "Bugs", "Droopy", ], lambda c: c.first_name, ordered=False, ) self.b1.fun_people_favorite_things.remove(bugs, bulk=bulk) self.assertQuerysetEqual( FunPerson._base_manager.order_by("first_name").filter( favorite_thing_id=self.b1.pk ), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) bugs.favorite_book = self.b1 bugs.save() self.b1.fun_people_favorite_things.clear(bulk=bulk) self.assertQuerysetEqual( FunPerson._base_manager.order_by("first_name").filter( favorite_thing_id=self.b1.pk ), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) def test_slow_removal_through_default_gfk_related_manager(self): self.test_removal_through_default_gfk_related_manager(bulk=False) def test_removal_through_specified_gfk_related_manager(self, bulk=True): Person.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_thing=self.b1 ) droopy = Person.objects.create( first_name="Droopy", last_name="Dog", fun=False, favorite_thing=self.b1 ) # The fun manager DOESN'T remove boring people. self.b1.favorite_things(manager="fun_people").remove(droopy, bulk=bulk) self.assertQuerysetEqual( self.b1.favorite_things(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) # The boring manager DOES remove boring people. self.b1.favorite_things(manager="boring_people").remove(droopy, bulk=bulk) self.assertQuerysetEqual( self.b1.favorite_things(manager="boring_people").all(), [], lambda c: c.first_name, ordered=False, ) droopy.favorite_thing = self.b1 droopy.save() # The fun manager ONLY clears fun people. self.b1.favorite_things(manager="fun_people").clear(bulk=bulk) self.assertQuerysetEqual( self.b1.favorite_things(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.favorite_things(manager="fun_people").all(), [], lambda c: c.first_name, ordered=False, ) def test_slow_removal_through_specified_gfk_related_manager(self): self.test_removal_through_specified_gfk_related_manager(bulk=False) def test_removal_through_default_m2m_related_manager(self): bugs = FunPerson.objects.create(first_name="Bugs", last_name="Bunny", fun=True) self.b1.fun_authors.add(bugs) droopy = FunPerson.objects.create( first_name="Droopy", last_name="Dog", fun=False ) self.b1.fun_authors.add(droopy) self.b1.fun_authors.remove(droopy) self.assertQuerysetEqual( self.b1.fun_authors.through._default_manager.all(), [ "Bugs", "Droopy", ], lambda c: c.funperson.first_name, ordered=False, ) self.b1.fun_authors.remove(bugs) self.assertQuerysetEqual( self.b1.fun_authors.through._default_manager.all(), [ "Droopy", ], lambda c: c.funperson.first_name, ordered=False, ) self.b1.fun_authors.add(bugs) self.b1.fun_authors.clear() self.assertQuerysetEqual( self.b1.fun_authors.through._default_manager.all(), [ "Droopy", ], lambda c: c.funperson.first_name, ordered=False, ) def test_removal_through_specified_m2m_related_manager(self): bugs = Person.objects.create(first_name="Bugs", last_name="Bunny", fun=True) self.b1.authors.add(bugs) droopy = Person.objects.create(first_name="Droopy", last_name="Dog", fun=False) self.b1.authors.add(droopy) # The fun manager DOESN'T remove boring people. self.b1.authors(manager="fun_people").remove(droopy) self.assertQuerysetEqual( self.b1.authors(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) # The boring manager DOES remove boring people. self.b1.authors(manager="boring_people").remove(droopy) self.assertQuerysetEqual( self.b1.authors(manager="boring_people").all(), [], lambda c: c.first_name, ordered=False, ) self.b1.authors.add(droopy) # The fun manager ONLY clears fun people. self.b1.authors(manager="fun_people").clear() self.assertQuerysetEqual( self.b1.authors(manager="boring_people").all(), [ "Droopy", ], lambda c: c.first_name, ordered=False, ) self.assertQuerysetEqual( self.b1.authors(manager="fun_people").all(), [], lambda c: c.first_name, ordered=False, ) def test_deconstruct_default(self): mgr = models.Manager() as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct() self.assertFalse(as_manager) self.assertEqual(mgr_path, "django.db.models.manager.Manager") self.assertEqual(args, ()) self.assertEqual(kwargs, {}) def test_deconstruct_as_manager(self): mgr = CustomQuerySet.as_manager() as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct() self.assertTrue(as_manager) self.assertEqual(qs_path, "custom_managers.models.CustomQuerySet") def test_deconstruct_from_queryset(self): mgr = DeconstructibleCustomManager("a", "b") as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct() self.assertFalse(as_manager) self.assertEqual( mgr_path, "custom_managers.models.DeconstructibleCustomManager" ) self.assertEqual( args, ( "a", "b", ), ) self.assertEqual(kwargs, {}) mgr = DeconstructibleCustomManager("x", "y", c=3, d=4) as_manager, mgr_path, qs_path, args, kwargs = mgr.deconstruct() self.assertFalse(as_manager) self.assertEqual( mgr_path, "custom_managers.models.DeconstructibleCustomManager" ) self.assertEqual( args, ( "x", "y", ), ) self.assertEqual(kwargs, {"c": 3, "d": 4}) def test_deconstruct_from_queryset_failing(self): mgr = CustomManager("arg") msg = ( "Could not find manager BaseCustomManagerFromCustomQuerySet in " "django.db.models.manager.\n" "Please note that you need to inherit from managers you " "dynamically generated with 'from_queryset()'." ) with self.assertRaisesMessage(ValueError, msg): mgr.deconstruct() def test_abstract_model_with_custom_manager_name(self): """ A custom manager may be defined on an abstract model. It will be inherited by the abstract model's children. """ PersonFromAbstract.abstract_persons.create(objects="Test") self.assertQuerysetEqual( PersonFromAbstract.abstract_persons.all(), ["Test"], lambda c: c.objects, ) class TestCars(TestCase): def test_managers(self): # Each model class gets a "_default_manager" attribute, which is a # reference to the first manager defined in the class. Car.cars.create(name="Corvette", mileage=21, top_speed=180) Car.cars.create(name="Neon", mileage=31, top_speed=100) self.assertQuerysetEqual( Car._default_manager.order_by("name"), [ "Corvette", "Neon", ], lambda c: c.name, ) self.assertQuerysetEqual( Car.cars.order_by("name"), [ "Corvette", "Neon", ], lambda c: c.name, ) # alternate manager self.assertQuerysetEqual( Car.fast_cars.all(), [ "Corvette", ], lambda c: c.name, ) # explicit default manager self.assertQuerysetEqual( FastCarAsDefault.cars.order_by("name"), [ "Corvette", "Neon", ], lambda c: c.name, ) self.assertQuerysetEqual( FastCarAsDefault._default_manager.all(), [ "Corvette", ], lambda c: c.name, ) # explicit base manager self.assertQuerysetEqual( FastCarAsBase.cars.order_by("name"), [ "Corvette", "Neon", ], lambda c: c.name, ) self.assertQuerysetEqual( FastCarAsBase._base_manager.all(), [ "Corvette", ], lambda c: c.name, ) class CustomManagersRegressTestCase(TestCase): def test_filtered_default_manager(self): """Even though the default manager filters out some records, we must still be able to save (particularly, save by updating existing records) those filtered instances. This is a regression test for #8990, #9527""" related = RelatedModel.objects.create(name="xyzzy") obj = RestrictedModel.objects.create(name="hidden", related=related) obj.name = "still hidden" obj.save() # If the hidden object wasn't seen during the save process, # there would now be two objects in the database. self.assertEqual(RestrictedModel.plain_manager.count(), 1) def test_refresh_from_db_when_default_manager_filters(self): """ Model.refresh_from_db() works for instances hidden by the default manager. """ book = Book._base_manager.create(is_published=False) Book._base_manager.filter(pk=book.pk).update(title="Hi") book.refresh_from_db() self.assertEqual(book.title, "Hi") def test_save_clears_annotations_from_base_manager(self): """Model.save() clears annotations from the base manager.""" self.assertEqual(Book._meta.base_manager.name, "annotated_objects") book = Book.annotated_objects.create(title="Hunting") Person.objects.create( first_name="Bugs", last_name="Bunny", fun=True, favorite_book=book, favorite_thing_id=1, ) book = Book.annotated_objects.first() self.assertEqual(book.favorite_avg, 1) # Annotation from the manager. book.title = "New Hunting" # save() fails if annotations that involve related fields aren't # cleared before the update query. book.save() self.assertEqual(Book.annotated_objects.first().title, "New Hunting") def test_delete_related_on_filtered_manager(self): """Deleting related objects should also not be distracted by a restricted manager on the related object. This is a regression test for #2698.""" related = RelatedModel.objects.create(name="xyzzy") for name, public in (("one", True), ("two", False), ("three", False)): RestrictedModel.objects.create(name=name, is_public=public, related=related) obj = RelatedModel.objects.get(name="xyzzy") obj.delete() # All of the RestrictedModel instances should have been # deleted, since they *all* pointed to the RelatedModel. If # the default manager is used, only the public one will be # deleted. self.assertEqual(len(RestrictedModel.plain_manager.all()), 0) def test_delete_one_to_one_manager(self): # The same test case as the last one, but for one-to-one # models, which are implemented slightly different internally, # so it's a different code path. obj = RelatedModel.objects.create(name="xyzzy") OneToOneRestrictedModel.objects.create(name="foo", is_public=False, related=obj) obj = RelatedModel.objects.get(name="xyzzy") obj.delete() self.assertEqual(len(OneToOneRestrictedModel.plain_manager.all()), 0) def test_queryset_with_custom_init(self): """ BaseManager.get_queryset() should use kwargs rather than args to allow custom kwargs (#24911). """ qs_custom = Person.custom_init_queryset_manager.all() qs_default = Person.objects.all() self.assertQuerysetEqual(qs_custom, qs_default)
d980c6441b4c3e9e87bec5bda6d673fd015edea892d0465b06184265769a0b16
""" Giving models a custom manager You can use a custom ``Manager`` in a particular model by extending the base ``Manager`` class and instantiating your custom ``Manager`` in your model. There are two reasons you might want to customize a ``Manager``: to add extra ``Manager`` methods, and/or to modify the initial ``QuerySet`` the ``Manager`` returns. """ from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.db import models class PersonManager(models.Manager): def get_fun_people(self): return self.filter(fun=True) class PublishedBookManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_published=True) class AnnotatedBookManager(models.Manager): def get_queryset(self): return ( super() .get_queryset() .annotate(favorite_avg=models.Avg("favorite_books__favorite_thing_id")) ) class CustomQuerySet(models.QuerySet): def filter(self, *args, **kwargs): queryset = super().filter(fun=True) queryset._filter_CustomQuerySet = True return queryset def public_method(self, *args, **kwargs): return self.all() def _private_method(self, *args, **kwargs): return self.all() def optout_public_method(self, *args, **kwargs): return self.all() optout_public_method.queryset_only = True def _optin_private_method(self, *args, **kwargs): return self.all() _optin_private_method.queryset_only = False class BaseCustomManager(models.Manager): def __init__(self, arg): super().__init__() self.init_arg = arg def filter(self, *args, **kwargs): queryset = super().filter(fun=True) queryset._filter_CustomManager = True return queryset def manager_only(self): return self.all() CustomManager = BaseCustomManager.from_queryset(CustomQuerySet) class CustomInitQuerySet(models.QuerySet): # QuerySet with an __init__() method that takes an additional argument. def __init__( self, custom_optional_arg=None, model=None, query=None, using=None, hints=None ): super().__init__(model=model, query=query, using=using, hints=hints) class DeconstructibleCustomManager(BaseCustomManager.from_queryset(CustomQuerySet)): def __init__(self, a, b, c=1, d=2): super().__init__(a) class FunPeopleManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(fun=True) class BoringPeopleManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(fun=False) class Person(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) fun = models.BooleanField(default=False) favorite_book = models.ForeignKey( "Book", models.SET_NULL, null=True, related_name="favorite_books" ) favorite_thing_type = models.ForeignKey( "contenttypes.ContentType", models.SET_NULL, null=True ) favorite_thing_id = models.IntegerField(null=True) favorite_thing = GenericForeignKey("favorite_thing_type", "favorite_thing_id") objects = PersonManager() fun_people = FunPeopleManager() boring_people = BoringPeopleManager() custom_queryset_default_manager = CustomQuerySet.as_manager() custom_queryset_custom_manager = CustomManager("hello") custom_init_queryset_manager = CustomInitQuerySet.as_manager() def __str__(self): return "%s %s" % (self.first_name, self.last_name) class FunPerson(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) fun = models.BooleanField(default=True) favorite_book = models.ForeignKey( "Book", models.SET_NULL, null=True, related_name="fun_people_favorite_books", ) favorite_thing_type = models.ForeignKey( "contenttypes.ContentType", models.SET_NULL, null=True ) favorite_thing_id = models.IntegerField(null=True) favorite_thing = GenericForeignKey("favorite_thing_type", "favorite_thing_id") objects = FunPeopleManager() class Book(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=30) is_published = models.BooleanField(default=False) authors = models.ManyToManyField(Person, related_name="books") fun_authors = models.ManyToManyField(FunPerson, related_name="books") favorite_things = GenericRelation( Person, content_type_field="favorite_thing_type", object_id_field="favorite_thing_id", ) fun_people_favorite_things = GenericRelation( FunPerson, content_type_field="favorite_thing_type", object_id_field="favorite_thing_id", ) published_objects = PublishedBookManager() annotated_objects = AnnotatedBookManager() class Meta: base_manager_name = "annotated_objects" class ConfusedBook(models.Model): title = models.CharField(max_length=50) author = models.CharField(max_length=30) favorite_things = GenericRelation( Person, content_type_field="favorite_thing_type", object_id_field="favorite_thing_id", ) less_favorite_things = GenericRelation( FunPerson, content_type_field="favorite_thing_type", object_id_field="favorite_thing_id", related_query_name="favorite_things", ) class FastCarManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(top_speed__gt=150) class Car(models.Model): name = models.CharField(max_length=10) mileage = models.IntegerField() top_speed = models.IntegerField(help_text="In miles per hour.") cars = models.Manager() fast_cars = FastCarManager() class FastCarAsBase(Car): class Meta: proxy = True base_manager_name = "fast_cars" class FastCarAsDefault(Car): class Meta: proxy = True default_manager_name = "fast_cars" class RestrictedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_public=True) class RelatedModel(models.Model): name = models.CharField(max_length=50) class RestrictedModel(models.Model): name = models.CharField(max_length=50) is_public = models.BooleanField(default=False) related = models.ForeignKey(RelatedModel, models.CASCADE) objects = RestrictedManager() plain_manager = models.Manager() class OneToOneRestrictedModel(models.Model): name = models.CharField(max_length=50) is_public = models.BooleanField(default=False) related = models.OneToOneField(RelatedModel, models.CASCADE) objects = RestrictedManager() plain_manager = models.Manager() class AbstractPerson(models.Model): abstract_persons = models.Manager() objects = models.CharField(max_length=30) class Meta: abstract = True class PersonFromAbstract(AbstractPerson): pass
fcbf81c200aac6efd75b7b03161f2a1d140560d35d6abf758ab812b52a094312
""" A series of tests to establish that the command-line management tools work as advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE and default settings.py files. """ import os import re import shutil import socket import stat import subprocess import sys import tempfile import unittest from io import StringIO from unittest import mock from django import conf, get_version from django.conf import settings from django.core.management import ( BaseCommand, CommandError, call_command, color, execute_from_command_line, ) from django.core.management.commands.loaddata import Command as LoaddataCommand from django.core.management.commands.runserver import Command as RunserverCommand from django.core.management.commands.testserver import Command as TestserverCommand from django.db import ConnectionHandler, connection from django.db.migrations.recorder import MigrationRecorder from django.test import LiveServerTestCase, SimpleTestCase, TestCase, override_settings from django.test.utils import captured_stderr, captured_stdout from django.urls import path from django.utils.version import PY39 from django.views.static import serve from . import urls custom_templates_dir = os.path.join(os.path.dirname(__file__), "custom_templates") SYSTEM_CHECK_MSG = "System check identified no issues" HAS_BLACK = shutil.which("black") class AdminScriptTestCase(SimpleTestCase): def setUp(self): tmpdir = tempfile.TemporaryDirectory() self.addCleanup(tmpdir.cleanup) # os.path.realpath() is required for temporary directories on macOS, # where `/var` is a symlink to `/private/var`. self.test_dir = os.path.realpath(os.path.join(tmpdir.name, "test_project")) os.mkdir(self.test_dir) def write_settings(self, filename, apps=None, is_dir=False, sdict=None, extra=None): if is_dir: settings_dir = os.path.join(self.test_dir, filename) os.mkdir(settings_dir) settings_file_path = os.path.join(settings_dir, "__init__.py") else: settings_file_path = os.path.join(self.test_dir, filename) with open(settings_file_path, "w") as settings_file: settings_file.write( "# Settings file automatically generated by admin_scripts test case\n" ) if extra: settings_file.write("%s\n" % extra) exports = [ "DATABASES", "DEFAULT_AUTO_FIELD", "ROOT_URLCONF", "SECRET_KEY", "USE_TZ", ] for s in exports: if hasattr(settings, s): o = getattr(settings, s) if not isinstance(o, (dict, tuple, list)): o = "'%s'" % o settings_file.write("%s = %s\n" % (s, o)) if apps is None: apps = [ "django.contrib.auth", "django.contrib.contenttypes", "admin_scripts", ] settings_file.write("INSTALLED_APPS = %s\n" % apps) if sdict: for k, v in sdict.items(): settings_file.write("%s = %s\n" % (k, v)) def _ext_backend_paths(self): """ Returns the paths for any external backend packages. """ paths = [] for backend in settings.DATABASES.values(): package = backend["ENGINE"].split(".")[0] if package != "django": backend_pkg = __import__(package) backend_dir = os.path.dirname(backend_pkg.__file__) paths.append(os.path.dirname(backend_dir)) return paths def run_test(self, args, settings_file=None, apps=None, umask=None): base_dir = os.path.dirname(self.test_dir) # The base dir for Django's tests is one level up. tests_dir = os.path.dirname(os.path.dirname(__file__)) # The base dir for Django is one level above the test dir. We don't use # `import django` to figure that out, so we don't pick up a Django # from site-packages or similar. django_dir = os.path.dirname(tests_dir) ext_backend_base_dirs = self._ext_backend_paths() # Define a temporary environment for the subprocess test_environ = os.environ.copy() # Set the test environment if settings_file: test_environ["DJANGO_SETTINGS_MODULE"] = settings_file elif "DJANGO_SETTINGS_MODULE" in test_environ: del test_environ["DJANGO_SETTINGS_MODULE"] python_path = [base_dir, django_dir, tests_dir] python_path.extend(ext_backend_base_dirs) test_environ["PYTHONPATH"] = os.pathsep.join(python_path) test_environ["PYTHONWARNINGS"] = "" p = subprocess.run( [sys.executable, *args], capture_output=True, cwd=self.test_dir, env=test_environ, text=True, # subprocess.run()'s umask was added in Python 3.9. **({"umask": umask} if umask and PY39 else {}), ) return p.stdout, p.stderr def run_django_admin(self, args, settings_file=None, umask=None): return self.run_test(["-m", "django", *args], settings_file, umask=umask) def run_manage(self, args, settings_file=None, manage_py=None): template_manage_py = ( os.path.join(os.path.dirname(__file__), manage_py) if manage_py else os.path.join( os.path.dirname(conf.__file__), "project_template", "manage.py-tpl" ) ) test_manage_py = os.path.join(self.test_dir, "manage.py") shutil.copyfile(template_manage_py, test_manage_py) with open(test_manage_py) as fp: manage_py_contents = fp.read() manage_py_contents = manage_py_contents.replace( "{{ project_name }}", "test_project" ) with open(test_manage_py, "w") as fp: fp.write(manage_py_contents) return self.run_test(["./manage.py", *args], settings_file) def assertNoOutput(self, stream): "Utility assertion: assert that the given stream is empty" self.assertEqual( len(stream), 0, "Stream should be empty: actually contains '%s'" % stream ) def assertOutput(self, stream, msg, regex=False): "Utility assertion: assert that the given message exists in the output" if regex: self.assertIsNotNone( re.search(msg, stream), "'%s' does not match actual output text '%s'" % (msg, stream), ) else: self.assertIn( msg, stream, "'%s' does not match actual output text '%s'" % (msg, stream), ) def assertNotInOutput(self, stream, msg): "Utility assertion: assert that the given message doesn't exist in the output" self.assertNotIn( msg, stream, "'%s' matches actual output text '%s'" % (msg, stream) ) ########################################################################## # DJANGO ADMIN TESTS # This first series of test classes checks the environment processing # of the django-admin. ########################################################################## class DjangoAdminNoSettings(AdminScriptTestCase): "A series of tests for django-admin when there is no settings.py file." def test_builtin_command(self): """ no settings: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_bad_settings(self): """ no settings: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ no settings: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_commands_with_invalid_settings(self): """ Commands that don't require settings succeed if the settings file doesn't exist. """ args = ["startproject"] out, err = self.run_django_admin(args, settings_file="bad_settings") self.assertNoOutput(out) self.assertOutput(err, "You must provide a project name", regex=True) class DjangoAdminDefaultSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings.py file that contains the test application. """ def setUp(self): super().setUp() self.write_settings("settings.py") def test_builtin_command(self): """ default: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ default: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ default: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ default: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ default: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ default: django-admin can't execute user commands if it isn't provided settings. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ default: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ default: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings.py file that contains the test application specified using a full path. """ def setUp(self): super().setUp() self.write_settings( "settings.py", [ "django.contrib.auth", "django.contrib.contenttypes", "admin_scripts", "admin_scripts.complex_app", ], ) def test_builtin_command(self): """ fulldefault: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ fulldefault: django-admin builtin commands succeed if a settings file is provided. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ fulldefault: django-admin builtin commands succeed if the environment contains settings. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ fulldefault: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ fulldefault: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ fulldefault: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ fulldefault: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ fulldefault: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminMinimalSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings.py file that doesn't contain the test application. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) def test_builtin_command(self): """ minimal: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ minimal: django-admin builtin commands fail if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): """ minimal: django-admin builtin commands fail if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): """ minimal: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ minimal: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "minimal: django-admin can't execute user commands unless settings are provided" args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ minimal: django-admin can't execute user commands, even if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): """ minimal: django-admin can't execute user commands, even if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class DjangoAdminAlternateSettings(AdminScriptTestCase): """ A series of tests for django-admin when using a settings file with a name other than 'settings.py'. """ def setUp(self): super().setUp() self.write_settings("alternate_settings.py") def test_builtin_command(self): """ alternate: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ alternate: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ alternate: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ alternate: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ alternate: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.alternate_settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ alternate: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminMultipleSettings(AdminScriptTestCase): """ A series of tests for django-admin when multiple settings files (including the default 'settings.py') are available. The default settings file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) self.write_settings("alternate_settings.py") def test_builtin_command(self): """ alternate: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_settings(self): """ alternate: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.alternate_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ alternate: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ alternate: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ alternate: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ alternate: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ alternate: django-admin can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.alternate_settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ alternate: django-admin can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_django_admin(args, "test_project.alternate_settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class DjangoAdminSettingsDirectory(AdminScriptTestCase): """ A series of tests for django-admin when the settings file is in a directory. (see #9751). """ def setUp(self): super().setUp() self.write_settings("settings", is_dir=True) def test_setup_environ(self): "directory: startapp creates the correct directory" args = ["startapp", "settings_test"] app_path = os.path.join(self.test_dir, "settings_test") out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) with open(os.path.join(app_path, "apps.py")) as f: content = f.read() self.assertIn("class SettingsTestConfig(AppConfig)", content) self.assertIn( 'name = "settings_test"' if HAS_BLACK else "name = 'settings_test'", content, ) def test_setup_environ_custom_template(self): "directory: startapp creates the correct directory with a custom template" template_path = os.path.join(custom_templates_dir, "app_template") args = ["startapp", "--template", template_path, "custom_settings_test"] app_path = os.path.join(self.test_dir, "custom_settings_test") out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) self.assertTrue(os.path.exists(os.path.join(app_path, "api.py"))) def test_startapp_unicode_name(self): """startapp creates the correct directory with Unicode characters.""" args = ["startapp", "こんにちは"] app_path = os.path.join(self.test_dir, "こんにちは") out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertTrue(os.path.exists(app_path)) with open(os.path.join(app_path, "apps.py"), encoding="utf8") as f: content = f.read() self.assertIn("class こんにちはConfig(AppConfig)", content) self.assertIn('name = "こんにちは"' if HAS_BLACK else "name = 'こんにちは'", content) def test_builtin_command(self): """ directory: django-admin builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "settings are not configured") def test_builtin_with_bad_settings(self): """ directory: django-admin builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ directory: django-admin builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ directory: django-admin can't execute user commands unless settings are provided. """ args = ["noargs_command"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "No Django settings specified") self.assertOutput(err, "Unknown command: 'noargs_command'") def test_builtin_with_settings(self): """ directory: django-admin builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ directory: django-admin builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) ########################################################################## # MANAGE.PY TESTS # This next series of test classes checks the environment processing # of the generated manage.py script ########################################################################## class ManageManuallyConfiguredSettings(AdminScriptTestCase): """Customized manage.py calling settings.configure().""" def test_non_existent_command_output(self): out, err = self.run_manage( ["invalid_command"], manage_py="configured_settings_manage.py" ) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'invalid_command'") self.assertNotInOutput(err, "No Django settings specified") class ManageNoSettings(AdminScriptTestCase): "A series of tests for manage.py when there is no settings.py file." def test_builtin_command(self): """ no settings: manage.py builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput( err, r"No module named '?(test_project\.)?settings'?", regex=True ) def test_builtin_with_bad_settings(self): """ no settings: manage.py builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ no settings: manage.py builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) class ManageDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application. """ def setUp(self): super().setUp() self.write_settings("settings.py") def test_builtin_command(self): """ default: manage.py builtin commands succeed when default settings are appropriate. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_settings(self): """ default: manage.py builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ default: manage.py builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ default: manage.py builtin commands succeed if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ default: manage.py builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ default: manage.py can execute user commands when default settings are appropriate. """ args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_settings(self): """ default: manage.py can execute user commands when settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ default: manage.py can execute user commands when settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageFullPathDefaultSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that contains the test application specified using a full path. """ def setUp(self): super().setUp() self.write_settings( "settings.py", ["django.contrib.auth", "django.contrib.contenttypes", "admin_scripts"], ) def test_builtin_command(self): """ fulldefault: manage.py builtin commands succeed when default settings are appropriate. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_settings(self): """ fulldefault: manage.py builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ fulldefault: manage.py builtin commands succeed if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ fulldefault: manage.py builtin commands succeed if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ fulldefault: manage.py builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): """ fulldefault: manage.py can execute user commands when default settings are appropriate. """ args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_settings(self): """ fulldefault: manage.py can execute user commands when settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ fulldefault: manage.py can execute user commands when settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageMinimalSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that doesn't contain the test application. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) def test_builtin_command(self): """ minimal: manage.py builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_settings(self): "minimal: manage.py builtin commands fail if settings are provided as argument" args = ["check", "--settings=test_project.settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_environment(self): """ minimal: manage.py builtin commands fail if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_bad_settings(self): """ minimal: manage.py builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ minimal: manage.py builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "minimal: manage.py can't execute user commands without appropriate settings" args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ minimal: manage.py can't execute user commands, even if settings are provided as argument. """ args = ["noargs_command", "--settings=test_project.settings"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_environment(self): """ minimal: manage.py can't execute user commands, even if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_manage(args, "test_project.settings") self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") class ManageAlternateSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings file with a name other than 'settings.py'. """ def setUp(self): super().setUp() self.write_settings("alternate_settings.py") def test_builtin_command(self): """ alternate: manage.py builtin commands fail with an error when no default settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput( err, r"No module named '?(test_project\.)?settings'?", regex=True ) def test_builtin_with_settings(self): "alternate: manage.py builtin commands work with settings provided as argument" args = ["check", "--settings=alternate_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertOutput(out, SYSTEM_CHECK_MSG) self.assertNoOutput(err) def test_builtin_with_environment(self): """ alternate: manage.py builtin commands work if settings are provided in the environment """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "alternate_settings") self.assertOutput(out, SYSTEM_CHECK_MSG) self.assertNoOutput(err) def test_builtin_with_bad_settings(self): """ alternate: manage.py builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ alternate: manage.py builtin commands fail if settings file (from environment) doesn't exist """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "alternate: manage.py can't execute user commands without settings" args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput( err, r"No module named '?(test_project\.)?settings'?", regex=True ) def test_custom_command_with_settings(self): """ alternate: manage.py can execute user commands if settings are provided as argument """ args = ["noargs_command", "--settings=alternate_settings"] out, err = self.run_manage(args) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', " "'alternate_settings'), ('traceback', False), ('verbosity', 1)]", ) self.assertNoOutput(err) def test_custom_command_with_environment(self): """ alternate: manage.py can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_manage(args, "alternate_settings") self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', None), " "('traceback', False), ('verbosity', 1)]", ) self.assertNoOutput(err) def test_custom_command_output_color(self): """ alternate: manage.py output syntax color can be deactivated with the `--no-color` option. """ args = ["noargs_command", "--no-color", "--settings=alternate_settings"] out, err = self.run_manage(args) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', True), ('pythonpath', None), ('settings', " "'alternate_settings'), ('traceback', False), ('verbosity', 1)]", ) self.assertNoOutput(err) class ManageMultipleSettings(AdminScriptTestCase): """A series of tests for manage.py when multiple settings files (including the default 'settings.py') are available. The default settings file is insufficient for performing the operations described, so the alternate settings must be used by the running script. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) self.write_settings("alternate_settings.py") def test_builtin_command(self): """ multiple: manage.py builtin commands fail with an error when no settings provided. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No installed app with label 'admin_scripts'.") def test_builtin_with_settings(self): """ multiple: manage.py builtin commands succeed if settings are provided as argument. """ args = ["check", "--settings=alternate_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_environment(self): """ multiple: manage.py can execute builtin commands if settings are provided in the environment. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "alternate_settings") self.assertNoOutput(err) self.assertOutput(out, SYSTEM_CHECK_MSG) def test_builtin_with_bad_settings(self): """ multiple: manage.py builtin commands fail if settings file (from argument) doesn't exist. """ args = ["check", "--settings=bad_settings", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_builtin_with_bad_environment(self): """ multiple: manage.py builtin commands fail if settings file (from environment) doesn't exist. """ args = ["check", "admin_scripts"] out, err = self.run_manage(args, "bad_settings") self.assertNoOutput(out) self.assertOutput(err, "No module named '?bad_settings'?", regex=True) def test_custom_command(self): "multiple: manage.py can't execute user commands using default settings" args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") def test_custom_command_with_settings(self): """ multiple: manage.py can execute user commands if settings are provided as argument. """ args = ["noargs_command", "--settings=alternate_settings"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") def test_custom_command_with_environment(self): """ multiple: manage.py can execute user commands if settings are provided in environment. """ args = ["noargs_command"] out, err = self.run_manage(args, "alternate_settings") self.assertNoOutput(err) self.assertOutput(out, "EXECUTE: noargs_command") class ManageSettingsWithSettingsErrors(AdminScriptTestCase): """ Tests for manage.py when using the default settings.py file containing runtime errors. """ def write_settings_with_import_error(self, filename): settings_file_path = os.path.join(self.test_dir, filename) with open(settings_file_path, "w") as settings_file: settings_file.write( "# Settings file automatically generated by admin_scripts test case\n" ) settings_file.write( "# The next line will cause an import error:\nimport foo42bar\n" ) def test_import_error(self): """ import error: manage.py builtin commands shows useful diagnostic info when settings with import errors is provided (#14130). """ self.write_settings_with_import_error("settings.py") args = ["check", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "No module named") self.assertOutput(err, "foo42bar") def test_attribute_error(self): """ manage.py builtin commands does not swallow attribute error due to bad settings (#18845). """ self.write_settings("settings.py", sdict={"BAD_VAR": "INSTALLED_APPS.crash"}) args = ["collectstatic", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "AttributeError: 'list' object has no attribute 'crash'") def test_key_error(self): self.write_settings("settings.py", sdict={"BAD_VAR": 'DATABASES["blah"]'}) args = ["collectstatic", "admin_scripts"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "KeyError: 'blah'") def test_help(self): """ Test listing available commands output note when only core commands are available. """ self.write_settings( "settings.py", extra="from django.core.exceptions import ImproperlyConfigured\n" "raise ImproperlyConfigured()", ) args = ["help"] out, err = self.run_manage(args) self.assertOutput(out, "only Django core commands are listed") self.assertNoOutput(err) class ManageCheck(AdminScriptTestCase): def test_nonexistent_app(self): """check reports an error on a nonexistent app in INSTALLED_APPS.""" self.write_settings( "settings.py", apps=["admin_scriptz.broken_app"], sdict={"USE_I18N": False}, ) args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "ModuleNotFoundError") self.assertOutput(err, "No module named") self.assertOutput(err, "admin_scriptz") def test_broken_app(self): """manage.py check reports an ImportError if an app's models.py raises one on import""" self.write_settings("settings.py", apps=["admin_scripts.broken_app"]) args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "ImportError") def test_complex_app(self): """manage.py check does not raise an ImportError validating a complex app with nested calls to load_app""" self.write_settings( "settings.py", apps=[ "admin_scripts.complex_app", "admin_scripts.simple_app", "django.contrib.admin.apps.SimpleAdminConfig", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.messages", ], sdict={ "DEBUG": True, "MIDDLEWARE": [ "django.contrib.messages.middleware.MessageMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", ], "TEMPLATES": [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ], }, ) args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertEqual(out, "System check identified no issues (0 silenced).\n") def test_app_with_import(self): """manage.py check does not raise errors when an app imports a base class that itself has an abstract base.""" self.write_settings( "settings.py", apps=[ "admin_scripts.app_with_import", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sites", ], sdict={"DEBUG": True}, ) args = ["check"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertEqual(out, "System check identified no issues (0 silenced).\n") def test_output_format(self): """All errors/warnings should be sorted by level and by message.""" self.write_settings( "settings.py", apps=[ "admin_scripts.app_raising_messages", "django.contrib.auth", "django.contrib.contenttypes", ], sdict={"DEBUG": True}, ) args = ["check"] out, err = self.run_manage(args) expected_err = ( "SystemCheckError: System check identified some issues:\n" "\n" "ERRORS:\n" "?: An error\n" "\tHINT: Error hint\n" "\n" "WARNINGS:\n" "a: Second warning\n" "obj: First warning\n" "\tHINT: Hint\n" "\n" "System check identified 3 issues (0 silenced).\n" ) self.assertEqual(err, expected_err) self.assertNoOutput(out) def test_warning_does_not_halt(self): """ When there are only warnings or less serious messages, then Django should not prevent user from launching their project, so `check` command should not raise `CommandError` exception. In this test we also test output format. """ self.write_settings( "settings.py", apps=[ "admin_scripts.app_raising_warning", "django.contrib.auth", "django.contrib.contenttypes", ], sdict={"DEBUG": True}, ) args = ["check"] out, err = self.run_manage(args) expected_err = ( "System check identified some issues:\n" # No "CommandError: " part "\n" "WARNINGS:\n" "?: A warning\n" "\n" "System check identified 1 issue (0 silenced).\n" ) self.assertEqual(err, expected_err) self.assertNoOutput(out) class ManageRunserver(SimpleTestCase): def setUp(self): def monkey_run(*args, **options): return self.output = StringIO() self.cmd = RunserverCommand(stdout=self.output) self.cmd.run = monkey_run def assertServerSettings(self, addr, port, ipv6=False, raw_ipv6=False): self.assertEqual(self.cmd.addr, addr) self.assertEqual(self.cmd.port, port) self.assertEqual(self.cmd.use_ipv6, ipv6) self.assertEqual(self.cmd._raw_ipv6, raw_ipv6) def test_runserver_addrport(self): call_command(self.cmd) self.assertServerSettings("127.0.0.1", "8000") call_command(self.cmd, addrport="1.2.3.4:8000") self.assertServerSettings("1.2.3.4", "8000") call_command(self.cmd, addrport="7000") self.assertServerSettings("127.0.0.1", "7000") @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_addrport_ipv6(self): call_command(self.cmd, addrport="", use_ipv6=True) self.assertServerSettings("::1", "8000", ipv6=True, raw_ipv6=True) call_command(self.cmd, addrport="7000", use_ipv6=True) self.assertServerSettings("::1", "7000", ipv6=True, raw_ipv6=True) call_command(self.cmd, addrport="[2001:0db8:1234:5678::9]:7000") self.assertServerSettings( "2001:0db8:1234:5678::9", "7000", ipv6=True, raw_ipv6=True ) def test_runner_hostname(self): call_command(self.cmd, addrport="localhost:8000") self.assertServerSettings("localhost", "8000") call_command(self.cmd, addrport="test.domain.local:7000") self.assertServerSettings("test.domain.local", "7000") @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_hostname_ipv6(self): call_command(self.cmd, addrport="test.domain.local:7000", use_ipv6=True) self.assertServerSettings("test.domain.local", "7000", ipv6=True) def test_runner_custom_defaults(self): self.cmd.default_addr = "0.0.0.0" self.cmd.default_port = "5000" call_command(self.cmd) self.assertServerSettings("0.0.0.0", "5000") @unittest.skipUnless(socket.has_ipv6, "platform doesn't support IPv6") def test_runner_custom_defaults_ipv6(self): self.cmd.default_addr_ipv6 = "::" call_command(self.cmd, use_ipv6=True) self.assertServerSettings("::", "8000", ipv6=True, raw_ipv6=True) def test_runner_ambiguous(self): # Only 4 characters, all of which could be in an ipv6 address call_command(self.cmd, addrport="beef:7654") self.assertServerSettings("beef", "7654") # Uses only characters that could be in an ipv6 address call_command(self.cmd, addrport="deadbeef:7654") self.assertServerSettings("deadbeef", "7654") def test_no_database(self): """ Ensure runserver.check_migrations doesn't choke on empty DATABASES. """ tested_connections = ConnectionHandler({}) with mock.patch( "django.core.management.base.connections", new=tested_connections ): self.cmd.check_migrations() def test_readonly_database(self): """ runserver.check_migrations() doesn't choke when a database is read-only. """ with mock.patch.object(MigrationRecorder, "has_table", return_value=False): self.cmd.check_migrations() # You have # ... self.assertIn("unapplied migration(s)", self.output.getvalue()) @mock.patch("django.core.management.commands.runserver.run") @mock.patch("django.core.management.base.BaseCommand.check_migrations") @mock.patch("django.core.management.base.BaseCommand.check") def test_skip_checks(self, mocked_check, *mocked_objects): call_command( "runserver", use_reloader=False, skip_checks=True, stdout=self.output, ) self.assertNotIn("Performing system checks...", self.output.getvalue()) mocked_check.assert_not_called() self.output.truncate(0) call_command( "runserver", use_reloader=False, skip_checks=False, stdout=self.output, ) self.assertIn("Performing system checks...", self.output.getvalue()) mocked_check.assert_called() class ManageRunserverMigrationWarning(TestCase): def setUp(self): self.stdout = StringIO() self.runserver_command = RunserverCommand(stdout=self.stdout) @override_settings(INSTALLED_APPS=["admin_scripts.app_waiting_migration"]) def test_migration_warning_one_app(self): self.runserver_command.check_migrations() output = self.stdout.getvalue() self.assertIn("You have 1 unapplied migration(s)", output) self.assertIn("apply the migrations for app(s): app_waiting_migration.", output) @override_settings( INSTALLED_APPS=[ "admin_scripts.app_waiting_migration", "admin_scripts.another_app_waiting_migration", ], ) def test_migration_warning_multiple_apps(self): self.runserver_command.check_migrations() output = self.stdout.getvalue() self.assertIn("You have 2 unapplied migration(s)", output) self.assertIn( "apply the migrations for app(s): another_app_waiting_migration, " "app_waiting_migration.", output, ) class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase): def setUp(self): super().setUp() self.write_settings( "settings.py", sdict={ "ALLOWED_HOSTS": [], "DEBUG": False, }, ) def test_empty_allowed_hosts_error(self): out, err = self.run_manage(["runserver"]) self.assertNoOutput(out) self.assertOutput( err, "CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False." ) class ManageRunserverHelpOutput(AdminScriptTestCase): def test_suppressed_options(self): """runserver doesn't support --verbosity and --trackback options.""" out, err = self.run_manage(["runserver", "--help"]) self.assertNotInOutput(out, "--verbosity") self.assertNotInOutput(out, "--trackback") self.assertOutput(out, "--settings") class ManageTestserver(SimpleTestCase): @mock.patch.object(TestserverCommand, "handle", return_value="") def test_testserver_handle_params(self, mock_handle): out = StringIO() call_command("testserver", "blah.json", stdout=out) mock_handle.assert_called_with( "blah.json", stdout=out, settings=None, pythonpath=None, verbosity=1, traceback=False, addrport="", no_color=False, use_ipv6=False, skip_checks=True, interactive=True, force_color=False, ) @mock.patch("django.db.connection.creation.create_test_db", return_value="test_db") @mock.patch.object(LoaddataCommand, "handle", return_value="") @mock.patch.object(RunserverCommand, "handle", return_value="") def test_params_to_runserver( self, mock_runserver_handle, mock_loaddata_handle, mock_create_test_db ): call_command("testserver", "blah.json") mock_runserver_handle.assert_called_with( addrport="", force_color=False, insecure_serving=False, no_color=False, pythonpath=None, settings=None, shutdown_message=( "\nServer stopped.\nNote that the test database, 'test_db', " "has not been deleted. You can explore it on your own." ), skip_checks=True, traceback=False, use_ipv6=False, use_reloader=False, use_static_handler=True, use_threading=connection.features.test_db_allows_multiple_connections, verbosity=1, ) ########################################################################## # COMMAND PROCESSING TESTS # user-space commands are correctly handled - in particular, arguments to # the commands are correctly parsed and processed. ########################################################################## class ColorCommand(BaseCommand): requires_system_checks = [] def handle(self, *args, **options): self.stdout.write("Hello, world!", self.style.ERROR) self.stderr.write("Hello, world!", self.style.ERROR) class CommandTypes(AdminScriptTestCase): "Tests for the various types of base command types that can be defined." def setUp(self): super().setUp() self.write_settings("settings.py") def test_version(self): "version is handled as a special case" args = ["version"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, get_version()) def test_version_alternative(self): "--version is equivalent to version" args1, args2 = ["version"], ["--version"] # It's possible one outputs on stderr and the other on stdout, hence the set self.assertEqual(set(self.run_manage(args1)), set(self.run_manage(args2))) def test_help(self): "help is handled as a special case" args = ["help"] out, err = self.run_manage(args) self.assertOutput( out, "Type 'manage.py help <subcommand>' for help on a specific subcommand." ) self.assertOutput(out, "[django]") self.assertOutput(out, "startapp") self.assertOutput(out, "startproject") def test_help_commands(self): "help --commands shows the list of all available commands" args = ["help", "--commands"] out, err = self.run_manage(args) self.assertNotInOutput(out, "usage:") self.assertNotInOutput(out, "Options:") self.assertNotInOutput(out, "[django]") self.assertOutput(out, "startapp") self.assertOutput(out, "startproject") self.assertNotInOutput(out, "\n\n") def test_help_alternative(self): "--help is equivalent to help" args1, args2 = ["help"], ["--help"] self.assertEqual(self.run_manage(args1), self.run_manage(args2)) def test_help_short_altert(self): "-h is handled as a short form of --help" args1, args2 = ["--help"], ["-h"] self.assertEqual(self.run_manage(args1), self.run_manage(args2)) def test_specific_help(self): "--help can be used on a specific command" args = ["check", "--help"] out, err = self.run_manage(args) self.assertNoOutput(err) # Command-specific options like --tag appear before options common to # all commands like --version. tag_location = out.find("--tag") version_location = out.find("--version") self.assertNotEqual(tag_location, -1) self.assertNotEqual(version_location, -1) self.assertLess(tag_location, version_location) self.assertOutput( out, "Checks the entire Django project for potential problems." ) def test_help_default_options_with_custom_arguments(self): args = ["base_command", "--help"] out, err = self.run_manage(args) self.assertNoOutput(err) expected_options = [ "-h", "--option_a OPTION_A", "--option_b OPTION_B", "--option_c OPTION_C", "--version", "-v {0,1,2,3}", "--settings SETTINGS", "--pythonpath PYTHONPATH", "--traceback", "--no-color", "--force-color", "args ...", ] for option in expected_options: self.assertOutput(out, f"[{option}]") self.assertOutput(out, "--option_a OPTION_A, -a OPTION_A") self.assertOutput(out, "--option_b OPTION_B, -b OPTION_B") self.assertOutput(out, "--option_c OPTION_C, -c OPTION_C") self.assertOutput(out, "-v {0,1,2,3}, --verbosity {0,1,2,3}") def test_color_style(self): style = color.no_style() self.assertEqual(style.ERROR("Hello, world!"), "Hello, world!") style = color.make_style("nocolor") self.assertEqual(style.ERROR("Hello, world!"), "Hello, world!") style = color.make_style("dark") self.assertIn("Hello, world!", style.ERROR("Hello, world!")) self.assertNotEqual(style.ERROR("Hello, world!"), "Hello, world!") # Default palette has color. style = color.make_style("") self.assertIn("Hello, world!", style.ERROR("Hello, world!")) self.assertNotEqual(style.ERROR("Hello, world!"), "Hello, world!") def test_command_color(self): out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err) call_command(command) if color.supports_color(): self.assertIn("Hello, world!\n", out.getvalue()) self.assertIn("Hello, world!\n", err.getvalue()) self.assertNotEqual(out.getvalue(), "Hello, world!\n") self.assertNotEqual(err.getvalue(), "Hello, world!\n") else: self.assertEqual(out.getvalue(), "Hello, world!\n") self.assertEqual(err.getvalue(), "Hello, world!\n") def test_command_no_color(self): "--no-color prevent colorization of the output" out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err, no_color=True) call_command(command) self.assertEqual(out.getvalue(), "Hello, world!\n") self.assertEqual(err.getvalue(), "Hello, world!\n") out = StringIO() err = StringIO() command = ColorCommand(stdout=out, stderr=err) call_command(command, no_color=True) self.assertEqual(out.getvalue(), "Hello, world!\n") self.assertEqual(err.getvalue(), "Hello, world!\n") def test_force_color_execute(self): out = StringIO() err = StringIO() with mock.patch.object(sys.stdout, "isatty", lambda: False): command = ColorCommand(stdout=out, stderr=err) call_command(command, force_color=True) self.assertEqual(out.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") self.assertEqual(err.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") def test_force_color_command_init(self): out = StringIO() err = StringIO() with mock.patch.object(sys.stdout, "isatty", lambda: False): command = ColorCommand(stdout=out, stderr=err, force_color=True) call_command(command) self.assertEqual(out.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") self.assertEqual(err.getvalue(), "\x1b[31;1mHello, world!\n\x1b[0m") def test_no_color_force_color_mutually_exclusive_execute(self): msg = "The --no-color and --force-color options can't be used together." with self.assertRaisesMessage(CommandError, msg): call_command(BaseCommand(), no_color=True, force_color=True) def test_no_color_force_color_mutually_exclusive_command_init(self): msg = "'no_color' and 'force_color' can't be used together." with self.assertRaisesMessage(CommandError, msg): call_command(BaseCommand(no_color=True, force_color=True)) def test_custom_stdout(self): class Command(BaseCommand): requires_system_checks = [] def handle(self, *args, **options): self.stdout.write("Hello, World!") out = StringIO() command = Command(stdout=out) call_command(command) self.assertEqual(out.getvalue(), "Hello, World!\n") out.truncate(0) new_out = StringIO() call_command(command, stdout=new_out) self.assertEqual(out.getvalue(), "") self.assertEqual(new_out.getvalue(), "Hello, World!\n") def test_custom_stderr(self): class Command(BaseCommand): requires_system_checks = [] def handle(self, *args, **options): self.stderr.write("Hello, World!") err = StringIO() command = Command(stderr=err) call_command(command) self.assertEqual(err.getvalue(), "Hello, World!\n") err.truncate(0) new_err = StringIO() call_command(command, stderr=new_err) self.assertEqual(err.getvalue(), "") self.assertEqual(new_err.getvalue(), "Hello, World!\n") def test_base_command(self): "User BaseCommands can execute when a label is provided" args = ["base_command", "testlabel"] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels) def test_base_command_no_label(self): "User BaseCommands can execute when no labels are provided" args = ["base_command"] expected_labels = "()" self._test_base_command(args, expected_labels) def test_base_command_multiple_label(self): "User BaseCommands can execute when no labels are provided" args = ["base_command", "testlabel", "anotherlabel"] expected_labels = "('testlabel', 'anotherlabel')" self._test_base_command(args, expected_labels) def test_base_command_with_option(self): "User BaseCommands can execute with options when a label is provided" args = ["base_command", "testlabel", "--option_a=x"] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels, option_a="'x'") def test_base_command_with_options(self): "User BaseCommands can execute with multiple options when a label is provided" args = ["base_command", "testlabel", "-a", "x", "--option_b=y"] expected_labels = "('testlabel',)" self._test_base_command(args, expected_labels, option_a="'x'", option_b="'y'") def test_base_command_with_wrong_option(self): "User BaseCommands outputs command usage when wrong option is specified" args = ["base_command", "--invalid"] out, err = self.run_manage(args) self.assertNoOutput(out) self.assertOutput(err, "usage: manage.py base_command") self.assertOutput(err, "error: unrecognized arguments: --invalid") def _test_base_command(self, args, labels, option_a="'1'", option_b="'2'"): out, err = self.run_manage(args) expected_out = ( "EXECUTE:BaseCommand labels=%s, " "options=[('force_color', False), ('no_color', False), " "('option_a', %s), ('option_b', %s), ('option_c', '3'), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]" ) % (labels, option_a, option_b) self.assertNoOutput(err) self.assertOutput(out, expected_out) def test_base_run_from_argv(self): """ Test run_from_argv properly terminates even with custom execute() (#19665) Also test proper traceback display. """ err = StringIO() command = BaseCommand(stderr=err) def raise_command_error(*args, **kwargs): raise CommandError("Custom error") command.execute = lambda args: args # This will trigger TypeError # If the Exception is not CommandError it should always # raise the original exception. with self.assertRaises(TypeError): command.run_from_argv(["", ""]) # If the Exception is CommandError and --traceback is not present # this command should raise a SystemExit and don't print any # traceback to the stderr. command.execute = raise_command_error err.truncate(0) with self.assertRaises(SystemExit): command.run_from_argv(["", ""]) err_message = err.getvalue() self.assertNotIn("Traceback", err_message) self.assertIn("CommandError", err_message) # If the Exception is CommandError and --traceback is present # this command should raise the original CommandError as if it # were not a CommandError. err.truncate(0) with self.assertRaises(CommandError): command.run_from_argv(["", "", "--traceback"]) def test_run_from_argv_non_ascii_error(self): """ Non-ASCII message of CommandError does not raise any UnicodeDecodeError in run_from_argv. """ def raise_command_error(*args, **kwargs): raise CommandError("Erreur personnalisée") command = BaseCommand(stderr=StringIO()) command.execute = raise_command_error with self.assertRaises(SystemExit): command.run_from_argv(["", ""]) def test_run_from_argv_closes_connections(self): """ A command called from the command line should close connections after being executed (#21255). """ command = BaseCommand() command.check = lambda: [] command.handle = lambda *args, **kwargs: args with mock.patch("django.core.management.base.connections") as mock_connections: command.run_from_argv(["", ""]) # Test connections have been closed self.assertTrue(mock_connections.close_all.called) def test_noargs(self): "NoArg Commands can be executed" args = ["noargs_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE: noargs_command options=[('force_color', False), " "('no_color', False), ('pythonpath', None), ('settings', None), " "('traceback', False), ('verbosity', 1)]", ) def test_noargs_with_args(self): "NoArg Commands raise an error if an argument is provided" args = ["noargs_command", "argument"] out, err = self.run_manage(args) self.assertOutput(err, "error: unrecognized arguments: argument") def test_app_command(self): "User AppCommands can execute when a single app name is provided" args = ["app_command", "auth"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]", ) def test_app_command_no_apps(self): "User AppCommands raise an error when no app name is provided" args = ["app_command"] out, err = self.run_manage(args) self.assertOutput(err, "error: Enter at least one application label.") def test_app_command_multiple_apps(self): "User AppCommands raise an error when multiple app names are provided" args = ["app_command", "auth", "contenttypes"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:AppCommand name=django.contrib.auth, options=") self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]", ) self.assertOutput( out, "EXECUTE:AppCommand name=django.contrib.contenttypes, options=" ) self.assertOutput( out, ", options=[('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), ('traceback', False), " "('verbosity', 1)]", ) def test_app_command_invalid_app_label(self): "User AppCommands can execute when a single app name is provided" args = ["app_command", "NOT_AN_APP"] out, err = self.run_manage(args) self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.") def test_app_command_some_invalid_app_labels(self): "User AppCommands can execute when some of the provided app names are invalid" args = ["app_command", "auth", "NOT_AN_APP"] out, err = self.run_manage(args) self.assertOutput(err, "No installed app with label 'NOT_AN_APP'.") def test_label_command(self): "User LabelCommands can execute when a label is provided" args = ["label_command", "testlabel"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:LabelCommand label=testlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), ('settings', " "None), ('traceback', False), ('verbosity', 1)]", ) def test_label_command_no_label(self): "User LabelCommands raise an error if no label is provided" args = ["label_command"] out, err = self.run_manage(args) self.assertOutput(err, "Enter at least one label") def test_label_command_multiple_label(self): "User LabelCommands are executed multiple times if multiple labels are provided" args = ["label_command", "testlabel", "anotherlabel"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:LabelCommand label=testlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), " "('settings', None), ('traceback', False), ('verbosity', 1)]", ) self.assertOutput( out, "EXECUTE:LabelCommand label=anotherlabel, options=[('force_color', " "False), ('no_color', False), ('pythonpath', None), " "('settings', None), ('traceback', False), ('verbosity', 1)]", ) def test_suppress_base_options_command_help(self): args = ["suppress_base_options_command", "--help"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "Test suppress base options command.") self.assertNotInOutput(out, "input file") self.assertOutput(out, "-h, --help") self.assertNotInOutput(out, "--version") self.assertNotInOutput(out, "--verbosity") self.assertNotInOutput(out, "-v {0,1,2,3}") self.assertNotInOutput(out, "--settings") self.assertNotInOutput(out, "--pythonpath") self.assertNotInOutput(out, "--traceback") self.assertNotInOutput(out, "--no-color") self.assertNotInOutput(out, "--force-color") def test_suppress_base_options_command_defaults(self): args = ["suppress_base_options_command"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:SuppressBaseOptionsCommand options=[('file', None), " "('force_color', False), ('no_color', False), " "('pythonpath', None), ('settings', None), " "('traceback', False), ('verbosity', 1)]", ) class Discovery(SimpleTestCase): def test_precedence(self): """ Apps listed first in INSTALLED_APPS have precedence. """ with self.settings( INSTALLED_APPS=[ "admin_scripts.complex_app", "admin_scripts.simple_app", "django.contrib.auth", "django.contrib.contenttypes", ] ): out = StringIO() call_command("duplicate", stdout=out) self.assertEqual(out.getvalue().strip(), "complex_app") with self.settings( INSTALLED_APPS=[ "admin_scripts.simple_app", "admin_scripts.complex_app", "django.contrib.auth", "django.contrib.contenttypes", ] ): out = StringIO() call_command("duplicate", stdout=out) self.assertEqual(out.getvalue().strip(), "simple_app") class ArgumentOrder(AdminScriptTestCase): """Tests for 2-stage argument parsing scheme. django-admin command arguments are parsed in 2 parts; the core arguments (--settings, --traceback and --pythonpath) are parsed using a basic parser, ignoring any unknown options. Then the full settings are passed to the command parser, which extracts commands of interest to the individual command. """ def setUp(self): super().setUp() self.write_settings( "settings.py", apps=["django.contrib.auth", "django.contrib.contenttypes"] ) self.write_settings("alternate_settings.py") def test_setting_then_option(self): """Options passed after settings are correctly handled.""" args = [ "base_command", "testlabel", "--settings=alternate_settings", "--option_a=x", ] self._test(args) def test_setting_then_short_option(self): """Short options passed after settings are correctly handled.""" args = ["base_command", "testlabel", "--settings=alternate_settings", "-a", "x"] self._test(args) def test_option_then_setting(self): """Options passed before settings are correctly handled.""" args = [ "base_command", "testlabel", "--option_a=x", "--settings=alternate_settings", ] self._test(args) def test_short_option_then_setting(self): """Short options passed before settings are correctly handled.""" args = ["base_command", "testlabel", "-a", "x", "--settings=alternate_settings"] self._test(args) def test_option_then_setting_then_option(self): """Options are correctly handled when they are passed before and after a setting.""" args = [ "base_command", "testlabel", "--option_a=x", "--settings=alternate_settings", "--option_b=y", ] self._test(args, option_b="'y'") def _test(self, args, option_b="'2'"): out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput( out, "EXECUTE:BaseCommand labels=('testlabel',), options=[" "('force_color', False), ('no_color', False), ('option_a', 'x'), " "('option_b', %s), ('option_c', '3'), ('pythonpath', None), " "('settings', 'alternate_settings'), ('traceback', False), " "('verbosity', 1)]" % option_b, ) class ExecuteFromCommandLine(SimpleTestCase): def test_program_name_from_argv(self): """ Program name is computed from the execute_from_command_line()'s argv argument, not sys.argv. """ args = ["help", "shell"] with captured_stdout() as out, captured_stderr() as err: with mock.patch("sys.argv", [None] + args): execute_from_command_line(["django-admin"] + args) self.assertIn("usage: django-admin shell", out.getvalue()) self.assertEqual(err.getvalue(), "") @override_settings(ROOT_URLCONF="admin_scripts.urls") class StartProject(LiveServerTestCase, AdminScriptTestCase): available_apps = [ "admin_scripts", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", ] def test_wrong_args(self): """ Passing the wrong kinds of arguments outputs an error and prints usage. """ out, err = self.run_django_admin(["startproject"]) self.assertNoOutput(out) self.assertOutput(err, "usage:") self.assertOutput(err, "You must provide a project name.") def test_simple_project(self): "Make sure the startproject management command creates a project" args = ["startproject", "testproject"] testproject_dir = os.path.join(self.test_dir, "testproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) # running again.. out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput( err, "CommandError: 'testproject' conflicts with the name of an " "existing Python module and cannot be used as a project name. " "Please try another name.", ) def test_invalid_project_name(self): "Make sure the startproject management command validates a project name" for bad_name in ("7testproject", "../testproject"): with self.subTest(project_name=bad_name): args = ["startproject", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "Error: '%s' is not a valid project name. Please make " "sure the name is a valid identifier." % bad_name, ) self.assertFalse(os.path.exists(testproject_dir)) def test_importable_project_name(self): """ startproject validates that project name doesn't clash with existing Python modules. """ bad_name = "os" args = ["startproject", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing " "Python module and cannot be used as a project name. Please try " "another name.", ) self.assertFalse(os.path.exists(testproject_dir)) def test_simple_project_different_directory(self): """ The startproject management command creates a project in a specific directory. """ args = ["startproject", "testproject", "othertestproject"] testproject_dir = os.path.join(self.test_dir, "othertestproject") os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "manage.py"))) # running again.. out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput( err, "already exists. Overlaying a project into an existing directory " "won't replace conflicting files.", ) def test_custom_project_template(self): """ The startproject management command is able to use a different project template. """ template_path = os.path.join(custom_templates_dir, "project_template") args = ["startproject", "--template", template_path, "customtestproject"] testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir"))) def test_template_dir_with_trailing_slash(self): "Ticket 17475: Template dir passed has a trailing path separator" template_path = os.path.join(custom_templates_dir, "project_template" + os.sep) args = ["startproject", "--template", template_path, "customtestproject"] testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir"))) def test_custom_project_template_from_tarball_by_path(self): """ The startproject management command is able to use a different project template from a tarball. """ template_path = os.path.join(custom_templates_dir, "project_template.tgz") args = ["startproject", "--template", template_path, "tarballtestproject"] testproject_dir = os.path.join(self.test_dir, "tarballtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_custom_project_template_from_tarball_to_alternative_location(self): """ Startproject can use a project template from a tarball and create it in a specified location. """ template_path = os.path.join(custom_templates_dir, "project_template.tgz") args = [ "startproject", "--template", template_path, "tarballtestproject", "altlocation", ] testproject_dir = os.path.join(self.test_dir, "altlocation") os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_custom_project_template_from_tarball_by_url(self): """ The startproject management command is able to use a different project template from a tarball via a URL. """ template_url = "%s/custom_templates/project_template.tgz" % self.live_server_url args = ["startproject", "--template", template_url, "urltestproject"] testproject_dir = os.path.join(self.test_dir, "urltestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_custom_project_template_from_tarball_by_url_django_user_agent(self): user_agent = None def serve_template(request, *args, **kwargs): nonlocal user_agent user_agent = request.headers["User-Agent"] return serve(request, *args, **kwargs) old_urlpatterns = urls.urlpatterns[:] try: urls.urlpatterns += [ path( "user_agent_check/<path:path>", serve_template, {"document_root": os.path.join(urls.here, "custom_templates")}, ), ] template_url = ( f"{self.live_server_url}/user_agent_check/project_template.tgz" ) args = ["startproject", "--template", template_url, "urltestproject"] _, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertIn("Django/%s" % get_version(), user_agent) finally: urls.urlpatterns = old_urlpatterns def test_project_template_tarball_url(self): """ " Startproject management command handles project template tar/zip balls from non-canonical urls. """ template_url = ( "%s/custom_templates/project_template.tgz/" % self.live_server_url ) args = ["startproject", "--template", template_url, "urltestproject"] testproject_dir = os.path.join(self.test_dir, "urltestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "run.py"))) def test_file_without_extension(self): "Make sure the startproject management command is able to render custom files" template_path = os.path.join(custom_templates_dir, "project_template") args = [ "startproject", "--template", template_path, "customtestproject", "-e", "txt", "-n", "Procfile", ] testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) self.assertTrue(os.path.exists(os.path.join(testproject_dir, "additional_dir"))) base_path = os.path.join(testproject_dir, "additional_dir") for f in ("Procfile", "additional_file.py", "requirements.txt"): self.assertTrue(os.path.exists(os.path.join(base_path, f))) with open(os.path.join(base_path, f)) as fh: self.assertEqual( fh.read().strip(), "# some file for customtestproject test project" ) def test_custom_project_template_context_variables(self): "Make sure template context variables are rendered with proper values" template_path = os.path.join(custom_templates_dir, "project_template") args = [ "startproject", "--template", template_path, "another_project", "project_dir", ] testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) out, err = self.run_django_admin(args) self.assertNoOutput(err) test_manage_py = os.path.join(testproject_dir, "manage.py") with open(test_manage_py) as fp: content = fp.read() self.assertIn('project_name = "another_project"', content) self.assertIn('project_directory = "%s"' % testproject_dir, content) def test_no_escaping_of_project_variables(self): "Make sure template context variables are not html escaped" # We're using a custom command so we need the alternate settings self.write_settings("alternate_settings.py") template_path = os.path.join(custom_templates_dir, "project_template") args = [ "custom_startproject", "--template", template_path, "another_project", "project_dir", "--extra", "<&>", "--settings=alternate_settings", ] testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) out, err = self.run_manage(args) self.assertNoOutput(err) test_manage_py = os.path.join(testproject_dir, "additional_dir", "extra.py") with open(test_manage_py) as fp: content = fp.read() self.assertIn("<&>", content) def test_custom_project_destination_missing(self): """ Make sure an exception is raised when the provided destination directory doesn't exist """ template_path = os.path.join(custom_templates_dir, "project_template") args = [ "startproject", "--template", template_path, "yet_another_project", "project_dir2", ] testproject_dir = os.path.join(self.test_dir, "project_dir2") out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput( err, "Destination directory '%s' does not exist, please create it first." % testproject_dir, ) self.assertFalse(os.path.exists(testproject_dir)) def test_custom_project_template_with_non_ascii_templates(self): """ The startproject management command is able to render templates with non-ASCII content. """ template_path = os.path.join(custom_templates_dir, "project_template") args = [ "startproject", "--template", template_path, "--extension=txt", "customtestproject", ] testproject_dir = os.path.join(self.test_dir, "customtestproject") out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertTrue(os.path.isdir(testproject_dir)) path = os.path.join(testproject_dir, "ticket-18091-non-ascii-template.txt") with open(path, encoding="utf-8") as f: self.assertEqual( f.read().splitlines(False), ["Some non-ASCII text for testing ticket #18091:", "üäö €"], ) def test_custom_project_template_hidden_directory_default_excluded(self): """Hidden directories are excluded by default.""" template_path = os.path.join(custom_templates_dir, "project_template") args = [ "startproject", "--template", template_path, "custom_project_template_hidden_directories", "project_dir", ] testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) _, err = self.run_django_admin(args) self.assertNoOutput(err) hidden_dir = os.path.join(testproject_dir, ".hidden") self.assertIs(os.path.exists(hidden_dir), False) def test_custom_project_template_hidden_directory_included(self): """ Template context variables in hidden directories are rendered, if not excluded. """ template_path = os.path.join(custom_templates_dir, "project_template") project_name = "custom_project_template_hidden_directories_included" args = [ "startproject", "--template", template_path, project_name, "project_dir", "--exclude", ] testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) _, err = self.run_django_admin(args) self.assertNoOutput(err) render_py_path = os.path.join(testproject_dir, ".hidden", "render.py") with open(render_py_path) as fp: self.assertIn( f"# The {project_name} should be rendered.", fp.read(), ) def test_custom_project_template_exclude_directory(self): """ Excluded directories (in addition to .git and __pycache__) are not included in the project. """ template_path = os.path.join(custom_templates_dir, "project_template") project_name = "custom_project_with_excluded_directories" args = [ "startproject", "--template", template_path, project_name, "project_dir", "--exclude", "additional_dir", "-x", ".hidden", ] testproject_dir = os.path.join(self.test_dir, "project_dir") os.mkdir(testproject_dir) _, err = self.run_django_admin(args) self.assertNoOutput(err) excluded_directories = [ ".hidden", "additional_dir", ".git", "__pycache__", ] for directory in excluded_directories: self.assertIs( os.path.exists(os.path.join(testproject_dir, directory)), False, ) not_excluded = os.path.join(testproject_dir, project_name) self.assertIs(os.path.exists(not_excluded), True) @unittest.skipIf( sys.platform == "win32", "Windows only partially supports umasks and chmod.", ) @unittest.skipUnless(PY39, "subprocess.run()'s umask was added in Python 3.9.") def test_honor_umask(self): _, err = self.run_django_admin(["startproject", "testproject"], umask=0o077) self.assertNoOutput(err) testproject_dir = os.path.join(self.test_dir, "testproject") self.assertIs(os.path.isdir(testproject_dir), True) tests = [ (["manage.py"], 0o700), (["testproject"], 0o700), (["testproject", "settings.py"], 0o600), ] for paths, expected_mode in tests: file_path = os.path.join(testproject_dir, *paths) with self.subTest(paths[-1]): self.assertEqual( stat.S_IMODE(os.stat(file_path).st_mode), expected_mode, ) class StartApp(AdminScriptTestCase): def test_invalid_name(self): """startapp validates that app name is a valid Python identifier.""" for bad_name in ("7testproject", "../testproject"): with self.subTest(app_name=bad_name): args = ["startapp", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: '{}' is not a valid app name. Please make " "sure the name is a valid identifier.".format(bad_name), ) self.assertFalse(os.path.exists(testproject_dir)) def test_importable_name(self): """ startapp validates that app name doesn't clash with existing Python modules. """ bad_name = "os" args = ["startapp", bad_name] testproject_dir = os.path.join(self.test_dir, bad_name) out, err = self.run_django_admin(args) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing " "Python module and cannot be used as an app name. Please try " "another name.", ) self.assertFalse(os.path.exists(testproject_dir)) def test_invalid_target_name(self): for bad_target in ( "invalid.dir_name", "7invalid_dir_name", ".invalid_dir_name", ): with self.subTest(bad_target): _, err = self.run_django_admin(["startapp", "app", bad_target]) self.assertOutput( err, "CommandError: '%s' is not a valid app directory. Please " "make sure the directory is a valid identifier." % bad_target, ) def test_importable_target_name(self): _, err = self.run_django_admin(["startapp", "app", "os"]) self.assertOutput( err, "CommandError: 'os' conflicts with the name of an existing Python " "module and cannot be used as an app directory. Please try " "another directory.", ) def test_trailing_slash_in_target_app_directory_name(self): app_dir = os.path.join(self.test_dir, "apps", "app1") os.makedirs(app_dir) _, err = self.run_django_admin( ["startapp", "app", os.path.join("apps", "app1", "")] ) self.assertNoOutput(err) self.assertIs(os.path.exists(os.path.join(app_dir, "apps.py")), True) def test_overlaying_app(self): # Use a subdirectory so it is outside the PYTHONPATH. os.makedirs(os.path.join(self.test_dir, "apps/app1")) self.run_django_admin(["startapp", "app1", "apps/app1"]) out, err = self.run_django_admin(["startapp", "app2", "apps/app1"]) self.assertOutput( err, "already exists. Overlaying an app into an existing directory " "won't replace conflicting files.", ) def test_template(self): out, err = self.run_django_admin(["startapp", "new_app"]) self.assertNoOutput(err) app_path = os.path.join(self.test_dir, "new_app") self.assertIs(os.path.exists(app_path), True) with open(os.path.join(app_path, "apps.py")) as f: content = f.read() self.assertIn("class NewAppConfig(AppConfig)", content) if HAS_BLACK: test_str = 'default_auto_field = "django.db.models.BigAutoField"' else: test_str = "default_auto_field = 'django.db.models.BigAutoField'" self.assertIn(test_str, content) self.assertIn( 'name = "new_app"' if HAS_BLACK else "name = 'new_app'", content, ) class DiffSettings(AdminScriptTestCase): """Tests for diffsettings management command.""" def test_basic(self): """Runs without error and emits settings diff.""" self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) args = ["diffsettings", "--settings=settings_to_diff"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "FOO = 'bar' ###") # Attributes from django.conf.Settings don't appear. self.assertNotInOutput(out, "is_overridden = ") def test_settings_configured(self): out, err = self.run_manage( ["diffsettings"], manage_py="configured_settings_manage.py" ) self.assertNoOutput(err) self.assertOutput(out, "CUSTOM = 1 ###\nDEBUG = True") # Attributes from django.conf.UserSettingsHolder don't appear. self.assertNotInOutput(out, "default_settings = ") def test_dynamic_settings_configured(self): # Custom default settings appear. out, err = self.run_manage( ["diffsettings"], manage_py="configured_dynamic_settings_manage.py" ) self.assertNoOutput(err) self.assertOutput(out, "FOO = 'bar' ###") def test_all(self): """The all option also shows settings with the default value.""" self.write_settings("settings_to_diff.py", sdict={"STATIC_URL": "None"}) args = ["diffsettings", "--settings=settings_to_diff", "--all"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "### STATIC_URL = None") def test_custom_default(self): """ The --default option specifies an alternate settings module for comparison. """ self.write_settings( "settings_default.py", sdict={"FOO": '"foo"', "BAR": '"bar1"'} ) self.write_settings( "settings_to_diff.py", sdict={"FOO": '"foo"', "BAR": '"bar2"'} ) out, err = self.run_manage( [ "diffsettings", "--settings=settings_to_diff", "--default=settings_default", ] ) self.assertNoOutput(err) self.assertNotInOutput(out, "FOO") self.assertOutput(out, "BAR = 'bar2'") def test_unified(self): """--output=unified emits settings diff in unified mode.""" self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) args = ["diffsettings", "--settings=settings_to_diff", "--output=unified"] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, "+ FOO = 'bar'") self.assertOutput(out, "- SECRET_KEY = ''") self.assertOutput(out, "+ SECRET_KEY = 'django_tests_secret_key'") self.assertNotInOutput(out, " APPEND_SLASH = True") def test_unified_all(self): """ --output=unified --all emits settings diff in unified mode and includes settings with the default value. """ self.write_settings("settings_to_diff.py", sdict={"FOO": '"bar"'}) args = [ "diffsettings", "--settings=settings_to_diff", "--output=unified", "--all", ] out, err = self.run_manage(args) self.assertNoOutput(err) self.assertOutput(out, " APPEND_SLASH = True") self.assertOutput(out, "+ FOO = 'bar'") self.assertOutput(out, "- SECRET_KEY = ''") class Dumpdata(AdminScriptTestCase): """Tests for dumpdata management command.""" def setUp(self): super().setUp() self.write_settings("settings.py") def test_pks_parsing(self): """Regression for #20509 Test would raise an exception rather than printing an error message. """ args = ["dumpdata", "--pks=1"] out, err = self.run_manage(args) self.assertOutput(err, "You can only use --pks option with one model") self.assertNoOutput(out) class MainModule(AdminScriptTestCase): """python -m django works like django-admin.""" def test_program_name_in_help(self): out, err = self.run_test(["-m", "django", "help"]) self.assertOutput( out, "Type 'python -m django help <subcommand>' for help on a specific " "subcommand.", ) class DjangoAdminSuggestions(AdminScriptTestCase): def setUp(self): super().setUp() self.write_settings("settings.py") def test_suggestions(self): args = ["rnserver", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'rnserver'. Did you mean runserver?") def test_no_suggestions(self): args = ["abcdef", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(out) self.assertNotInOutput(err, "Did you mean")
e99618db5e8f7862f33065f088b1b31cbb442b187334d2fd7c1aae1beb45d690
#!/usr/bin/env python import sys from django.conf import settings from django.core.management import execute_from_command_line if __name__ == "__main__": settings.configure(DEBUG=True, CUSTOM=1) execute_from_command_line(sys.argv)
a122b5a3086afb026cec26e99726a4cb3219cbd363070ae49b7cceb35371496c
import os from django.urls import path from django.views.static import serve here = os.path.dirname(__file__) urlpatterns = [ path( "custom_templates/<path:path>", serve, {"document_root": os.path.join(here, "custom_templates")}, ), ]
4661ccdfa5e02ff5a8d2ea6a7955e7ce0a295d99602163b9b247583ff4dfdfcb
#!/usr/bin/env python import sys from django.conf import global_settings, settings from django.core.management import execute_from_command_line class Settings: def __getattr__(self, name): if name == "FOO": return "bar" return getattr(global_settings, name) def __dir__(self): return super().__dir__() + dir(global_settings) + ["FOO"] if __name__ == "__main__": settings.configure(Settings()) execute_from_command_line(sys.argv)
2e961cb691ca4c43855c16d72e015e450b39a1b5b9caca79a7926f720728a14c
import datetime from django.test import TestCase from .models import Thing class ReservedNameTests(TestCase): def generate(self): day1 = datetime.date(2005, 1, 1) Thing.objects.create( when="a", join="b", like="c", drop="d", alter="e", having="f", where=day1, has_hyphen="h", ) day2 = datetime.date(2006, 2, 2) Thing.objects.create( when="h", join="i", like="j", drop="k", alter="l", having="m", where=day2, ) def test_simple(self): day1 = datetime.date(2005, 1, 1) t = Thing.objects.create( when="a", join="b", like="c", drop="d", alter="e", having="f", where=day1, has_hyphen="h", ) self.assertEqual(t.when, "a") day2 = datetime.date(2006, 2, 2) u = Thing.objects.create( when="h", join="i", like="j", drop="k", alter="l", having="m", where=day2, ) self.assertEqual(u.when, "h") def test_order_by(self): self.generate() things = [t.when for t in Thing.objects.order_by("when")] self.assertEqual(things, ["a", "h"]) def test_fields(self): self.generate() v = Thing.objects.get(pk="a") self.assertEqual(v.join, "b") self.assertEqual(v.where, datetime.date(year=2005, month=1, day=1)) def test_dates(self): self.generate() resp = Thing.objects.dates("where", "year") self.assertEqual( list(resp), [ datetime.date(2005, 1, 1), datetime.date(2006, 1, 1), ], ) def test_month_filter(self): self.generate() self.assertEqual(Thing.objects.filter(where__month=1)[0].when, "a")
b5ce6c6540ef106cebda7d6ee1baa651ed042fbf9bb84ae343b89a737697206c
""" Using SQL reserved names Need to use a reserved SQL name as a column name or table name? Need to include a hyphen in a column or table name? No problem. Django quotes names appropriately behind the scenes, so your database won't complain about reserved-name usage. """ from django.db import models class Thing(models.Model): when = models.CharField(max_length=1, primary_key=True) join = models.CharField(max_length=1) like = models.CharField(max_length=1) drop = models.CharField(max_length=1) alter = models.CharField(max_length=1) having = models.CharField(max_length=1) where = models.DateField(max_length=1) has_hyphen = models.CharField(max_length=1, db_column="has-hyphen") class Meta: db_table = "select" def __str__(self): return self.when
03bc34576075c1e9c7186609925230e6136c31d56a01c59b6b7e3296bc923368
from django.contrib import admin from django.test import SimpleTestCase class AdminAutoDiscoverTests(SimpleTestCase): """ Test for bug #8245 - don't raise an AlreadyRegistered exception when using autodiscover() and an admin.py module contains an error. """ def test_double_call_autodiscover(self): # The first time autodiscover is called, we should get our real error. with self.assertRaisesMessage(Exception, "Bad admin module"): admin.autodiscover() # Calling autodiscover again should raise the very same error it did # the first time, not an AlreadyRegistered error. with self.assertRaisesMessage(Exception, "Bad admin module"): admin.autodiscover()
aa72cf294c0be316f9630d236947e246b5695e09b1d2d0cf4471ff8a590f985b
from django.conf import settings from django.contrib.redirects.middleware import RedirectFallbackMiddleware from django.contrib.redirects.models import Redirect from django.contrib.sites.models import Site from django.core.exceptions import ImproperlyConfigured from django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect from django.test import TestCase, modify_settings, override_settings @modify_settings( MIDDLEWARE={ "append": "django.contrib.redirects.middleware.RedirectFallbackMiddleware" } ) @override_settings(APPEND_SLASH=False, ROOT_URLCONF="redirects_tests.urls", SITE_ID=1) class RedirectTests(TestCase): @classmethod def setUpTestData(cls): cls.site = Site.objects.get(pk=settings.SITE_ID) def test_model(self): r1 = Redirect.objects.create( site=self.site, old_path="/initial", new_path="/new_target" ) self.assertEqual(str(r1), "/initial ---> /new_target") def test_redirect(self): Redirect.objects.create( site=self.site, old_path="/initial", new_path="/new_target" ) response = self.client.get("/initial") self.assertRedirects( response, "/new_target", status_code=301, target_status_code=404 ) @override_settings(APPEND_SLASH=True) def test_redirect_with_append_slash(self): Redirect.objects.create( site=self.site, old_path="/initial/", new_path="/new_target/" ) response = self.client.get("/initial") self.assertRedirects( response, "/new_target/", status_code=301, target_status_code=404 ) @override_settings(APPEND_SLASH=True) def test_redirect_with_append_slash_and_query_string(self): Redirect.objects.create( site=self.site, old_path="/initial/?foo", new_path="/new_target/" ) response = self.client.get("/initial?foo") self.assertRedirects( response, "/new_target/", status_code=301, target_status_code=404 ) @override_settings(APPEND_SLASH=True) def test_redirect_not_found_with_append_slash(self): """ Exercise the second Redirect.DoesNotExist branch in RedirectFallbackMiddleware. """ response = self.client.get("/test") self.assertEqual(response.status_code, 404) def test_redirect_shortcircuits_non_404_response(self): """RedirectFallbackMiddleware short-circuits on non-404 requests.""" response = self.client.get("/") self.assertEqual(response.status_code, 200) def test_response_gone(self): """When the redirect target is '', return a 410""" Redirect.objects.create(site=self.site, old_path="/initial", new_path="") response = self.client.get("/initial") self.assertEqual(response.status_code, 410) @modify_settings(INSTALLED_APPS={"remove": "django.contrib.sites"}) def test_sites_not_installed(self): def get_response(request): return HttpResponse() msg = ( "You cannot use RedirectFallbackMiddleware when " "django.contrib.sites is not installed." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): RedirectFallbackMiddleware(get_response) class OverriddenRedirectFallbackMiddleware(RedirectFallbackMiddleware): # Use HTTP responses different from the defaults response_gone_class = HttpResponseForbidden response_redirect_class = HttpResponseRedirect @modify_settings( MIDDLEWARE={"append": "redirects_tests.tests.OverriddenRedirectFallbackMiddleware"} ) @override_settings(SITE_ID=1) class OverriddenRedirectMiddlewareTests(TestCase): @classmethod def setUpTestData(cls): cls.site = Site.objects.get(pk=settings.SITE_ID) def test_response_gone_class(self): Redirect.objects.create(site=self.site, old_path="/initial/", new_path="") response = self.client.get("/initial/") self.assertEqual(response.status_code, 403) def test_response_redirect_class(self): Redirect.objects.create( site=self.site, old_path="/initial/", new_path="/new_target/" ) response = self.client.get("/initial/") self.assertEqual(response.status_code, 302)
d48ac1dab06c8e4e92be67595b5a76f685621005a88c2be8d6811e563d22c41e
from django.http import HttpResponse from django.urls import path urlpatterns = [ path("", lambda req: HttpResponse("OK")), ]
5e69621fdd06cfaa2d959f4ebb32b11e848eedbdc7ef7d71bda9f4a6a0f9be87
from math import ceil from operator import attrgetter from django.core.exceptions import FieldDoesNotExist from django.db import ( IntegrityError, NotSupportedError, OperationalError, ProgrammingError, connection, ) from django.db.models import FileField, Value from django.db.models.functions import Lower from django.test import ( TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature, ) from .models import ( BigAutoFieldModel, Country, NoFields, NullableFields, Pizzeria, ProxyCountry, ProxyMultiCountry, ProxyMultiProxyCountry, ProxyProxyCountry, RelatedModel, Restaurant, SmallAutoFieldModel, State, TwoFields, UpsertConflict, ) class BulkCreateTests(TestCase): def setUp(self): self.data = [ Country(name="United States of America", iso_two_letter="US"), Country(name="The Netherlands", iso_two_letter="NL"), Country(name="Germany", iso_two_letter="DE"), Country(name="Czech Republic", iso_two_letter="CZ"), ] def test_simple(self): created = Country.objects.bulk_create(self.data) self.assertEqual(created, self.data) self.assertQuerysetEqual( Country.objects.order_by("-name"), [ "United States of America", "The Netherlands", "Germany", "Czech Republic", ], attrgetter("name"), ) created = Country.objects.bulk_create([]) self.assertEqual(created, []) self.assertEqual(Country.objects.count(), 4) @skipUnlessDBFeature("has_bulk_insert") def test_efficiency(self): with self.assertNumQueries(1): Country.objects.bulk_create(self.data) @skipUnlessDBFeature("has_bulk_insert") def test_long_non_ascii_text(self): """ Inserting non-ASCII values with a length in the range 2001 to 4000 characters, i.e. 4002 to 8000 bytes, must be set as a CLOB on Oracle (#22144). """ Country.objects.bulk_create([Country(description="Ж" * 3000)]) self.assertEqual(Country.objects.count(), 1) @skipUnlessDBFeature("has_bulk_insert") def test_long_and_short_text(self): Country.objects.bulk_create( [ Country(description="a" * 4001, iso_two_letter="A"), Country(description="a", iso_two_letter="B"), Country(description="Ж" * 2001, iso_two_letter="C"), Country(description="Ж", iso_two_letter="D"), ] ) self.assertEqual(Country.objects.count(), 4) def test_multi_table_inheritance_unsupported(self): expected_message = "Can't bulk create a multi-table inherited model" with self.assertRaisesMessage(ValueError, expected_message): Pizzeria.objects.bulk_create( [ Pizzeria(name="The Art of Pizza"), ] ) with self.assertRaisesMessage(ValueError, expected_message): ProxyMultiCountry.objects.bulk_create( [ ProxyMultiCountry(name="Fillory", iso_two_letter="FL"), ] ) with self.assertRaisesMessage(ValueError, expected_message): ProxyMultiProxyCountry.objects.bulk_create( [ ProxyMultiProxyCountry(name="Fillory", iso_two_letter="FL"), ] ) def test_proxy_inheritance_supported(self): ProxyCountry.objects.bulk_create( [ ProxyCountry(name="Qwghlm", iso_two_letter="QW"), Country(name="Tortall", iso_two_letter="TA"), ] ) self.assertQuerysetEqual( ProxyCountry.objects.all(), {"Qwghlm", "Tortall"}, attrgetter("name"), ordered=False, ) ProxyProxyCountry.objects.bulk_create( [ ProxyProxyCountry(name="Netherlands", iso_two_letter="NT"), ] ) self.assertQuerysetEqual( ProxyProxyCountry.objects.all(), { "Qwghlm", "Tortall", "Netherlands", }, attrgetter("name"), ordered=False, ) def test_non_auto_increment_pk(self): State.objects.bulk_create( [State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"]] ) self.assertQuerysetEqual( State.objects.order_by("two_letter_code"), [ "CA", "IL", "ME", "NY", ], attrgetter("two_letter_code"), ) @skipUnlessDBFeature("has_bulk_insert") def test_non_auto_increment_pk_efficiency(self): with self.assertNumQueries(1): State.objects.bulk_create( [State(two_letter_code=s) for s in ["IL", "NY", "CA", "ME"]] ) self.assertQuerysetEqual( State.objects.order_by("two_letter_code"), [ "CA", "IL", "ME", "NY", ], attrgetter("two_letter_code"), ) @skipIfDBFeature("allows_auto_pk_0") def test_zero_as_autoval(self): """ Zero as id for AutoField should raise exception in MySQL, because MySQL does not allow zero for automatic primary key if the NO_AUTO_VALUE_ON_ZERO SQL mode is not enabled. """ valid_country = Country(name="Germany", iso_two_letter="DE") invalid_country = Country(id=0, name="Poland", iso_two_letter="PL") msg = "The database backend does not accept 0 as a value for AutoField." with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create([valid_country, invalid_country]) def test_batch_same_vals(self): # SQLite had a problem where all the same-valued models were # collapsed to one insert. Restaurant.objects.bulk_create([Restaurant(name="foo") for i in range(0, 2)]) self.assertEqual(Restaurant.objects.count(), 2) def test_large_batch(self): TwoFields.objects.bulk_create( [TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)] ) self.assertEqual(TwoFields.objects.count(), 1001) self.assertEqual( TwoFields.objects.filter(f1__gte=450, f1__lte=550).count(), 101 ) self.assertEqual(TwoFields.objects.filter(f2__gte=901).count(), 101) @skipUnlessDBFeature("has_bulk_insert") def test_large_single_field_batch(self): # SQLite had a problem with more than 500 UNIONed selects in single # query. Restaurant.objects.bulk_create([Restaurant() for i in range(0, 501)]) @skipUnlessDBFeature("has_bulk_insert") def test_large_batch_efficiency(self): with override_settings(DEBUG=True): connection.queries_log.clear() TwoFields.objects.bulk_create( [TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)] ) self.assertLess(len(connection.queries), 10) def test_large_batch_mixed(self): """ Test inserting a large batch with objects having primary key set mixed together with objects without PK set. """ TwoFields.objects.bulk_create( [ TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1) for i in range(100000, 101000) ] ) self.assertEqual(TwoFields.objects.count(), 1000) # We can't assume much about the ID's created, except that the above # created IDs must exist. id_range = range(100000, 101000, 2) self.assertEqual(TwoFields.objects.filter(id__in=id_range).count(), 500) self.assertEqual(TwoFields.objects.exclude(id__in=id_range).count(), 500) @skipUnlessDBFeature("has_bulk_insert") def test_large_batch_mixed_efficiency(self): """ Test inserting a large batch with objects having primary key set mixed together with objects without PK set. """ with override_settings(DEBUG=True): connection.queries_log.clear() TwoFields.objects.bulk_create( [ TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1) for i in range(100000, 101000) ] ) self.assertLess(len(connection.queries), 10) def test_explicit_batch_size(self): objs = [TwoFields(f1=i, f2=i) for i in range(0, 4)] num_objs = len(objs) TwoFields.objects.bulk_create(objs, batch_size=1) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=2) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=3) self.assertEqual(TwoFields.objects.count(), num_objs) TwoFields.objects.all().delete() TwoFields.objects.bulk_create(objs, batch_size=num_objs) self.assertEqual(TwoFields.objects.count(), num_objs) def test_empty_model(self): NoFields.objects.bulk_create([NoFields() for i in range(2)]) self.assertEqual(NoFields.objects.count(), 2) @skipUnlessDBFeature("has_bulk_insert") def test_explicit_batch_size_efficiency(self): objs = [TwoFields(f1=i, f2=i) for i in range(0, 100)] with self.assertNumQueries(2): TwoFields.objects.bulk_create(objs, 50) TwoFields.objects.all().delete() with self.assertNumQueries(1): TwoFields.objects.bulk_create(objs, len(objs)) @skipUnlessDBFeature("has_bulk_insert") def test_explicit_batch_size_respects_max_batch_size(self): objs = [Country(name=f"Country {i}") for i in range(1000)] fields = ["name", "iso_two_letter", "description"] max_batch_size = max(connection.ops.bulk_batch_size(fields, objs), 1) with self.assertNumQueries(ceil(len(objs) / max_batch_size)): Country.objects.bulk_create(objs, batch_size=max_batch_size + 1) @skipUnlessDBFeature("has_bulk_insert") def test_bulk_insert_expressions(self): Restaurant.objects.bulk_create( [ Restaurant(name="Sam's Shake Shack"), Restaurant(name=Lower(Value("Betty's Beetroot Bar"))), ] ) bbb = Restaurant.objects.filter(name="betty's beetroot bar") self.assertEqual(bbb.count(), 1) @skipUnlessDBFeature("has_bulk_insert") def test_bulk_insert_nullable_fields(self): fk_to_auto_fields = { "auto_field": NoFields.objects.create(), "small_auto_field": SmallAutoFieldModel.objects.create(), "big_auto_field": BigAutoFieldModel.objects.create(), } # NULL can be mixed with other values in nullable fields nullable_fields = [ field for field in NullableFields._meta.get_fields() if field.name != "id" ] NullableFields.objects.bulk_create( [ NullableFields(**{**fk_to_auto_fields, field.name: None}) for field in nullable_fields ] ) self.assertEqual(NullableFields.objects.count(), len(nullable_fields)) for field in nullable_fields: with self.subTest(field=field): field_value = "" if isinstance(field, FileField) else None self.assertEqual( NullableFields.objects.filter(**{field.name: field_value}).count(), 1, ) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_set_pk_and_insert_single_item(self): with self.assertNumQueries(1): countries = Country.objects.bulk_create([self.data[0]]) self.assertEqual(len(countries), 1) self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0]) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_set_pk_and_query_efficiency(self): with self.assertNumQueries(1): countries = Country.objects.bulk_create(self.data) self.assertEqual(len(countries), 4) self.assertEqual(Country.objects.get(pk=countries[0].pk), countries[0]) self.assertEqual(Country.objects.get(pk=countries[1].pk), countries[1]) self.assertEqual(Country.objects.get(pk=countries[2].pk), countries[2]) self.assertEqual(Country.objects.get(pk=countries[3].pk), countries[3]) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_set_state(self): country_nl = Country(name="Netherlands", iso_two_letter="NL") country_be = Country(name="Belgium", iso_two_letter="BE") Country.objects.bulk_create([country_nl]) country_be.save() # Objects save via bulk_create() and save() should have equal state. self.assertEqual(country_nl._state.adding, country_be._state.adding) self.assertEqual(country_nl._state.db, country_be._state.db) def test_set_state_with_pk_specified(self): state_ca = State(two_letter_code="CA") state_ny = State(two_letter_code="NY") State.objects.bulk_create([state_ca]) state_ny.save() # Objects save via bulk_create() and save() should have equal state. self.assertEqual(state_ca._state.adding, state_ny._state.adding) self.assertEqual(state_ca._state.db, state_ny._state.db) @skipIfDBFeature("supports_ignore_conflicts") def test_ignore_conflicts_value_error(self): message = "This database backend does not support ignoring conflicts." with self.assertRaisesMessage(NotSupportedError, message): TwoFields.objects.bulk_create(self.data, ignore_conflicts=True) @skipUnlessDBFeature("supports_ignore_conflicts") def test_ignore_conflicts_ignore(self): data = [ TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2), TwoFields(f1=3, f2=3), ] TwoFields.objects.bulk_create(data) self.assertEqual(TwoFields.objects.count(), 3) # With ignore_conflicts=True, conflicts are ignored. conflicting_objects = [ TwoFields(f1=2, f2=2), TwoFields(f1=3, f2=3), ] TwoFields.objects.bulk_create([conflicting_objects[0]], ignore_conflicts=True) TwoFields.objects.bulk_create(conflicting_objects, ignore_conflicts=True) self.assertEqual(TwoFields.objects.count(), 3) self.assertIsNone(conflicting_objects[0].pk) self.assertIsNone(conflicting_objects[1].pk) # New objects are created and conflicts are ignored. new_object = TwoFields(f1=4, f2=4) TwoFields.objects.bulk_create( conflicting_objects + [new_object], ignore_conflicts=True ) self.assertEqual(TwoFields.objects.count(), 4) self.assertIsNone(new_object.pk) # Without ignore_conflicts=True, there's a problem. with self.assertRaises(IntegrityError): TwoFields.objects.bulk_create(conflicting_objects) def test_nullable_fk_after_parent(self): parent = NoFields() child = NullableFields(auto_field=parent, integer_field=88) parent.save() NullableFields.objects.bulk_create([child]) child = NullableFields.objects.get(integer_field=88) self.assertEqual(child.auto_field, parent) @skipUnlessDBFeature("can_return_rows_from_bulk_insert") def test_nullable_fk_after_parent_bulk_create(self): parent = NoFields() child = NullableFields(auto_field=parent, integer_field=88) NoFields.objects.bulk_create([parent]) NullableFields.objects.bulk_create([child]) child = NullableFields.objects.get(integer_field=88) self.assertEqual(child.auto_field, parent) def test_unsaved_parent(self): parent = NoFields() msg = ( "bulk_create() prohibited to prevent data loss due to unsaved " "related object 'auto_field'." ) with self.assertRaisesMessage(ValueError, msg): NullableFields.objects.bulk_create([NullableFields(auto_field=parent)]) def test_invalid_batch_size_exception(self): msg = "Batch size must be a positive integer." with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create([], batch_size=-1) @skipIfDBFeature("supports_update_conflicts") def test_update_conflicts_unsupported(self): msg = "This database backend does not support updating conflicts." with self.assertRaisesMessage(NotSupportedError, msg): Country.objects.bulk_create(self.data, update_conflicts=True) @skipUnlessDBFeature("supports_ignore_conflicts", "supports_update_conflicts") def test_ignore_update_conflicts_exclusive(self): msg = "ignore_conflicts and update_conflicts are mutually exclusive" with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create( self.data, ignore_conflicts=True, update_conflicts=True, ) @skipUnlessDBFeature("supports_update_conflicts") def test_update_conflicts_no_update_fields(self): msg = ( "Fields that will be updated when a row insertion fails on " "conflicts must be provided." ) with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create(self.data, update_conflicts=True) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_unique_field_unsupported(self): msg = ( "This database backend does not support updating conflicts with " "specifying unique fields that can trigger the upsert." ) with self.assertRaisesMessage(NotSupportedError, msg): TwoFields.objects.bulk_create( [TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)], update_conflicts=True, update_fields=["f2"], unique_fields=["f1"], ) @skipUnlessDBFeature("supports_update_conflicts") def test_update_conflicts_nonexistent_update_fields(self): unique_fields = None if connection.features.supports_update_conflicts_with_target: unique_fields = ["f1"] msg = "TwoFields has no field named 'nonexistent'" with self.assertRaisesMessage(FieldDoesNotExist, msg): TwoFields.objects.bulk_create( [TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)], update_conflicts=True, update_fields=["nonexistent"], unique_fields=unique_fields, ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_unique_fields_required(self): msg = "Unique fields that can trigger the upsert must be provided." with self.assertRaisesMessage(ValueError, msg): TwoFields.objects.bulk_create( [TwoFields(f1=1, f2=1), TwoFields(f1=2, f2=2)], update_conflicts=True, update_fields=["f1"], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_invalid_update_fields(self): msg = "bulk_create() can only be used with concrete fields in update_fields." # Reverse one-to-one relationship. with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create( self.data, update_conflicts=True, update_fields=["relatedmodel"], unique_fields=["pk"], ) # Many-to-many relationship. with self.assertRaisesMessage(ValueError, msg): RelatedModel.objects.bulk_create( [RelatedModel(country=self.data[0])], update_conflicts=True, update_fields=["big_auto_fields"], unique_fields=["country"], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_pk_in_update_fields(self): msg = "bulk_create() cannot be used with primary keys in update_fields." with self.assertRaisesMessage(ValueError, msg): BigAutoFieldModel.objects.bulk_create( [BigAutoFieldModel()], update_conflicts=True, update_fields=["id"], unique_fields=["id"], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target", ) def test_update_conflicts_invalid_unique_fields(self): msg = "bulk_create() can only be used with concrete fields in unique_fields." # Reverse one-to-one relationship. with self.assertRaisesMessage(ValueError, msg): Country.objects.bulk_create( self.data, update_conflicts=True, update_fields=["name"], unique_fields=["relatedmodel"], ) # Many-to-many relationship. with self.assertRaisesMessage(ValueError, msg): RelatedModel.objects.bulk_create( [RelatedModel(country=self.data[0])], update_conflicts=True, update_fields=["name"], unique_fields=["big_auto_fields"], ) def _test_update_conflicts_two_fields(self, unique_fields): TwoFields.objects.bulk_create( [ TwoFields(f1=1, f2=1, name="a"), TwoFields(f1=2, f2=2, name="b"), ] ) self.assertEqual(TwoFields.objects.count(), 2) conflicting_objects = [ TwoFields(f1=1, f2=1, name="c"), TwoFields(f1=2, f2=2, name="d"), ] TwoFields.objects.bulk_create( conflicting_objects, update_conflicts=True, unique_fields=unique_fields, update_fields=["name"], ) self.assertEqual(TwoFields.objects.count(), 2) self.assertCountEqual( TwoFields.objects.values("f1", "f2", "name"), [ {"f1": 1, "f2": 1, "name": "c"}, {"f1": 2, "f2": 2, "name": "d"}, ], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_two_fields_unique_fields_first(self): self._test_update_conflicts_two_fields(["f1"]) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_two_fields_unique_fields_second(self): self._test_update_conflicts_two_fields(["f2"]) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_two_fields_unique_fields_both(self): with self.assertRaises((OperationalError, ProgrammingError)): self._test_update_conflicts_two_fields(["f1", "f2"]) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_two_fields_no_unique_fields(self): self._test_update_conflicts_two_fields([]) def _test_update_conflicts_unique_two_fields(self, unique_fields): Country.objects.bulk_create(self.data) self.assertEqual(Country.objects.count(), 4) new_data = [ # Conflicting countries. Country( name="Germany", iso_two_letter="DE", description=("Germany is a country in Central Europe."), ), Country( name="Czech Republic", iso_two_letter="CZ", description=( "The Czech Republic is a landlocked country in Central Europe." ), ), # New countries. Country(name="Australia", iso_two_letter="AU"), Country( name="Japan", iso_two_letter="JP", description=("Japan is an island country in East Asia."), ), ] Country.objects.bulk_create( new_data, update_conflicts=True, update_fields=["description"], unique_fields=unique_fields, ) self.assertEqual(Country.objects.count(), 6) self.assertCountEqual( Country.objects.values("iso_two_letter", "description"), [ {"iso_two_letter": "US", "description": ""}, {"iso_two_letter": "NL", "description": ""}, { "iso_two_letter": "DE", "description": ("Germany is a country in Central Europe."), }, { "iso_two_letter": "CZ", "description": ( "The Czech Republic is a landlocked country in Central Europe." ), }, {"iso_two_letter": "AU", "description": ""}, { "iso_two_letter": "JP", "description": ("Japan is an island country in East Asia."), }, ], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_two_fields_unique_fields_both(self): self._test_update_conflicts_unique_two_fields(["iso_two_letter", "name"]) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_two_fields_unique_fields_one(self): with self.assertRaises((OperationalError, ProgrammingError)): self._test_update_conflicts_unique_two_fields(["iso_two_letter"]) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_unique_two_fields_unique_no_unique_fields(self): self._test_update_conflicts_unique_two_fields([]) def _test_update_conflicts(self, unique_fields): UpsertConflict.objects.bulk_create( [ UpsertConflict(number=1, rank=1, name="John"), UpsertConflict(number=2, rank=2, name="Mary"), UpsertConflict(number=3, rank=3, name="Hannah"), ] ) self.assertEqual(UpsertConflict.objects.count(), 3) conflicting_objects = [ UpsertConflict(number=1, rank=4, name="Steve"), UpsertConflict(number=2, rank=2, name="Olivia"), UpsertConflict(number=3, rank=1, name="Hannah"), ] UpsertConflict.objects.bulk_create( conflicting_objects, update_conflicts=True, update_fields=["name", "rank"], unique_fields=unique_fields, ) self.assertEqual(UpsertConflict.objects.count(), 3) self.assertCountEqual( UpsertConflict.objects.values("number", "rank", "name"), [ {"number": 1, "rank": 4, "name": "Steve"}, {"number": 2, "rank": 2, "name": "Olivia"}, {"number": 3, "rank": 1, "name": "Hannah"}, ], ) UpsertConflict.objects.bulk_create( conflicting_objects + [UpsertConflict(number=4, rank=4, name="Mark")], update_conflicts=True, update_fields=["name", "rank"], unique_fields=unique_fields, ) self.assertEqual(UpsertConflict.objects.count(), 4) self.assertCountEqual( UpsertConflict.objects.values("number", "rank", "name"), [ {"number": 1, "rank": 4, "name": "Steve"}, {"number": 2, "rank": 2, "name": "Olivia"}, {"number": 3, "rank": 1, "name": "Hannah"}, {"number": 4, "rank": 4, "name": "Mark"}, ], ) @skipUnlessDBFeature( "supports_update_conflicts", "supports_update_conflicts_with_target" ) def test_update_conflicts_unique_fields(self): self._test_update_conflicts(unique_fields=["number"]) @skipUnlessDBFeature("supports_update_conflicts") @skipIfDBFeature("supports_update_conflicts_with_target") def test_update_conflicts_no_unique_fields(self): self._test_update_conflicts([])
b61446aed834c855c63af00998a5130a388f10082c428b36795b3a1d97339168
import datetime import uuid from decimal import Decimal from django.db import models from django.utils import timezone try: from PIL import Image except ImportError: Image = None class Country(models.Model): name = models.CharField(max_length=255) iso_two_letter = models.CharField(max_length=2) description = models.TextField() class Meta: constraints = [ models.UniqueConstraint( fields=["iso_two_letter", "name"], name="country_name_iso_unique", ), ] class ProxyCountry(Country): class Meta: proxy = True class ProxyProxyCountry(ProxyCountry): class Meta: proxy = True class ProxyMultiCountry(ProxyCountry): pass class ProxyMultiProxyCountry(ProxyMultiCountry): class Meta: proxy = True class Place(models.Model): name = models.CharField(max_length=100) class Meta: abstract = True class Restaurant(Place): pass class Pizzeria(Restaurant): pass class State(models.Model): two_letter_code = models.CharField(max_length=2, primary_key=True) class TwoFields(models.Model): f1 = models.IntegerField(unique=True) f2 = models.IntegerField(unique=True) name = models.CharField(max_length=15, null=True) class UpsertConflict(models.Model): number = models.IntegerField(unique=True) rank = models.IntegerField() name = models.CharField(max_length=15) class NoFields(models.Model): pass class SmallAutoFieldModel(models.Model): id = models.SmallAutoField(primary_key=True) class BigAutoFieldModel(models.Model): id = models.BigAutoField(primary_key=True) class NullableFields(models.Model): # Fields in db.backends.oracle.BulkInsertMapper big_int_filed = models.BigIntegerField(null=True, default=1) binary_field = models.BinaryField(null=True, default=b"data") date_field = models.DateField(null=True, default=timezone.now) datetime_field = models.DateTimeField(null=True, default=timezone.now) decimal_field = models.DecimalField( null=True, max_digits=2, decimal_places=1, default=Decimal("1.1") ) duration_field = models.DurationField(null=True, default=datetime.timedelta(1)) float_field = models.FloatField(null=True, default=3.2) integer_field = models.IntegerField(null=True, default=2) null_boolean_field = models.BooleanField(null=True, default=False) positive_big_integer_field = models.PositiveBigIntegerField( null=True, default=2**63 - 1 ) positive_integer_field = models.PositiveIntegerField(null=True, default=3) positive_small_integer_field = models.PositiveSmallIntegerField( null=True, default=4 ) small_integer_field = models.SmallIntegerField(null=True, default=5) time_field = models.TimeField(null=True, default=timezone.now) auto_field = models.ForeignKey(NoFields, on_delete=models.CASCADE, null=True) small_auto_field = models.ForeignKey( SmallAutoFieldModel, on_delete=models.CASCADE, null=True ) big_auto_field = models.ForeignKey( BigAutoFieldModel, on_delete=models.CASCADE, null=True ) # Fields not required in BulkInsertMapper char_field = models.CharField(null=True, max_length=4, default="char") email_field = models.EmailField(null=True, default="[email protected]") file_field = models.FileField(null=True, default="file.txt") file_path_field = models.FilePathField(path="/tmp", null=True, default="file.txt") generic_ip_address_field = models.GenericIPAddressField( null=True, default="127.0.0.1" ) if Image: image_field = models.ImageField(null=True, default="image.jpg") slug_field = models.SlugField(null=True, default="slug") text_field = models.TextField(null=True, default="text") url_field = models.URLField(null=True, default="/") uuid_field = models.UUIDField(null=True, default=uuid.uuid4) class RelatedModel(models.Model): name = models.CharField(max_length=15, null=True) country = models.OneToOneField(Country, models.CASCADE, primary_key=True) big_auto_fields = models.ManyToManyField(BigAutoFieldModel)
2a3cd67106ecf6a26e265dbe6f01d992b7493e0bfec23ad5f36b8931cf1745e1
""" Regression tests for Model inheritance behavior. """ import datetime from operator import attrgetter from unittest import expectedFailure from django import forms from django.test import TestCase from .models import ( ArticleWithAuthor, BachelorParty, BirthdayParty, BusStation, Child, Congressman, DerivedM, InternalCertificationAudit, ItalianRestaurant, M2MChild, MessyBachelorParty, ParkingLot, ParkingLot3, ParkingLot4A, ParkingLot4B, Person, Place, Politician, Profile, QualityControl, Restaurant, SelfRefChild, SelfRefParent, Senator, Supplier, TrainStation, User, Wholesaler, ) class ModelInheritanceTest(TestCase): def test_model_inheritance(self): # Regression for #7350, #7202 # When you create a Parent object with a specific reference to an # existent child instance, saving the Parent doesn't duplicate the # child. This behavior is only activated during a raw save - it is # mostly relevant to deserialization, but any sort of CORBA style # 'narrow()' API would require a similar approach. # Create a child-parent-grandparent chain place1 = Place(name="Guido's House of Pasta", address="944 W. Fullerton") place1.save_base(raw=True) restaurant = Restaurant( place_ptr=place1, serves_hot_dogs=True, serves_pizza=False, ) restaurant.save_base(raw=True) italian_restaurant = ItalianRestaurant( restaurant_ptr=restaurant, serves_gnocchi=True ) italian_restaurant.save_base(raw=True) # Create a child-parent chain with an explicit parent link place2 = Place(name="Main St", address="111 Main St") place2.save_base(raw=True) park = ParkingLot(parent=place2, capacity=100) park.save_base(raw=True) # No extra parent objects have been created. places = list(Place.objects.all()) self.assertEqual(places, [place1, place2]) dicts = list(Restaurant.objects.values("name", "serves_hot_dogs")) self.assertEqual( dicts, [{"name": "Guido's House of Pasta", "serves_hot_dogs": True}] ) dicts = list( ItalianRestaurant.objects.values( "name", "serves_hot_dogs", "serves_gnocchi" ) ) self.assertEqual( dicts, [ { "name": "Guido's House of Pasta", "serves_gnocchi": True, "serves_hot_dogs": True, } ], ) dicts = list(ParkingLot.objects.values("name", "capacity")) self.assertEqual( dicts, [ { "capacity": 100, "name": "Main St", } ], ) # You can also update objects when using a raw save. place1.name = "Guido's All New House of Pasta" place1.save_base(raw=True) restaurant.serves_hot_dogs = False restaurant.save_base(raw=True) italian_restaurant.serves_gnocchi = False italian_restaurant.save_base(raw=True) place2.name = "Derelict lot" place2.save_base(raw=True) park.capacity = 50 park.save_base(raw=True) # No extra parent objects after an update, either. places = list(Place.objects.all()) self.assertEqual(places, [place2, place1]) self.assertEqual(places[0].name, "Derelict lot") self.assertEqual(places[1].name, "Guido's All New House of Pasta") dicts = list(Restaurant.objects.values("name", "serves_hot_dogs")) self.assertEqual( dicts, [ { "name": "Guido's All New House of Pasta", "serves_hot_dogs": False, } ], ) dicts = list( ItalianRestaurant.objects.values( "name", "serves_hot_dogs", "serves_gnocchi" ) ) self.assertEqual( dicts, [ { "name": "Guido's All New House of Pasta", "serves_gnocchi": False, "serves_hot_dogs": False, } ], ) dicts = list(ParkingLot.objects.values("name", "capacity")) self.assertEqual( dicts, [ { "capacity": 50, "name": "Derelict lot", } ], ) # If you try to raw_save a parent attribute onto a child object, # the attribute will be ignored. italian_restaurant.name = "Lorenzo's Pasta Hut" italian_restaurant.save_base(raw=True) # Note that the name has not changed # - name is an attribute of Place, not ItalianRestaurant dicts = list( ItalianRestaurant.objects.values( "name", "serves_hot_dogs", "serves_gnocchi" ) ) self.assertEqual( dicts, [ { "name": "Guido's All New House of Pasta", "serves_gnocchi": False, "serves_hot_dogs": False, } ], ) def test_issue_7105(self): # Regressions tests for #7105: dates() queries should be able to use # fields from the parent model as easily as the child. Child.objects.create( name="child", created=datetime.datetime(2008, 6, 26, 17, 0, 0) ) datetimes = list(Child.objects.datetimes("created", "month")) self.assertEqual(datetimes, [datetime.datetime(2008, 6, 1, 0, 0)]) def test_issue_7276(self): # Regression test for #7276: calling delete() on a model with # multi-table inheritance should delete the associated rows from any # ancestor tables, as well as any descendent objects. place1 = Place(name="Guido's House of Pasta", address="944 W. Fullerton") place1.save_base(raw=True) restaurant = Restaurant( place_ptr=place1, serves_hot_dogs=True, serves_pizza=False, ) restaurant.save_base(raw=True) italian_restaurant = ItalianRestaurant( restaurant_ptr=restaurant, serves_gnocchi=True ) italian_restaurant.save_base(raw=True) ident = ItalianRestaurant.objects.all()[0].id self.assertEqual(Place.objects.get(pk=ident), place1) Restaurant.objects.create( name="a", address="xx", serves_hot_dogs=True, serves_pizza=False, ) # This should delete both Restaurants, plus the related places, plus # the ItalianRestaurant. Restaurant.objects.all().delete() with self.assertRaises(Place.DoesNotExist): Place.objects.get(pk=ident) with self.assertRaises(ItalianRestaurant.DoesNotExist): ItalianRestaurant.objects.get(pk=ident) def test_issue_6755(self): """ Regression test for #6755 """ r = Restaurant(serves_pizza=False, serves_hot_dogs=False) r.save() self.assertEqual(r.id, r.place_ptr_id) orig_id = r.id r = Restaurant(place_ptr_id=orig_id, serves_pizza=True, serves_hot_dogs=False) r.save() self.assertEqual(r.id, orig_id) self.assertEqual(r.id, r.place_ptr_id) def test_issue_11764(self): """ Regression test for #11764 """ wholesalers = list(Wholesaler.objects.select_related()) self.assertEqual(wholesalers, []) def test_issue_7853(self): """ Regression test for #7853 If the parent class has a self-referential link, make sure that any updates to that link via the child update the right table. """ obj = SelfRefChild.objects.create(child_data=37, parent_data=42) obj.delete() def test_get_next_previous_by_date(self): """ Regression tests for #8076 get_(next/previous)_by_date should work """ c1 = ArticleWithAuthor( headline="ArticleWithAuthor 1", author="Person 1", pub_date=datetime.datetime(2005, 8, 1, 3, 0), ) c1.save() c2 = ArticleWithAuthor( headline="ArticleWithAuthor 2", author="Person 2", pub_date=datetime.datetime(2005, 8, 1, 10, 0), ) c2.save() c3 = ArticleWithAuthor( headline="ArticleWithAuthor 3", author="Person 3", pub_date=datetime.datetime(2005, 8, 2), ) c3.save() self.assertEqual(c1.get_next_by_pub_date(), c2) self.assertEqual(c2.get_next_by_pub_date(), c3) with self.assertRaises(ArticleWithAuthor.DoesNotExist): c3.get_next_by_pub_date() self.assertEqual(c3.get_previous_by_pub_date(), c2) self.assertEqual(c2.get_previous_by_pub_date(), c1) with self.assertRaises(ArticleWithAuthor.DoesNotExist): c1.get_previous_by_pub_date() def test_inherited_fields(self): """ Regression test for #8825 and #9390 Make sure all inherited fields (esp. m2m fields, in this case) appear on the child class. """ m2mchildren = list(M2MChild.objects.filter(articles__isnull=False)) self.assertEqual(m2mchildren, []) # Ordering should not include any database column more than once (this # is most likely to occur naturally with model inheritance, so we # check it here). Regression test for #9390. This necessarily pokes at # the SQL string for the query, since the duplicate problems are only # apparent at that late stage. qs = ArticleWithAuthor.objects.order_by("pub_date", "pk") sql = qs.query.get_compiler(qs.db).as_sql()[0] fragment = sql[sql.find("ORDER BY") :] pos = fragment.find("pub_date") self.assertEqual(fragment.find("pub_date", pos + 1), -1) def test_queryset_update_on_parent_model(self): """ Regression test for #10362 It is possible to call update() and only change a field in an ancestor model. """ article = ArticleWithAuthor.objects.create( author="fred", headline="Hey there!", pub_date=datetime.datetime(2009, 3, 1, 8, 0, 0), ) update = ArticleWithAuthor.objects.filter(author="fred").update( headline="Oh, no!" ) self.assertEqual(update, 1) update = ArticleWithAuthor.objects.filter(pk=article.pk).update( headline="Oh, no!" ) self.assertEqual(update, 1) derivedm1 = DerivedM.objects.create( customPK=44, base_name="b1", derived_name="d1", ) self.assertEqual(derivedm1.customPK, 44) self.assertEqual(derivedm1.base_name, "b1") self.assertEqual(derivedm1.derived_name, "d1") derivedms = list(DerivedM.objects.all()) self.assertEqual(derivedms, [derivedm1]) def test_use_explicit_o2o_to_parent_as_pk(self): """ The connector from child to parent need not be the pk on the child. """ self.assertEqual(ParkingLot3._meta.pk.name, "primary_key") # the child->parent link self.assertEqual(ParkingLot3._meta.get_ancestor_link(Place).name, "parent") def test_use_explicit_o2o_to_parent_from_abstract_model(self): self.assertEqual(ParkingLot4A._meta.pk.name, "parent") ParkingLot4A.objects.create( name="Parking4A", address="21 Jump Street", ) self.assertEqual(ParkingLot4B._meta.pk.name, "parent") ParkingLot4A.objects.create( name="Parking4B", address="21 Jump Street", ) def test_all_fields_from_abstract_base_class(self): """ Regression tests for #7588 """ # All fields from an ABC, including those inherited non-abstractly # should be available on child classes (#7588). Creating this instance # should work without error. QualityControl.objects.create( headline="Problems in Django", pub_date=datetime.datetime.now(), quality=10, assignee="adrian", ) def test_abstract_base_class_m2m_relation_inheritance(self): # many-to-many relations defined on an abstract base class are # correctly inherited (and created) on the child class. p1 = Person.objects.create(name="Alice") p2 = Person.objects.create(name="Bob") p3 = Person.objects.create(name="Carol") p4 = Person.objects.create(name="Dave") birthday = BirthdayParty.objects.create(name="Birthday party for Alice") birthday.attendees.set([p1, p3]) bachelor = BachelorParty.objects.create(name="Bachelor party for Bob") bachelor.attendees.set([p2, p4]) parties = list(p1.birthdayparty_set.all()) self.assertEqual(parties, [birthday]) parties = list(p1.bachelorparty_set.all()) self.assertEqual(parties, []) parties = list(p2.bachelorparty_set.all()) self.assertEqual(parties, [bachelor]) # A subclass of a subclass of an abstract model doesn't get its own # accessor. self.assertFalse(hasattr(p2, "messybachelorparty_set")) # ... but it does inherit the m2m from its parent messy = MessyBachelorParty.objects.create(name="Bachelor party for Dave") messy.attendees.set([p4]) messy_parent = messy.bachelorparty_ptr parties = list(p4.bachelorparty_set.all()) self.assertEqual(parties, [bachelor, messy_parent]) def test_abstract_base_class_m2m_relation_inheritance_manager_reused(self): p1 = Person.objects.create(name="Alice") self.assertIs(p1.birthdayparty_set, p1.birthdayparty_set) self.assertIs(p1.bachelorparty_set, p1.bachelorparty_set) def test_abstract_verbose_name_plural_inheritance(self): """ verbose_name_plural correctly inherited from ABC if inheritance chain includes an abstract model. """ # Regression test for #11369: verbose_name_plural should be inherited # from an ABC even when there are one or more intermediate # abstract models in the inheritance chain, for consistency with # verbose_name. self.assertEqual(InternalCertificationAudit._meta.verbose_name_plural, "Audits") def test_inherited_nullable_exclude(self): obj = SelfRefChild.objects.create(child_data=37, parent_data=42) self.assertQuerysetEqual( SelfRefParent.objects.exclude(self_data=72), [obj.pk], attrgetter("pk") ) self.assertQuerysetEqual( SelfRefChild.objects.exclude(self_data=72), [obj.pk], attrgetter("pk") ) def test_concrete_abstract_concrete_pk(self): """ Primary key set correctly with concrete->abstract->concrete inheritance. """ # Regression test for #13987: Primary key is incorrectly determined # when more than one model has a concrete->abstract->concrete # inheritance hierarchy. self.assertEqual( len( [field for field in BusStation._meta.local_fields if field.primary_key] ), 1, ) self.assertEqual( len( [ field for field in TrainStation._meta.local_fields if field.primary_key ] ), 1, ) self.assertIs(BusStation._meta.pk.model, BusStation) self.assertIs(TrainStation._meta.pk.model, TrainStation) def test_inherited_unique_field_with_form(self): """ A model which has different primary key for the parent model passes unique field checking correctly (#17615). """ class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = "__all__" User.objects.create(username="user_only") p = Profile.objects.create(username="user_with_profile") form = ProfileForm( {"username": "user_with_profile", "extra": "hello"}, instance=p ) self.assertTrue(form.is_valid()) def test_inheritance_joins(self): # Test for #17502 - check that filtering through two levels of # inheritance chain doesn't generate extra joins. qs = ItalianRestaurant.objects.all() self.assertEqual(str(qs.query).count("JOIN"), 2) qs = ItalianRestaurant.objects.filter(name="foo") self.assertEqual(str(qs.query).count("JOIN"), 2) @expectedFailure def test_inheritance_values_joins(self): # It would be nice (but not too important) to skip the middle join in # this case. Skipping is possible as nothing from the middle model is # used in the qs and top contains direct pointer to the bottom model. qs = ItalianRestaurant.objects.values_list("serves_gnocchi").filter(name="foo") self.assertEqual(str(qs.query).count("JOIN"), 1) def test_issue_21554(self): senator = Senator.objects.create(name="John Doe", title="X", state="Y") senator = Senator.objects.get(pk=senator.pk) self.assertEqual(senator.name, "John Doe") self.assertEqual(senator.title, "X") self.assertEqual(senator.state, "Y") def test_inheritance_resolve_columns(self): Restaurant.objects.create( name="Bobs Cafe", address="Somewhere", serves_pizza=True, serves_hot_dogs=True, ) p = Place.objects.select_related("restaurant")[0] self.assertIsInstance(p.restaurant.serves_pizza, bool) def test_inheritance_select_related(self): # Regression test for #7246 r1 = Restaurant.objects.create( name="Nobu", serves_hot_dogs=True, serves_pizza=False ) r2 = Restaurant.objects.create( name="Craft", serves_hot_dogs=False, serves_pizza=True ) Supplier.objects.create(name="John", restaurant=r1) Supplier.objects.create(name="Jane", restaurant=r2) self.assertQuerysetEqual( Supplier.objects.order_by("name").select_related(), [ "Jane", "John", ], attrgetter("name"), ) jane = Supplier.objects.order_by("name").select_related("restaurant")[0] self.assertEqual(jane.restaurant.name, "Craft") def test_filter_with_parent_fk(self): r = Restaurant.objects.create() s = Supplier.objects.create(restaurant=r) # The mismatch between Restaurant and Place is intentional (#28175). self.assertSequenceEqual( Supplier.objects.filter(restaurant__in=Place.objects.all()), [s] ) def test_ptr_accessor_assigns_state(self): r = Restaurant.objects.create() self.assertIs(r.place_ptr._state.adding, False) self.assertEqual(r.place_ptr._state.db, "default") def test_related_filtering_query_efficiency_ticket_15844(self): r = Restaurant.objects.create( name="Guido's House of Pasta", address="944 W. Fullerton", serves_hot_dogs=True, serves_pizza=False, ) s = Supplier.objects.create(restaurant=r) with self.assertNumQueries(1): self.assertSequenceEqual(Supplier.objects.filter(restaurant=r), [s]) with self.assertNumQueries(1): self.assertSequenceEqual(r.supplier_set.all(), [s]) def test_queries_on_parent_access(self): italian_restaurant = ItalianRestaurant.objects.create( name="Guido's House of Pasta", address="944 W. Fullerton", serves_hot_dogs=True, serves_pizza=False, serves_gnocchi=True, ) # No queries are made when accessing the parent objects. italian_restaurant = ItalianRestaurant.objects.get(pk=italian_restaurant.pk) with self.assertNumQueries(0): restaurant = italian_restaurant.restaurant_ptr self.assertEqual(restaurant.place_ptr.restaurant, restaurant) self.assertEqual(restaurant.italianrestaurant, italian_restaurant) # One query is made when accessing the parent objects when the instance # is deferred. italian_restaurant = ItalianRestaurant.objects.only("serves_gnocchi").get( pk=italian_restaurant.pk ) with self.assertNumQueries(1): restaurant = italian_restaurant.restaurant_ptr self.assertEqual(restaurant.place_ptr.restaurant, restaurant) self.assertEqual(restaurant.italianrestaurant, italian_restaurant) # No queries are made when accessing the parent objects when the # instance has deferred a field not present in the parent table. italian_restaurant = ItalianRestaurant.objects.defer("serves_gnocchi").get( pk=italian_restaurant.pk ) with self.assertNumQueries(0): restaurant = italian_restaurant.restaurant_ptr self.assertEqual(restaurant.place_ptr.restaurant, restaurant) self.assertEqual(restaurant.italianrestaurant, italian_restaurant) def test_id_field_update_on_ancestor_change(self): place1 = Place.objects.create(name="House of Pasta", address="944 Fullerton") place2 = Place.objects.create(name="House of Pizza", address="954 Fullerton") place3 = Place.objects.create(name="Burger house", address="964 Fullerton") restaurant1 = Restaurant.objects.create( place_ptr=place1, serves_hot_dogs=True, serves_pizza=False, ) restaurant2 = Restaurant.objects.create( place_ptr=place2, serves_hot_dogs=True, serves_pizza=False, ) italian_restaurant = ItalianRestaurant.objects.create( restaurant_ptr=restaurant1, serves_gnocchi=True, ) # Changing the parent of a restaurant changes the restaurant's ID & PK. restaurant1.place_ptr = place3 self.assertEqual(restaurant1.pk, place3.pk) self.assertEqual(restaurant1.id, place3.id) self.assertEqual(restaurant1.pk, restaurant1.id) restaurant1.place_ptr = None self.assertIsNone(restaurant1.pk) self.assertIsNone(restaurant1.id) # Changing the parent of an italian restaurant changes the restaurant's # ID & PK. italian_restaurant.restaurant_ptr = restaurant2 self.assertEqual(italian_restaurant.pk, restaurant2.pk) self.assertEqual(italian_restaurant.id, restaurant2.id) self.assertEqual(italian_restaurant.pk, italian_restaurant.id) italian_restaurant.restaurant_ptr = None self.assertIsNone(italian_restaurant.pk) self.assertIsNone(italian_restaurant.id) def test_create_new_instance_with_pk_equals_none(self): p1 = Profile.objects.create(username="john") p2 = User.objects.get(pk=p1.user_ptr_id).profile # Create a new profile by setting pk = None. p2.pk = None p2.user_ptr_id = None p2.username = "bill" p2.save() self.assertEqual(Profile.objects.count(), 2) self.assertEqual(User.objects.get(pk=p1.user_ptr_id).username, "john") def test_create_new_instance_with_pk_equals_none_multi_inheritance(self): c1 = Congressman.objects.create(state="PA", name="John", title="senator 1") c2 = Person.objects.get(pk=c1.pk).congressman # Create a new congressman by setting pk = None. c2.pk = None c2.id = None c2.politician_ptr_id = None c2.name = "Bill" c2.title = "senator 2" c2.save() self.assertEqual(Congressman.objects.count(), 2) self.assertEqual(Person.objects.get(pk=c1.pk).name, "John") self.assertEqual( Politician.objects.get(pk=c1.politician_ptr_id).title, "senator 1", )
4262f8e5a854bf2dbe0cb10c1e621438f491c58f7afed8d8fa26415bf3bc8899
import datetime from django.db import models class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Meta: ordering = ("name",) class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) class ItalianRestaurant(Restaurant): serves_gnocchi = models.BooleanField(default=False) class ParkingLot(Place): # An explicit link to the parent (we can control the attribute name). parent = models.OneToOneField( Place, models.CASCADE, primary_key=True, parent_link=True ) capacity = models.IntegerField() class ParkingLot3(Place): # The parent_link connector need not be the pk on the model. primary_key = models.AutoField(primary_key=True) parent = models.OneToOneField(Place, models.CASCADE, parent_link=True) class ParkingLot4(models.Model): # Test parent_link connector can be discovered in abstract classes. parent = models.OneToOneField(Place, models.CASCADE, parent_link=True) class Meta: abstract = True class ParkingLot4A(ParkingLot4, Place): pass class ParkingLot4B(Place, ParkingLot4): pass class Supplier(models.Model): name = models.CharField(max_length=50) restaurant = models.ForeignKey(Restaurant, models.CASCADE) class Wholesaler(Supplier): retailer = models.ForeignKey( Supplier, models.CASCADE, related_name="wholesale_supplier" ) class Parent(models.Model): created = models.DateTimeField(default=datetime.datetime.now) class Child(Parent): name = models.CharField(max_length=10) class SelfRefParent(models.Model): parent_data = models.IntegerField() self_data = models.ForeignKey("self", models.SET_NULL, null=True) class SelfRefChild(SelfRefParent): child_data = models.IntegerField() class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() class Meta: ordering = ("-pub_date", "headline") class ArticleWithAuthor(Article): author = models.CharField(max_length=100) class M2MBase(models.Model): articles = models.ManyToManyField(Article) class M2MChild(M2MBase): name = models.CharField(max_length=50) class Evaluation(Article): quality = models.IntegerField() class Meta: abstract = True class QualityControl(Evaluation): assignee = models.CharField(max_length=50) class BaseM(models.Model): base_name = models.CharField(max_length=100) class DerivedM(BaseM): customPK = models.IntegerField(primary_key=True) derived_name = models.CharField(max_length=100) class AuditBase(models.Model): planned_date = models.DateField() class Meta: abstract = True verbose_name_plural = "Audits" class CertificationAudit(AuditBase): class Meta(AuditBase.Meta): abstract = True class InternalCertificationAudit(CertificationAudit): auditing_dept = models.CharField(max_length=20) # Abstract classes don't get m2m tables autocreated. class Person(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ("name",) class AbstractEvent(models.Model): name = models.CharField(max_length=100) attendees = models.ManyToManyField(Person, related_name="%(class)s_set") class Meta: abstract = True ordering = ("name",) class BirthdayParty(AbstractEvent): pass class BachelorParty(AbstractEvent): pass class MessyBachelorParty(BachelorParty): pass # Check concrete -> abstract -> concrete inheritance class SearchableLocation(models.Model): keywords = models.CharField(max_length=255) class Station(SearchableLocation): name = models.CharField(max_length=128) class Meta: abstract = True class BusStation(Station): inbound = models.BooleanField(default=False) class TrainStation(Station): zone = models.IntegerField() class User(models.Model): username = models.CharField(max_length=30, unique=True) class Profile(User): profile_id = models.AutoField(primary_key=True) extra = models.CharField(max_length=30, blank=True) # Check concrete + concrete -> concrete -> concrete class Politician(models.Model): politician_id = models.AutoField(primary_key=True) title = models.CharField(max_length=50) class Congressman(Person, Politician): state = models.CharField(max_length=2) class Senator(Congressman): pass
0312b5461946a519e2b7eed5cddfe609ca399153fcd63eb86632fc765e02ba80
import datetime from decimal import Decimal from unittest import mock from django.core.exceptions import FieldError from django.db import NotSupportedError, connection from django.db.models import ( Avg, BooleanField, Case, F, Func, IntegerField, Max, Min, OuterRef, Q, RowRange, Subquery, Sum, Value, ValueRange, When, Window, WindowFrame, ) from django.db.models.fields.json import KeyTextTransform, KeyTransform from django.db.models.functions import ( Cast, CumeDist, DenseRank, ExtractYear, FirstValue, Lag, LastValue, Lead, NthValue, Ntile, PercentRank, Rank, RowNumber, Upper, ) from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from .models import Detail, Employee @skipUnlessDBFeature("supports_over_clause") class WindowFunctionTests(TestCase): @classmethod def setUpTestData(cls): Employee.objects.bulk_create( [ Employee( name=e[0], salary=e[1], department=e[2], hire_date=e[3], age=e[4], bonus=Decimal(e[1]) / 400, ) for e in [ ("Jones", 45000, "Accounting", datetime.datetime(2005, 11, 1), 20), ( "Williams", 37000, "Accounting", datetime.datetime(2009, 6, 1), 20, ), ("Jenson", 45000, "Accounting", datetime.datetime(2008, 4, 1), 20), ("Adams", 50000, "Accounting", datetime.datetime(2013, 7, 1), 50), ("Smith", 55000, "Sales", datetime.datetime(2007, 6, 1), 30), ("Brown", 53000, "Sales", datetime.datetime(2009, 9, 1), 30), ("Johnson", 40000, "Marketing", datetime.datetime(2012, 3, 1), 30), ("Smith", 38000, "Marketing", datetime.datetime(2009, 10, 1), 20), ("Wilkinson", 60000, "IT", datetime.datetime(2011, 3, 1), 40), ("Moore", 34000, "IT", datetime.datetime(2013, 8, 1), 40), ("Miller", 100000, "Management", datetime.datetime(2005, 6, 1), 40), ("Johnson", 80000, "Management", datetime.datetime(2005, 7, 1), 50), ] ] ) def test_dense_rank(self): tests = [ ExtractYear(F("hire_date")).asc(), F("hire_date__year").asc(), "hire_date__year", ] for order_by in tests: with self.subTest(order_by=order_by): qs = Employee.objects.annotate( rank=Window(expression=DenseRank(), order_by=order_by), ) self.assertQuerysetEqual( qs, [ ("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 1), ("Miller", 100000, "Management", datetime.date(2005, 6, 1), 1), ("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 1), ("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 2), ("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 3), ("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 4), ("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 4), ("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 4), ("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 5), ("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 6), ("Moore", 34000, "IT", datetime.date(2013, 8, 1), 7), ("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 7), ], lambda entry: ( entry.name, entry.salary, entry.department, entry.hire_date, entry.rank, ), ordered=False, ) def test_department_salary(self): qs = Employee.objects.annotate( department_sum=Window( expression=Sum("salary"), partition_by=F("department"), order_by=[F("hire_date").asc()], ) ).order_by("department", "department_sum") self.assertQuerysetEqual( qs, [ ("Jones", "Accounting", 45000, 45000), ("Jenson", "Accounting", 45000, 90000), ("Williams", "Accounting", 37000, 127000), ("Adams", "Accounting", 50000, 177000), ("Wilkinson", "IT", 60000, 60000), ("Moore", "IT", 34000, 94000), ("Miller", "Management", 100000, 100000), ("Johnson", "Management", 80000, 180000), ("Smith", "Marketing", 38000, 38000), ("Johnson", "Marketing", 40000, 78000), ("Smith", "Sales", 55000, 55000), ("Brown", "Sales", 53000, 108000), ], lambda entry: ( entry.name, entry.department, entry.salary, entry.department_sum, ), ) def test_rank(self): """ Rank the employees based on the year they're were hired. Since there are multiple employees hired in different years, this will contain gaps. """ qs = Employee.objects.annotate( rank=Window( expression=Rank(), order_by=F("hire_date__year").asc(), ) ) self.assertQuerysetEqual( qs, [ ("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 1), ("Miller", 100000, "Management", datetime.date(2005, 6, 1), 1), ("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 1), ("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 4), ("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 5), ("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 6), ("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 6), ("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 6), ("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 9), ("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 10), ("Moore", 34000, "IT", datetime.date(2013, 8, 1), 11), ("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 11), ], lambda entry: ( entry.name, entry.salary, entry.department, entry.hire_date, entry.rank, ), ordered=False, ) def test_row_number(self): """ The row number window function computes the number based on the order in which the tuples were inserted. Depending on the backend, Oracle requires an ordering-clause in the Window expression. """ qs = Employee.objects.annotate( row_number=Window( expression=RowNumber(), order_by=F("pk").asc(), ) ).order_by("pk") self.assertQuerysetEqual( qs, [ ("Jones", "Accounting", 1), ("Williams", "Accounting", 2), ("Jenson", "Accounting", 3), ("Adams", "Accounting", 4), ("Smith", "Sales", 5), ("Brown", "Sales", 6), ("Johnson", "Marketing", 7), ("Smith", "Marketing", 8), ("Wilkinson", "IT", 9), ("Moore", "IT", 10), ("Miller", "Management", 11), ("Johnson", "Management", 12), ], lambda entry: (entry.name, entry.department, entry.row_number), ) def test_row_number_no_ordering(self): """ The row number window function computes the number based on the order in which the tuples were inserted. """ # Add a default ordering for consistent results across databases. qs = Employee.objects.annotate( row_number=Window( expression=RowNumber(), ) ).order_by("pk") self.assertQuerysetEqual( qs, [ ("Jones", "Accounting", 1), ("Williams", "Accounting", 2), ("Jenson", "Accounting", 3), ("Adams", "Accounting", 4), ("Smith", "Sales", 5), ("Brown", "Sales", 6), ("Johnson", "Marketing", 7), ("Smith", "Marketing", 8), ("Wilkinson", "IT", 9), ("Moore", "IT", 10), ("Miller", "Management", 11), ("Johnson", "Management", 12), ], lambda entry: (entry.name, entry.department, entry.row_number), ) def test_avg_salary_department(self): qs = Employee.objects.annotate( avg_salary=Window( expression=Avg("salary"), order_by=F("department").asc(), partition_by="department", ) ).order_by("department", "-salary", "name") self.assertQuerysetEqual( qs, [ ("Adams", 50000, "Accounting", 44250.00), ("Jenson", 45000, "Accounting", 44250.00), ("Jones", 45000, "Accounting", 44250.00), ("Williams", 37000, "Accounting", 44250.00), ("Wilkinson", 60000, "IT", 47000.00), ("Moore", 34000, "IT", 47000.00), ("Miller", 100000, "Management", 90000.00), ("Johnson", 80000, "Management", 90000.00), ("Johnson", 40000, "Marketing", 39000.00), ("Smith", 38000, "Marketing", 39000.00), ("Smith", 55000, "Sales", 54000.00), ("Brown", 53000, "Sales", 54000.00), ], transform=lambda row: ( row.name, row.salary, row.department, row.avg_salary, ), ) def test_lag(self): """ Compute the difference between an employee's salary and the next highest salary in the employee's department. Return None if the employee has the lowest salary. """ qs = Employee.objects.annotate( lag=Window( expression=Lag(expression="salary", offset=1), partition_by=F("department"), order_by=[F("salary").asc(), F("name").asc()], ) ).order_by("department", F("salary").asc(), F("name").asc()) self.assertQuerysetEqual( qs, [ ("Williams", 37000, "Accounting", None), ("Jenson", 45000, "Accounting", 37000), ("Jones", 45000, "Accounting", 45000), ("Adams", 50000, "Accounting", 45000), ("Moore", 34000, "IT", None), ("Wilkinson", 60000, "IT", 34000), ("Johnson", 80000, "Management", None), ("Miller", 100000, "Management", 80000), ("Smith", 38000, "Marketing", None), ("Johnson", 40000, "Marketing", 38000), ("Brown", 53000, "Sales", None), ("Smith", 55000, "Sales", 53000), ], transform=lambda row: (row.name, row.salary, row.department, row.lag), ) def test_lag_decimalfield(self): qs = Employee.objects.annotate( lag=Window( expression=Lag(expression="bonus", offset=1), partition_by=F("department"), order_by=[F("bonus").asc(), F("name").asc()], ) ).order_by("department", F("bonus").asc(), F("name").asc()) self.assertQuerysetEqual( qs, [ ("Williams", 92.5, "Accounting", None), ("Jenson", 112.5, "Accounting", 92.5), ("Jones", 112.5, "Accounting", 112.5), ("Adams", 125, "Accounting", 112.5), ("Moore", 85, "IT", None), ("Wilkinson", 150, "IT", 85), ("Johnson", 200, "Management", None), ("Miller", 250, "Management", 200), ("Smith", 95, "Marketing", None), ("Johnson", 100, "Marketing", 95), ("Brown", 132.5, "Sales", None), ("Smith", 137.5, "Sales", 132.5), ], transform=lambda row: (row.name, row.bonus, row.department, row.lag), ) def test_first_value(self): qs = Employee.objects.annotate( first_value=Window( expression=FirstValue("salary"), partition_by=F("department"), order_by=F("hire_date").asc(), ) ).order_by("department", "hire_date") self.assertQuerysetEqual( qs, [ ("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 45000), ("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 45000), ("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 45000), ("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 45000), ("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 60000), ("Moore", 34000, "IT", datetime.date(2013, 8, 1), 60000), ("Miller", 100000, "Management", datetime.date(2005, 6, 1), 100000), ("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 100000), ("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 38000), ("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 38000), ("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 55000), ("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 55000), ], lambda row: ( row.name, row.salary, row.department, row.hire_date, row.first_value, ), ) def test_last_value(self): qs = Employee.objects.annotate( last_value=Window( expression=LastValue("hire_date"), partition_by=F("department"), order_by=F("hire_date").asc(), ) ) self.assertQuerysetEqual( qs, [ ( "Adams", "Accounting", datetime.date(2013, 7, 1), 50000, datetime.date(2013, 7, 1), ), ( "Jenson", "Accounting", datetime.date(2008, 4, 1), 45000, datetime.date(2008, 4, 1), ), ( "Jones", "Accounting", datetime.date(2005, 11, 1), 45000, datetime.date(2005, 11, 1), ), ( "Williams", "Accounting", datetime.date(2009, 6, 1), 37000, datetime.date(2009, 6, 1), ), ( "Moore", "IT", datetime.date(2013, 8, 1), 34000, datetime.date(2013, 8, 1), ), ( "Wilkinson", "IT", datetime.date(2011, 3, 1), 60000, datetime.date(2011, 3, 1), ), ( "Miller", "Management", datetime.date(2005, 6, 1), 100000, datetime.date(2005, 6, 1), ), ( "Johnson", "Management", datetime.date(2005, 7, 1), 80000, datetime.date(2005, 7, 1), ), ( "Johnson", "Marketing", datetime.date(2012, 3, 1), 40000, datetime.date(2012, 3, 1), ), ( "Smith", "Marketing", datetime.date(2009, 10, 1), 38000, datetime.date(2009, 10, 1), ), ( "Brown", "Sales", datetime.date(2009, 9, 1), 53000, datetime.date(2009, 9, 1), ), ( "Smith", "Sales", datetime.date(2007, 6, 1), 55000, datetime.date(2007, 6, 1), ), ], transform=lambda row: ( row.name, row.department, row.hire_date, row.salary, row.last_value, ), ordered=False, ) def test_function_list_of_values(self): qs = ( Employee.objects.annotate( lead=Window( expression=Lead(expression="salary"), order_by=[F("hire_date").asc(), F("name").desc()], partition_by="department", ) ) .values_list("name", "salary", "department", "hire_date", "lead") .order_by("department", F("hire_date").asc(), F("name").desc()) ) self.assertNotIn("GROUP BY", str(qs.query)) self.assertSequenceEqual( qs, [ ("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 45000), ("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 37000), ("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 50000), ("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), None), ("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 34000), ("Moore", 34000, "IT", datetime.date(2013, 8, 1), None), ("Miller", 100000, "Management", datetime.date(2005, 6, 1), 80000), ("Johnson", 80000, "Management", datetime.date(2005, 7, 1), None), ("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 40000), ("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), None), ("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 53000), ("Brown", 53000, "Sales", datetime.date(2009, 9, 1), None), ], ) def test_min_department(self): """An alternative way to specify a query for FirstValue.""" qs = Employee.objects.annotate( min_salary=Window( expression=Min("salary"), partition_by=F("department"), order_by=[F("salary").asc(), F("name").asc()], ) ).order_by("department", "salary", "name") self.assertQuerysetEqual( qs, [ ("Williams", "Accounting", 37000, 37000), ("Jenson", "Accounting", 45000, 37000), ("Jones", "Accounting", 45000, 37000), ("Adams", "Accounting", 50000, 37000), ("Moore", "IT", 34000, 34000), ("Wilkinson", "IT", 60000, 34000), ("Johnson", "Management", 80000, 80000), ("Miller", "Management", 100000, 80000), ("Smith", "Marketing", 38000, 38000), ("Johnson", "Marketing", 40000, 38000), ("Brown", "Sales", 53000, 53000), ("Smith", "Sales", 55000, 53000), ], lambda row: (row.name, row.department, row.salary, row.min_salary), ) def test_max_per_year(self): """ Find the maximum salary awarded in the same year as the employee was hired, regardless of the department. """ qs = Employee.objects.annotate( max_salary_year=Window( expression=Max("salary"), order_by=ExtractYear("hire_date").asc(), partition_by=ExtractYear("hire_date"), ) ).order_by(ExtractYear("hire_date"), "salary") self.assertQuerysetEqual( qs, [ ("Jones", "Accounting", 45000, 2005, 100000), ("Johnson", "Management", 80000, 2005, 100000), ("Miller", "Management", 100000, 2005, 100000), ("Smith", "Sales", 55000, 2007, 55000), ("Jenson", "Accounting", 45000, 2008, 45000), ("Williams", "Accounting", 37000, 2009, 53000), ("Smith", "Marketing", 38000, 2009, 53000), ("Brown", "Sales", 53000, 2009, 53000), ("Wilkinson", "IT", 60000, 2011, 60000), ("Johnson", "Marketing", 40000, 2012, 40000), ("Moore", "IT", 34000, 2013, 50000), ("Adams", "Accounting", 50000, 2013, 50000), ], lambda row: ( row.name, row.department, row.salary, row.hire_date.year, row.max_salary_year, ), ) def test_cume_dist(self): """ Compute the cumulative distribution for the employees based on the salary in increasing order. Equal to rank/total number of rows (12). """ qs = Employee.objects.annotate( cume_dist=Window( expression=CumeDist(), order_by=F("salary").asc(), ) ).order_by("salary", "name") # Round result of cume_dist because Oracle uses greater precision. self.assertQuerysetEqual( qs, [ ("Moore", "IT", 34000, 0.0833333333), ("Williams", "Accounting", 37000, 0.1666666667), ("Smith", "Marketing", 38000, 0.25), ("Johnson", "Marketing", 40000, 0.3333333333), ("Jenson", "Accounting", 45000, 0.5), ("Jones", "Accounting", 45000, 0.5), ("Adams", "Accounting", 50000, 0.5833333333), ("Brown", "Sales", 53000, 0.6666666667), ("Smith", "Sales", 55000, 0.75), ("Wilkinson", "IT", 60000, 0.8333333333), ("Johnson", "Management", 80000, 0.9166666667), ("Miller", "Management", 100000, 1), ], lambda row: ( row.name, row.department, row.salary, round(row.cume_dist, 10), ), ) def test_nthvalue(self): qs = Employee.objects.annotate( nth_value=Window( expression=NthValue(expression="salary", nth=2), order_by=[F("hire_date").asc(), F("name").desc()], partition_by=F("department"), ) ).order_by("department", "hire_date", "name") self.assertQuerysetEqual( qs, [ ("Jones", "Accounting", datetime.date(2005, 11, 1), 45000, None), ("Jenson", "Accounting", datetime.date(2008, 4, 1), 45000, 45000), ("Williams", "Accounting", datetime.date(2009, 6, 1), 37000, 45000), ("Adams", "Accounting", datetime.date(2013, 7, 1), 50000, 45000), ("Wilkinson", "IT", datetime.date(2011, 3, 1), 60000, None), ("Moore", "IT", datetime.date(2013, 8, 1), 34000, 34000), ("Miller", "Management", datetime.date(2005, 6, 1), 100000, None), ("Johnson", "Management", datetime.date(2005, 7, 1), 80000, 80000), ("Smith", "Marketing", datetime.date(2009, 10, 1), 38000, None), ("Johnson", "Marketing", datetime.date(2012, 3, 1), 40000, 40000), ("Smith", "Sales", datetime.date(2007, 6, 1), 55000, None), ("Brown", "Sales", datetime.date(2009, 9, 1), 53000, 53000), ], lambda row: ( row.name, row.department, row.hire_date, row.salary, row.nth_value, ), ) def test_lead(self): """ Determine what the next person hired in the same department makes. Because the dataset is ambiguous, the name is also part of the ordering clause. No default is provided, so None/NULL should be returned. """ qs = Employee.objects.annotate( lead=Window( expression=Lead(expression="salary"), order_by=[F("hire_date").asc(), F("name").desc()], partition_by="department", ) ).order_by("department", F("hire_date").asc(), F("name").desc()) self.assertQuerysetEqual( qs, [ ("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 45000), ("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 37000), ("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 50000), ("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), None), ("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 34000), ("Moore", 34000, "IT", datetime.date(2013, 8, 1), None), ("Miller", 100000, "Management", datetime.date(2005, 6, 1), 80000), ("Johnson", 80000, "Management", datetime.date(2005, 7, 1), None), ("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 40000), ("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), None), ("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 53000), ("Brown", 53000, "Sales", datetime.date(2009, 9, 1), None), ], transform=lambda row: ( row.name, row.salary, row.department, row.hire_date, row.lead, ), ) def test_lead_offset(self): """ Determine what the person hired after someone makes. Due to ambiguity, the name is also included in the ordering. """ qs = Employee.objects.annotate( lead=Window( expression=Lead("salary", offset=2), partition_by="department", order_by=F("hire_date").asc(), ) ) self.assertQuerysetEqual( qs, [ ("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 37000), ("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 50000), ("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), None), ("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), None), ("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), None), ("Moore", 34000, "IT", datetime.date(2013, 8, 1), None), ("Johnson", 80000, "Management", datetime.date(2005, 7, 1), None), ("Miller", 100000, "Management", datetime.date(2005, 6, 1), None), ("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), None), ("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), None), ("Smith", 55000, "Sales", datetime.date(2007, 6, 1), None), ("Brown", 53000, "Sales", datetime.date(2009, 9, 1), None), ], transform=lambda row: ( row.name, row.salary, row.department, row.hire_date, row.lead, ), ordered=False, ) @skipUnlessDBFeature("supports_default_in_lead_lag") def test_lead_default(self): qs = Employee.objects.annotate( lead_default=Window( expression=Lead(expression="salary", offset=5, default=60000), partition_by=F("department"), order_by=F("department").asc(), ) ) self.assertEqual( list(qs.values_list("lead_default", flat=True).distinct()), [60000] ) def test_ntile(self): """ Compute the group for each of the employees across the entire company, based on how high the salary is for them. There are twelve employees so it divides evenly into four groups. """ qs = Employee.objects.annotate( ntile=Window( expression=Ntile(num_buckets=4), order_by="-salary", ) ).order_by("ntile", "-salary", "name") self.assertQuerysetEqual( qs, [ ("Miller", "Management", 100000, 1), ("Johnson", "Management", 80000, 1), ("Wilkinson", "IT", 60000, 1), ("Smith", "Sales", 55000, 2), ("Brown", "Sales", 53000, 2), ("Adams", "Accounting", 50000, 2), ("Jenson", "Accounting", 45000, 3), ("Jones", "Accounting", 45000, 3), ("Johnson", "Marketing", 40000, 3), ("Smith", "Marketing", 38000, 4), ("Williams", "Accounting", 37000, 4), ("Moore", "IT", 34000, 4), ], lambda x: (x.name, x.department, x.salary, x.ntile), ) def test_percent_rank(self): """ Calculate the percentage rank of the employees across the entire company based on salary and name (in case of ambiguity). """ qs = Employee.objects.annotate( percent_rank=Window( expression=PercentRank(), order_by=[F("salary").asc(), F("name").asc()], ) ).order_by("percent_rank") # Round to account for precision differences among databases. self.assertQuerysetEqual( qs, [ ("Moore", "IT", 34000, 0.0), ("Williams", "Accounting", 37000, 0.0909090909), ("Smith", "Marketing", 38000, 0.1818181818), ("Johnson", "Marketing", 40000, 0.2727272727), ("Jenson", "Accounting", 45000, 0.3636363636), ("Jones", "Accounting", 45000, 0.4545454545), ("Adams", "Accounting", 50000, 0.5454545455), ("Brown", "Sales", 53000, 0.6363636364), ("Smith", "Sales", 55000, 0.7272727273), ("Wilkinson", "IT", 60000, 0.8181818182), ("Johnson", "Management", 80000, 0.9090909091), ("Miller", "Management", 100000, 1.0), ], transform=lambda row: ( row.name, row.department, row.salary, round(row.percent_rank, 10), ), ) def test_nth_returns_null(self): """ Find the nth row of the data set. None is returned since there are fewer than 20 rows in the test data. """ qs = Employee.objects.annotate( nth_value=Window( expression=NthValue("salary", nth=20), order_by=F("salary").asc() ) ) self.assertEqual( list(qs.values_list("nth_value", flat=True).distinct()), [None] ) def test_multiple_partitioning(self): """ Find the maximum salary for each department for people hired in the same year. """ qs = Employee.objects.annotate( max=Window( expression=Max("salary"), partition_by=[F("department"), F("hire_date__year")], ) ).order_by("department", "hire_date", "name") self.assertQuerysetEqual( qs, [ ("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 45000), ("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 45000), ("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 37000), ("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 50000), ("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 60000), ("Moore", 34000, "IT", datetime.date(2013, 8, 1), 34000), ("Miller", 100000, "Management", datetime.date(2005, 6, 1), 100000), ("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 100000), ("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 38000), ("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 40000), ("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 55000), ("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 53000), ], transform=lambda row: ( row.name, row.salary, row.department, row.hire_date, row.max, ), ) def test_multiple_ordering(self): """ Accumulate the salaries over the departments based on hire_date. If two people were hired on the same date in the same department, the ordering clause will render a different result for those people. """ qs = Employee.objects.annotate( sum=Window( expression=Sum("salary"), partition_by="department", order_by=[F("hire_date").asc(), F("name").asc()], ) ).order_by("department", "sum") self.assertQuerysetEqual( qs, [ ("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 45000), ("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 90000), ("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 127000), ("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 177000), ("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 60000), ("Moore", 34000, "IT", datetime.date(2013, 8, 1), 94000), ("Miller", 100000, "Management", datetime.date(2005, 6, 1), 100000), ("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 180000), ("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 38000), ("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 78000), ("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 55000), ("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 108000), ], transform=lambda row: ( row.name, row.salary, row.department, row.hire_date, row.sum, ), ) def test_related_ordering_with_count(self): qs = Employee.objects.annotate( department_sum=Window( expression=Sum("salary"), partition_by=F("department"), order_by=["classification__code"], ) ) self.assertEqual(qs.count(), 12) @skipUnlessDBFeature("supports_frame_range_fixed_distance") def test_range_n_preceding_and_following(self): qs = Employee.objects.annotate( sum=Window( expression=Sum("salary"), order_by=F("salary").asc(), partition_by="department", frame=ValueRange(start=-2, end=2), ) ) self.assertIn("RANGE BETWEEN 2 PRECEDING AND 2 FOLLOWING", str(qs.query)) self.assertQuerysetEqual( qs, [ ("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 37000), ("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 90000), ("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 90000), ("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 50000), ("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 53000), ("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 55000), ("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 40000), ("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 38000), ("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 60000), ("Moore", 34000, "IT", datetime.date(2013, 8, 1), 34000), ("Miller", 100000, "Management", datetime.date(2005, 6, 1), 100000), ("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 80000), ], transform=lambda row: ( row.name, row.salary, row.department, row.hire_date, row.sum, ), ordered=False, ) def test_range_unbound(self): """A query with RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING.""" qs = Employee.objects.annotate( sum=Window( expression=Sum("salary"), partition_by="age", order_by=[F("age").asc()], frame=ValueRange(start=None, end=None), ) ).order_by("department", "hire_date", "name") self.assertIn( "RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING", str(qs.query) ) self.assertQuerysetEqual( qs, [ ("Jones", "Accounting", 45000, datetime.date(2005, 11, 1), 165000), ("Jenson", "Accounting", 45000, datetime.date(2008, 4, 1), 165000), ("Williams", "Accounting", 37000, datetime.date(2009, 6, 1), 165000), ("Adams", "Accounting", 50000, datetime.date(2013, 7, 1), 130000), ("Wilkinson", "IT", 60000, datetime.date(2011, 3, 1), 194000), ("Moore", "IT", 34000, datetime.date(2013, 8, 1), 194000), ("Miller", "Management", 100000, datetime.date(2005, 6, 1), 194000), ("Johnson", "Management", 80000, datetime.date(2005, 7, 1), 130000), ("Smith", "Marketing", 38000, datetime.date(2009, 10, 1), 165000), ("Johnson", "Marketing", 40000, datetime.date(2012, 3, 1), 148000), ("Smith", "Sales", 55000, datetime.date(2007, 6, 1), 148000), ("Brown", "Sales", 53000, datetime.date(2009, 9, 1), 148000), ], transform=lambda row: ( row.name, row.department, row.salary, row.hire_date, row.sum, ), ) def test_subquery_row_range_rank(self): qs = Employee.objects.annotate( highest_avg_salary_date=Subquery( Employee.objects.filter( department=OuterRef("department"), ) .annotate( avg_salary=Window( expression=Avg("salary"), order_by=[F("hire_date").asc()], frame=RowRange(start=-1, end=1), ), ) .order_by("-avg_salary", "hire_date") .values("hire_date")[:1], ), ).order_by("department", "name") self.assertQuerysetEqual( qs, [ ("Adams", "Accounting", datetime.date(2005, 11, 1)), ("Jenson", "Accounting", datetime.date(2005, 11, 1)), ("Jones", "Accounting", datetime.date(2005, 11, 1)), ("Williams", "Accounting", datetime.date(2005, 11, 1)), ("Moore", "IT", datetime.date(2011, 3, 1)), ("Wilkinson", "IT", datetime.date(2011, 3, 1)), ("Johnson", "Management", datetime.date(2005, 6, 1)), ("Miller", "Management", datetime.date(2005, 6, 1)), ("Johnson", "Marketing", datetime.date(2009, 10, 1)), ("Smith", "Marketing", datetime.date(2009, 10, 1)), ("Brown", "Sales", datetime.date(2007, 6, 1)), ("Smith", "Sales", datetime.date(2007, 6, 1)), ], transform=lambda row: ( row.name, row.department, row.highest_avg_salary_date, ), ) def test_row_range_rank(self): """ A query with ROWS BETWEEN UNBOUNDED PRECEDING AND 3 FOLLOWING. The resulting sum is the sum of the three next (if they exist) and all previous rows according to the ordering clause. """ qs = Employee.objects.annotate( sum=Window( expression=Sum("salary"), order_by=[F("hire_date").asc(), F("name").desc()], frame=RowRange(start=None, end=3), ) ).order_by("sum", "hire_date") self.assertIn("ROWS BETWEEN UNBOUNDED PRECEDING AND 3 FOLLOWING", str(qs.query)) self.assertQuerysetEqual( qs, [ ("Miller", 100000, "Management", datetime.date(2005, 6, 1), 280000), ("Johnson", 80000, "Management", datetime.date(2005, 7, 1), 325000), ("Jones", 45000, "Accounting", datetime.date(2005, 11, 1), 362000), ("Smith", 55000, "Sales", datetime.date(2007, 6, 1), 415000), ("Jenson", 45000, "Accounting", datetime.date(2008, 4, 1), 453000), ("Williams", 37000, "Accounting", datetime.date(2009, 6, 1), 513000), ("Brown", 53000, "Sales", datetime.date(2009, 9, 1), 553000), ("Smith", 38000, "Marketing", datetime.date(2009, 10, 1), 603000), ("Wilkinson", 60000, "IT", datetime.date(2011, 3, 1), 637000), ("Johnson", 40000, "Marketing", datetime.date(2012, 3, 1), 637000), ("Adams", 50000, "Accounting", datetime.date(2013, 7, 1), 637000), ("Moore", 34000, "IT", datetime.date(2013, 8, 1), 637000), ], transform=lambda row: ( row.name, row.salary, row.department, row.hire_date, row.sum, ), ) @skipUnlessDBFeature("can_distinct_on_fields") def test_distinct_window_function(self): """ Window functions are not aggregates, and hence a query to filter out duplicates may be useful. """ qs = ( Employee.objects.annotate( sum=Window( expression=Sum("salary"), partition_by=ExtractYear("hire_date"), order_by=ExtractYear("hire_date"), ), year=ExtractYear("hire_date"), ) .values("year", "sum") .distinct("year") .order_by("year") ) results = [ {"year": 2005, "sum": 225000}, {"year": 2007, "sum": 55000}, {"year": 2008, "sum": 45000}, {"year": 2009, "sum": 128000}, {"year": 2011, "sum": 60000}, {"year": 2012, "sum": 40000}, {"year": 2013, "sum": 84000}, ] for idx, val in zip(range(len(results)), results): with self.subTest(result=val): self.assertEqual(qs[idx], val) def test_fail_update(self): """Window expressions can't be used in an UPDATE statement.""" msg = ( "Window expressions are not allowed in this query (salary=<Window: " "Max(Col(expressions_window_employee, expressions_window.Employee.salary)) " "OVER (PARTITION BY Col(expressions_window_employee, " "expressions_window.Employee.department))>)." ) with self.assertRaisesMessage(FieldError, msg): Employee.objects.filter(department="Management").update( salary=Window(expression=Max("salary"), partition_by="department"), ) def test_fail_insert(self): """Window expressions can't be used in an INSERT statement.""" msg = ( "Window expressions are not allowed in this query (salary=<Window: " "Sum(Value(10000), order_by=OrderBy(F(pk), descending=False)) OVER ()" ) with self.assertRaisesMessage(FieldError, msg): Employee.objects.create( name="Jameson", department="Management", hire_date=datetime.date(2007, 7, 1), salary=Window(expression=Sum(Value(10000), order_by=F("pk").asc())), ) def test_window_expression_within_subquery(self): subquery_qs = Employee.objects.annotate( highest=Window( FirstValue("id"), partition_by=F("department"), order_by=F("salary").desc(), ) ).values("highest") highest_salary = Employee.objects.filter(pk__in=subquery_qs) self.assertCountEqual( highest_salary.values("department", "salary"), [ {"department": "Accounting", "salary": 50000}, {"department": "Sales", "salary": 55000}, {"department": "Marketing", "salary": 40000}, {"department": "IT", "salary": 60000}, {"department": "Management", "salary": 100000}, ], ) @skipUnlessDBFeature("supports_json_field") def test_key_transform(self): Detail.objects.bulk_create( [ Detail(value={"department": "IT", "name": "Smith", "salary": 37000}), Detail(value={"department": "IT", "name": "Nowak", "salary": 32000}), Detail(value={"department": "HR", "name": "Brown", "salary": 50000}), Detail(value={"department": "HR", "name": "Smith", "salary": 55000}), Detail(value={"department": "PR", "name": "Moore", "salary": 90000}), ] ) tests = [ (KeyTransform("department", "value"), KeyTransform("name", "value")), (F("value__department"), F("value__name")), ] for partition_by, order_by in tests: with self.subTest(partition_by=partition_by, order_by=order_by): qs = Detail.objects.annotate( department_sum=Window( expression=Sum( Cast( KeyTextTransform("salary", "value"), output_field=IntegerField(), ) ), partition_by=[partition_by], order_by=[order_by], ) ).order_by("value__department", "department_sum") self.assertQuerysetEqual( qs, [ ("Brown", "HR", 50000, 50000), ("Smith", "HR", 55000, 105000), ("Nowak", "IT", 32000, 32000), ("Smith", "IT", 37000, 69000), ("Moore", "PR", 90000, 90000), ], lambda entry: ( entry.value["name"], entry.value["department"], entry.value["salary"], entry.department_sum, ), ) def test_invalid_start_value_range(self): msg = "start argument must be a negative integer, zero, or None, but got '3'." with self.assertRaisesMessage(ValueError, msg): list( Employee.objects.annotate( test=Window( expression=Sum("salary"), order_by=F("hire_date").asc(), frame=ValueRange(start=3), ) ) ) def test_invalid_end_value_range(self): msg = "end argument must be a positive integer, zero, or None, but got '-3'." with self.assertRaisesMessage(ValueError, msg): list( Employee.objects.annotate( test=Window( expression=Sum("salary"), order_by=F("hire_date").asc(), frame=ValueRange(end=-3), ) ) ) def test_invalid_type_end_value_range(self): msg = "end argument must be a positive integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list( Employee.objects.annotate( test=Window( expression=Sum("salary"), order_by=F("hire_date").asc(), frame=ValueRange(end="a"), ) ) ) def test_invalid_type_start_value_range(self): msg = "start argument must be a negative integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list( Employee.objects.annotate( test=Window( expression=Sum("salary"), frame=ValueRange(start="a"), ) ) ) def test_invalid_type_end_row_range(self): msg = "end argument must be a positive integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list( Employee.objects.annotate( test=Window( expression=Sum("salary"), frame=RowRange(end="a"), ) ) ) @skipUnlessDBFeature("only_supports_unbounded_with_preceding_and_following") def test_unsupported_range_frame_start(self): msg = ( "%s only supports UNBOUNDED together with PRECEDING and FOLLOWING." % connection.display_name ) with self.assertRaisesMessage(NotSupportedError, msg): list( Employee.objects.annotate( test=Window( expression=Sum("salary"), order_by=F("hire_date").asc(), frame=ValueRange(start=-1), ) ) ) @skipUnlessDBFeature("only_supports_unbounded_with_preceding_and_following") def test_unsupported_range_frame_end(self): msg = ( "%s only supports UNBOUNDED together with PRECEDING and FOLLOWING." % connection.display_name ) with self.assertRaisesMessage(NotSupportedError, msg): list( Employee.objects.annotate( test=Window( expression=Sum("salary"), order_by=F("hire_date").asc(), frame=ValueRange(end=1), ) ) ) def test_invalid_type_start_row_range(self): msg = "start argument must be a negative integer, zero, or None, but got 'a'." with self.assertRaisesMessage(ValueError, msg): list( Employee.objects.annotate( test=Window( expression=Sum("salary"), order_by=F("hire_date").asc(), frame=RowRange(start="a"), ) ) ) class WindowUnsupportedTests(TestCase): def test_unsupported_backend(self): msg = "This backend does not support window expressions." with mock.patch.object(connection.features, "supports_over_clause", False): with self.assertRaisesMessage(NotSupportedError, msg): Employee.objects.annotate( dense_rank=Window(expression=DenseRank()) ).get() class NonQueryWindowTests(SimpleTestCase): def test_window_repr(self): self.assertEqual( repr(Window(expression=Sum("salary"), partition_by="department")), "<Window: Sum(F(salary)) OVER (PARTITION BY F(department))>", ) self.assertEqual( repr(Window(expression=Avg("salary"), order_by=F("department").asc())), "<Window: Avg(F(salary)) OVER (OrderByList(OrderBy(F(department), " "descending=False)))>", ) def test_window_frame_repr(self): self.assertEqual( repr(RowRange(start=-1)), "<RowRange: ROWS BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING>", ) self.assertEqual( repr(ValueRange(start=None, end=1)), "<ValueRange: RANGE BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING>", ) self.assertEqual( repr(ValueRange(start=0, end=0)), "<ValueRange: RANGE BETWEEN CURRENT ROW AND CURRENT ROW>", ) self.assertEqual( repr(RowRange(start=0, end=0)), "<RowRange: ROWS BETWEEN CURRENT ROW AND CURRENT ROW>", ) def test_empty_group_by_cols(self): window = Window(expression=Sum("pk")) self.assertEqual(window.get_group_by_cols(), []) self.assertFalse(window.contains_aggregate) def test_frame_empty_group_by_cols(self): frame = WindowFrame() self.assertEqual(frame.get_group_by_cols(), []) def test_frame_window_frame_notimplemented(self): frame = WindowFrame() msg = "Subclasses must implement window_frame_start_end()." with self.assertRaisesMessage(NotImplementedError, msg): frame.window_frame_start_end(None, None, None) def test_invalid_filter(self): msg = "Window is disallowed in the filter clause" qs = Employee.objects.annotate(dense_rank=Window(expression=DenseRank())) with self.assertRaisesMessage(NotSupportedError, msg): qs.filter(dense_rank__gte=1) with self.assertRaisesMessage(NotSupportedError, msg): qs.annotate(inc_rank=F("dense_rank") + Value(1)).filter(inc_rank__gte=1) with self.assertRaisesMessage(NotSupportedError, msg): qs.filter(id=F("dense_rank")) with self.assertRaisesMessage(NotSupportedError, msg): qs.filter(id=Func("dense_rank", 2, function="div")) with self.assertRaisesMessage(NotSupportedError, msg): qs.annotate(total=Sum("dense_rank", filter=Q(name="Jones"))).filter(total=1) def test_conditional_annotation(self): qs = Employee.objects.annotate( dense_rank=Window(expression=DenseRank()), ).annotate( equal=Case( When(id=F("dense_rank"), then=Value(True)), default=Value(False), output_field=BooleanField(), ), ) # The SQL standard disallows referencing window functions in the WHERE # clause. msg = "Window is disallowed in the filter clause" with self.assertRaisesMessage(NotSupportedError, msg): qs.filter(equal=True) def test_invalid_order_by(self): msg = ( "Window.order_by must be either a string reference to a field, an " "expression, or a list or tuple of them." ) with self.assertRaisesMessage(ValueError, msg): Window(expression=Sum("power"), order_by={"-horse"}) def test_invalid_source_expression(self): msg = "Expression 'Upper' isn't compatible with OVER clauses." with self.assertRaisesMessage(ValueError, msg): Window(expression=Upper("name"))
126f1ef19de09ef214ea11268222b2fed4cb1365a4c096545067e9e906ace790
from django.db import models class Classification(models.Model): code = models.CharField(max_length=10) class Employee(models.Model): name = models.CharField(max_length=40, blank=False, null=False) salary = models.PositiveIntegerField() department = models.CharField(max_length=40, blank=False, null=False) hire_date = models.DateField(blank=False, null=False) age = models.IntegerField(blank=False, null=False) classification = models.ForeignKey( "Classification", on_delete=models.CASCADE, null=True ) bonus = models.DecimalField(decimal_places=2, max_digits=15, null=True) class Detail(models.Model): value = models.JSONField() class Meta: required_db_features = {"supports_json_field"}
69b23d5ab6ec9370acaa2da9f2a0f863659d37af4add9ca39dc94c50d6c9be4a
from datetime import datetime from operator import attrgetter from django.db.models import ( CharField, Count, DateTimeField, F, Max, OuterRef, Subquery, Value, ) from django.db.models.functions import Upper from django.test import TestCase from .models import Article, Author, ChildArticle, OrderedByFArticle, Reference class OrderingTests(TestCase): @classmethod def setUpTestData(cls): cls.a1 = Article.objects.create( headline="Article 1", pub_date=datetime(2005, 7, 26) ) cls.a2 = Article.objects.create( headline="Article 2", pub_date=datetime(2005, 7, 27) ) cls.a3 = Article.objects.create( headline="Article 3", pub_date=datetime(2005, 7, 27) ) cls.a4 = Article.objects.create( headline="Article 4", pub_date=datetime(2005, 7, 28) ) cls.author_1 = Author.objects.create(name="Name 1") cls.author_2 = Author.objects.create(name="Name 2") for i in range(2): Author.objects.create() def test_default_ordering(self): """ By default, Article.objects.all() orders by pub_date descending, then headline ascending. """ self.assertQuerysetEqual( Article.objects.all(), [ "Article 4", "Article 2", "Article 3", "Article 1", ], attrgetter("headline"), ) # Getting a single item should work too: self.assertEqual(Article.objects.all()[0], self.a4) def test_default_ordering_override(self): """ Override ordering with order_by, which is in the same format as the ordering attribute in models. """ self.assertQuerysetEqual( Article.objects.order_by("headline"), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline"), ) self.assertQuerysetEqual( Article.objects.order_by("pub_date", "-headline"), [ "Article 1", "Article 3", "Article 2", "Article 4", ], attrgetter("headline"), ) def test_order_by_override(self): """ Only the last order_by has any effect (since they each override any previous ordering). """ self.assertQuerysetEqual( Article.objects.order_by("id"), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline"), ) self.assertQuerysetEqual( Article.objects.order_by("id").order_by("-headline"), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline"), ) def test_order_by_nulls_first_and_last(self): msg = "nulls_first and nulls_last are mutually exclusive" with self.assertRaisesMessage(ValueError, msg): Article.objects.order_by( F("author").desc(nulls_last=True, nulls_first=True) ) def assertQuerysetEqualReversible(self, queryset, sequence): self.assertSequenceEqual(queryset, sequence) self.assertSequenceEqual(queryset.reverse(), list(reversed(sequence))) def test_order_by_nulls_last(self): Article.objects.filter(headline="Article 3").update(author=self.author_1) Article.objects.filter(headline="Article 4").update(author=self.author_2) # asc and desc are chainable with nulls_last. self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").desc(nulls_last=True), "headline"), [self.a4, self.a3, self.a1, self.a2], ) self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").asc(nulls_last=True), "headline"), [self.a3, self.a4, self.a1, self.a2], ) self.assertQuerysetEqualReversible( Article.objects.order_by( Upper("author__name").desc(nulls_last=True), "headline" ), [self.a4, self.a3, self.a1, self.a2], ) self.assertQuerysetEqualReversible( Article.objects.order_by( Upper("author__name").asc(nulls_last=True), "headline" ), [self.a3, self.a4, self.a1, self.a2], ) def test_order_by_nulls_first(self): Article.objects.filter(headline="Article 3").update(author=self.author_1) Article.objects.filter(headline="Article 4").update(author=self.author_2) # asc and desc are chainable with nulls_first. self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").asc(nulls_first=True), "headline"), [self.a1, self.a2, self.a3, self.a4], ) self.assertQuerysetEqualReversible( Article.objects.order_by(F("author").desc(nulls_first=True), "headline"), [self.a1, self.a2, self.a4, self.a3], ) self.assertQuerysetEqualReversible( Article.objects.order_by( Upper("author__name").asc(nulls_first=True), "headline" ), [self.a1, self.a2, self.a3, self.a4], ) self.assertQuerysetEqualReversible( Article.objects.order_by( Upper("author__name").desc(nulls_first=True), "headline" ), [self.a1, self.a2, self.a4, self.a3], ) def test_orders_nulls_first_on_filtered_subquery(self): Article.objects.filter(headline="Article 1").update(author=self.author_1) Article.objects.filter(headline="Article 2").update(author=self.author_1) Article.objects.filter(headline="Article 4").update(author=self.author_2) Author.objects.filter(name__isnull=True).delete() author_3 = Author.objects.create(name="Name 3") article_subquery = ( Article.objects.filter( author=OuterRef("pk"), headline__icontains="Article", ) .order_by() .values("author") .annotate( last_date=Max("pub_date"), ) .values("last_date") ) self.assertQuerysetEqualReversible( Author.objects.annotate( last_date=Subquery(article_subquery, output_field=DateTimeField()) ) .order_by(F("last_date").asc(nulls_first=True)) .distinct(), [author_3, self.author_1, self.author_2], ) def test_stop_slicing(self): """ Use the 'stop' part of slicing notation to limit the results. """ self.assertQuerysetEqual( Article.objects.order_by("headline")[:2], [ "Article 1", "Article 2", ], attrgetter("headline"), ) def test_stop_start_slicing(self): """ Use the 'stop' and 'start' parts of slicing notation to offset the result list. """ self.assertQuerysetEqual( Article.objects.order_by("headline")[1:3], [ "Article 2", "Article 3", ], attrgetter("headline"), ) def test_random_ordering(self): """ Use '?' to order randomly. """ self.assertEqual(len(list(Article.objects.order_by("?"))), 4) def test_reversed_ordering(self): """ Ordering can be reversed using the reverse() method on a queryset. This allows you to extract things like "the last two items" (reverse and then take the first two). """ self.assertQuerysetEqual( Article.objects.reverse()[:2], [ "Article 1", "Article 3", ], attrgetter("headline"), ) def test_reverse_ordering_pure(self): qs1 = Article.objects.order_by(F("headline").asc()) qs2 = qs1.reverse() self.assertQuerysetEqual( qs2, [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline"), ) self.assertQuerysetEqual( qs1, [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline"), ) def test_reverse_meta_ordering_pure(self): Article.objects.create( headline="Article 5", pub_date=datetime(2005, 7, 30), author=self.author_1, second_author=self.author_2, ) Article.objects.create( headline="Article 5", pub_date=datetime(2005, 7, 30), author=self.author_2, second_author=self.author_1, ) self.assertQuerysetEqual( Article.objects.filter(headline="Article 5").reverse(), ["Name 2", "Name 1"], attrgetter("author.name"), ) self.assertQuerysetEqual( Article.objects.filter(headline="Article 5"), ["Name 1", "Name 2"], attrgetter("author.name"), ) def test_no_reordering_after_slicing(self): msg = "Cannot reverse a query once a slice has been taken." qs = Article.objects.all()[0:2] with self.assertRaisesMessage(TypeError, msg): qs.reverse() with self.assertRaisesMessage(TypeError, msg): qs.last() def test_extra_ordering(self): """ Ordering can be based on fields included from an 'extra' clause """ self.assertQuerysetEqual( Article.objects.extra( select={"foo": "pub_date"}, order_by=["foo", "headline"] ), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline"), ) def test_extra_ordering_quoting(self): """ If the extra clause uses an SQL keyword for a name, it will be protected by quoting. """ self.assertQuerysetEqual( Article.objects.extra( select={"order": "pub_date"}, order_by=["order", "headline"] ), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline"), ) def test_extra_ordering_with_table_name(self): self.assertQuerysetEqual( Article.objects.extra(order_by=["ordering_article.headline"]), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline"), ) self.assertQuerysetEqual( Article.objects.extra(order_by=["-ordering_article.headline"]), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline"), ) def test_order_by_pk(self): """ 'pk' works as an ordering option in Meta. """ self.assertEqual( [a.pk for a in Author.objects.all()], [a.pk for a in Author.objects.order_by("-pk")], ) def test_order_by_fk_attname(self): """ ordering by a foreign key by its attribute name prevents the query from inheriting its related model ordering option (#19195). """ authors = list(Author.objects.order_by("id")) for i in range(1, 5): author = authors[i - 1] article = getattr(self, "a%d" % (5 - i)) article.author = author article.save(update_fields={"author"}) self.assertQuerysetEqual( Article.objects.order_by("author_id"), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline"), ) def test_order_by_self_referential_fk(self): self.a1.author = Author.objects.create(editor=self.author_1) self.a1.save() self.a2.author = Author.objects.create(editor=self.author_2) self.a2.save() self.assertQuerysetEqual( Article.objects.filter(author__isnull=False).order_by("author__editor"), ["Article 2", "Article 1"], attrgetter("headline"), ) self.assertQuerysetEqual( Article.objects.filter(author__isnull=False).order_by("author__editor_id"), ["Article 1", "Article 2"], attrgetter("headline"), ) def test_order_by_f_expression(self): self.assertQuerysetEqual( Article.objects.order_by(F("headline")), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline"), ) self.assertQuerysetEqual( Article.objects.order_by(F("headline").asc()), [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline"), ) self.assertQuerysetEqual( Article.objects.order_by(F("headline").desc()), [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline"), ) def test_order_by_f_expression_duplicates(self): """ A column may only be included once (the first occurrence) so we check to ensure there are no duplicates by inspecting the SQL. """ qs = Article.objects.order_by(F("headline").asc(), F("headline").desc()) sql = str(qs.query).upper() fragment = sql[sql.find("ORDER BY") :] self.assertEqual(fragment.count("HEADLINE"), 1) self.assertQuerysetEqual( qs, [ "Article 1", "Article 2", "Article 3", "Article 4", ], attrgetter("headline"), ) qs = Article.objects.order_by(F("headline").desc(), F("headline").asc()) sql = str(qs.query).upper() fragment = sql[sql.find("ORDER BY") :] self.assertEqual(fragment.count("HEADLINE"), 1) self.assertQuerysetEqual( qs, [ "Article 4", "Article 3", "Article 2", "Article 1", ], attrgetter("headline"), ) def test_order_by_constant_value(self): # Order by annotated constant from selected columns. qs = Article.objects.annotate( constant=Value("1", output_field=CharField()), ).order_by("constant", "-headline") self.assertSequenceEqual(qs, [self.a4, self.a3, self.a2, self.a1]) # Order by annotated constant which is out of selected columns. self.assertSequenceEqual( qs.values_list("headline", flat=True), [ "Article 4", "Article 3", "Article 2", "Article 1", ], ) # Order by constant. qs = Article.objects.order_by(Value("1", output_field=CharField()), "-headline") self.assertSequenceEqual(qs, [self.a4, self.a3, self.a2, self.a1]) def test_related_ordering_duplicate_table_reference(self): """ An ordering referencing a model with an ordering referencing a model multiple time no circular reference should be detected (#24654). """ first_author = Author.objects.create() second_author = Author.objects.create() self.a1.author = first_author self.a1.second_author = second_author self.a1.save() self.a2.author = second_author self.a2.second_author = first_author self.a2.save() r1 = Reference.objects.create(article_id=self.a1.pk) r2 = Reference.objects.create(article_id=self.a2.pk) self.assertSequenceEqual(Reference.objects.all(), [r2, r1]) def test_default_ordering_by_f_expression(self): """F expressions can be used in Meta.ordering.""" articles = OrderedByFArticle.objects.all() articles.filter(headline="Article 2").update(author=self.author_2) articles.filter(headline="Article 3").update(author=self.author_1) self.assertQuerysetEqual( articles, ["Article 1", "Article 4", "Article 3", "Article 2"], attrgetter("headline"), ) def test_order_by_ptr_field_with_default_ordering_by_expression(self): ca1 = ChildArticle.objects.create( headline="h2", pub_date=datetime(2005, 7, 27), author=self.author_2, ) ca2 = ChildArticle.objects.create( headline="h2", pub_date=datetime(2005, 7, 27), author=self.author_1, ) ca3 = ChildArticle.objects.create( headline="h3", pub_date=datetime(2005, 7, 27), author=self.author_1, ) ca4 = ChildArticle.objects.create(headline="h1", pub_date=datetime(2005, 7, 28)) articles = ChildArticle.objects.order_by("article_ptr") self.assertSequenceEqual(articles, [ca4, ca2, ca1, ca3]) def test_default_ordering_does_not_affect_group_by(self): Article.objects.exclude(headline="Article 4").update(author=self.author_1) Article.objects.filter(headline="Article 4").update(author=self.author_2) articles = Article.objects.values("author").annotate(count=Count("author")) self.assertCountEqual( articles, [ {"author": self.author_1.pk, "count": 3}, {"author": self.author_2.pk, "count": 1}, ], )
2052c678e5374b1dc0ab36d912e3fd7c4078163f84fae8289099d9fe5c127c85
""" Specifying ordering Specify default ordering for a model using the ``ordering`` attribute, which should be a list or tuple of field names. This tells Django how to order ``QuerySet`` results. If a field name in ``ordering`` starts with a hyphen, that field will be ordered in descending order. Otherwise, it'll be ordered in ascending order. The special-case field name ``"?"`` specifies random order. The ordering attribute is not required. If you leave it off, ordering will be undefined -- not random, just undefined. """ from django.db import models class Author(models.Model): name = models.CharField(max_length=63, null=True, blank=True) editor = models.ForeignKey("self", models.CASCADE, null=True) class Meta: ordering = ("-pk",) class Article(models.Model): author = models.ForeignKey(Author, models.SET_NULL, null=True) second_author = models.ForeignKey( Author, models.SET_NULL, null=True, related_name="+" ) headline = models.CharField(max_length=100) pub_date = models.DateTimeField() class Meta: ordering = ( "-pub_date", models.F("headline"), models.F("author__name").asc(), models.OrderBy(models.F("second_author__name")), ) class OrderedByAuthorArticle(Article): class Meta: proxy = True ordering = ("author", "second_author") class OrderedByFArticle(Article): class Meta: proxy = True ordering = (models.F("author").asc(nulls_first=True), "id") class ChildArticle(Article): pass class Reference(models.Model): article = models.ForeignKey(OrderedByAuthorArticle, models.CASCADE) class Meta: ordering = ("article",)
1af87c4997c0014fa00b8282b77a111634196eb9ed16cfdc423a0d1521cbcdd4
from django.test import TestCase from .models import Article, Car, Driver, Reporter class ManyToOneNullTests(TestCase): @classmethod def setUpTestData(cls): # Create a Reporter. cls.r = Reporter(name="John Smith") cls.r.save() # Create an Article. cls.a = Article(headline="First", reporter=cls.r) cls.a.save() # Create an Article via the Reporter object. cls.a2 = cls.r.article_set.create(headline="Second") # Create an Article with no Reporter by passing "reporter=None". cls.a3 = Article(headline="Third", reporter=None) cls.a3.save() # Create another article and reporter cls.r2 = Reporter(name="Paul Jones") cls.r2.save() cls.a4 = cls.r2.article_set.create(headline="Fourth") def test_get_related(self): self.assertEqual(self.a.reporter.id, self.r.id) # Article objects have access to their related Reporter objects. r = self.a.reporter self.assertEqual(r.id, self.r.id) def test_created_via_related_set(self): self.assertEqual(self.a2.reporter.id, self.r.id) def test_related_set(self): # Reporter objects have access to their related Article objects. self.assertSequenceEqual(self.r.article_set.all(), [self.a, self.a2]) self.assertSequenceEqual( self.r.article_set.filter(headline__startswith="Fir"), [self.a] ) self.assertEqual(self.r.article_set.count(), 2) def test_created_without_related(self): self.assertIsNone(self.a3.reporter) # Need to reget a3 to refresh the cache a3 = Article.objects.get(pk=self.a3.pk) with self.assertRaises(AttributeError): getattr(a3.reporter, "id") # Accessing an article's 'reporter' attribute returns None # if the reporter is set to None. self.assertIsNone(a3.reporter) # To retrieve the articles with no reporters set, use "reporter__isnull=True". self.assertSequenceEqual( Article.objects.filter(reporter__isnull=True), [self.a3] ) # We can achieve the same thing by filtering for the case where the # reporter is None. self.assertSequenceEqual(Article.objects.filter(reporter=None), [self.a3]) # Set the reporter for the Third article self.assertSequenceEqual(self.r.article_set.all(), [self.a, self.a2]) self.r.article_set.add(a3) self.assertSequenceEqual( self.r.article_set.all(), [self.a, self.a2, self.a3], ) # Remove an article from the set, and check that it was removed. self.r.article_set.remove(a3) self.assertSequenceEqual(self.r.article_set.all(), [self.a, self.a2]) self.assertSequenceEqual( Article.objects.filter(reporter__isnull=True), [self.a3] ) def test_remove_from_wrong_set(self): self.assertSequenceEqual(self.r2.article_set.all(), [self.a4]) # Try to remove a4 from a set it does not belong to with self.assertRaises(Reporter.DoesNotExist): self.r.article_set.remove(self.a4) self.assertSequenceEqual(self.r2.article_set.all(), [self.a4]) def test_set(self): # Use manager.set() to allocate ForeignKey. Null is legal, so existing # members of the set that are not in the assignment set are set to null. self.r2.article_set.set([self.a2, self.a3]) self.assertSequenceEqual(self.r2.article_set.all(), [self.a2, self.a3]) # Use manager.set(clear=True) self.r2.article_set.set([self.a3, self.a4], clear=True) self.assertSequenceEqual(self.r2.article_set.all(), [self.a4, self.a3]) # Clear the rest of the set self.r2.article_set.set([]) self.assertSequenceEqual(self.r2.article_set.all(), []) self.assertSequenceEqual( Article.objects.filter(reporter__isnull=True), [self.a4, self.a2, self.a3], ) def test_set_clear_non_bulk(self): # 2 queries for clear(), 1 for add(), and 1 to select objects. with self.assertNumQueries(4): self.r.article_set.set([self.a], bulk=False, clear=True) def test_assign_clear_related_set(self): # Use descriptor assignment to allocate ForeignKey. Null is legal, so # existing members of the set that are not in the assignment set are # set to null. self.r2.article_set.set([self.a2, self.a3]) self.assertSequenceEqual(self.r2.article_set.all(), [self.a2, self.a3]) # Clear the rest of the set self.r.article_set.clear() self.assertSequenceEqual(self.r.article_set.all(), []) self.assertSequenceEqual( Article.objects.filter(reporter__isnull=True), [self.a, self.a4], ) def test_assign_with_queryset(self): # Querysets used in reverse FK assignments are pre-evaluated # so their value isn't affected by the clearing operation in # RelatedManager.set() (#19816). self.r2.article_set.set([self.a2, self.a3]) qs = self.r2.article_set.filter(headline="Second") self.r2.article_set.set(qs) self.assertEqual(1, self.r2.article_set.count()) self.assertEqual(1, qs.count()) def test_add_efficiency(self): r = Reporter.objects.create() articles = [] for _ in range(3): articles.append(Article.objects.create()) with self.assertNumQueries(1): r.article_set.add(*articles) self.assertEqual(r.article_set.count(), 3) def test_clear_efficiency(self): r = Reporter.objects.create() for _ in range(3): r.article_set.create() with self.assertNumQueries(1): r.article_set.clear() self.assertEqual(r.article_set.count(), 0) def test_related_null_to_field(self): c1 = Car.objects.create() d1 = Driver.objects.create() self.assertIs(d1.car, None) with self.assertNumQueries(0): self.assertEqual(list(c1.drivers.all()), []) def test_unsaved(self): msg = ( "'Car' instance needs to have a primary key value before this relationship " "can be used." ) with self.assertRaisesMessage(ValueError, msg): Car(make="Ford").drivers.all() def test_related_null_to_field_related_managers(self): car = Car.objects.create(make=None) driver = Driver.objects.create() msg = ( f'"{car!r}" needs to have a value for field "make" before this ' f"relationship can be used." ) with self.assertRaisesMessage(ValueError, msg): car.drivers.add(driver) with self.assertRaisesMessage(ValueError, msg): car.drivers.create() with self.assertRaisesMessage(ValueError, msg): car.drivers.get_or_create() with self.assertRaisesMessage(ValueError, msg): car.drivers.update_or_create() with self.assertRaisesMessage(ValueError, msg): car.drivers.remove(driver) with self.assertRaisesMessage(ValueError, msg): car.drivers.clear() with self.assertRaisesMessage(ValueError, msg): car.drivers.set([driver]) with self.assertNumQueries(0): self.assertEqual(car.drivers.count(), 0)
ef90932fe7870941278f6dca2243093616380428073cfe3d9fe6a6d410f2cd5e
""" Many-to-one relationships that can be null To define a many-to-one relationship that can have a null foreign key, use ``ForeignKey()`` with ``null=True`` . """ from django.db import models class Reporter(models.Model): name = models.CharField(max_length=30) class Article(models.Model): headline = models.CharField(max_length=100) reporter = models.ForeignKey(Reporter, models.SET_NULL, null=True) class Meta: ordering = ("headline",) def __str__(self): return self.headline class Car(models.Model): make = models.CharField(max_length=100, null=True, unique=True) class Driver(models.Model): car = models.ForeignKey( Car, models.SET_NULL, to_field="make", null=True, related_name="drivers" )
ae7fa86b722fd84af709fee2d6dc424e3f4cf394bbc8f89acce9f5aef49ffa90
import sys from types import ModuleType from django.conf import USE_L10N_DEPRECATED_MSG, Settings, settings from django.test import TestCase, ignore_warnings from django.utils.deprecation import RemovedInDjango50Warning class DeprecationTests(TestCase): msg = USE_L10N_DEPRECATED_MSG def test_override_settings_warning(self): # Warning is raised when USE_L10N is set in UserSettingsHolder (used by # the @override_settings decorator). with self.assertRaisesMessage(RemovedInDjango50Warning, self.msg): with self.settings(USE_L10N=True): pass def test_settings_init_warning(self): settings_module = ModuleType("fake_settings_module") settings_module.SECRET_KEY = "foo" settings_module.USE_TZ = True settings_module.USE_L10N = False sys.modules["fake_settings_module"] = settings_module try: with self.assertRaisesMessage(RemovedInDjango50Warning, self.msg): Settings("fake_settings_module") finally: del sys.modules["fake_settings_module"] def test_access_warning(self): with self.assertRaisesMessage(RemovedInDjango50Warning, self.msg): settings.USE_L10N # Works a second time. with self.assertRaisesMessage(RemovedInDjango50Warning, self.msg): settings.USE_L10N @ignore_warnings(category=RemovedInDjango50Warning) def test_access(self): with self.settings(USE_L10N=False): self.assertIs(settings.USE_L10N, False) # Works a second time. self.assertIs(settings.USE_L10N, False)
1ceddad6dfcc0d8c356c96e58ad06b3e697973486cae730a432560e34fa95dd1
import warnings from django.test import SimpleTestCase from django.utils.deprecation import ( DeprecationInstanceCheck, RemovedAfterNextVersionWarning, RemovedInNextVersionWarning, RenameMethodsBase, ) class RenameManagerMethods(RenameMethodsBase): renamed_methods = (("old", "new", DeprecationWarning),) class RenameMethodsTests(SimpleTestCase): """ Tests the `RenameMethodsBase` type introduced to rename `get_query_set` to `get_queryset` across the code base following #15363. """ def test_class_definition_warnings(self): """ Ensure a warning is raised upon class definition to suggest renaming the faulty method. """ msg = "`Manager.old` method should be renamed `new`." with self.assertWarnsMessage(DeprecationWarning, msg): class Manager(metaclass=RenameManagerMethods): def old(self): pass def test_get_new_defined(self): """ Ensure `old` complains and not `new` when only `new` is defined. """ class Manager(metaclass=RenameManagerMethods): def new(self): pass manager = Manager() with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter("always") manager.new() self.assertEqual(len(recorded), 0) msg = "`Manager.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg): manager.old() def test_get_old_defined(self): """ Ensure `old` complains when only `old` is defined. """ msg = "`Manager.old` method should be renamed `new`." with self.assertWarnsMessage(DeprecationWarning, msg): class Manager(metaclass=RenameManagerMethods): def old(self): pass manager = Manager() with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter("always") manager.new() self.assertEqual(len(recorded), 0) msg = "`Manager.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg): manager.old() def test_deprecated_subclass_renamed(self): """ Ensure the correct warnings are raised when a class that didn't rename `old` subclass one that did. """ class Renamed(metaclass=RenameManagerMethods): def new(self): pass msg = "`Deprecated.old` method should be renamed `new`." with self.assertWarnsMessage(DeprecationWarning, msg): class Deprecated(Renamed): def old(self): super().old() deprecated = Deprecated() msg = "`Renamed.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg): deprecated.new() msg = "`Deprecated.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg): deprecated.old() def test_renamed_subclass_deprecated(self): """ Ensure the correct warnings are raised when a class that renamed `old` subclass one that didn't. """ msg = "`Deprecated.old` method should be renamed `new`." with self.assertWarnsMessage(DeprecationWarning, msg): class Deprecated(metaclass=RenameManagerMethods): def old(self): pass class Renamed(Deprecated): def new(self): super().new() renamed = Renamed() with warnings.catch_warnings(record=True) as recorded: warnings.simplefilter("always") renamed.new() self.assertEqual(len(recorded), 0) msg = "`Renamed.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg): renamed.old() def test_deprecated_subclass_renamed_and_mixins(self): """ Ensure the correct warnings are raised when a subclass inherit from a class that renamed `old` and mixins that may or may not have renamed `new`. """ class Renamed(metaclass=RenameManagerMethods): def new(self): pass class RenamedMixin: def new(self): super().new() class DeprecatedMixin: def old(self): super().old() msg = "`DeprecatedMixin.old` method should be renamed `new`." with self.assertWarnsMessage(DeprecationWarning, msg): class Deprecated(DeprecatedMixin, RenamedMixin, Renamed): pass deprecated = Deprecated() msg = "`RenamedMixin.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg): deprecated.new() msg = "`DeprecatedMixin.old` is deprecated, use `new` instead." with self.assertWarnsMessage(DeprecationWarning, msg): deprecated.old() def test_removedafternextversionwarning_pending(self): self.assertTrue( issubclass(RemovedAfterNextVersionWarning, PendingDeprecationWarning) ) class DeprecationInstanceCheckTest(SimpleTestCase): def test_warning(self): class Manager(metaclass=DeprecationInstanceCheck): alternative = "fake.path.Foo" deprecation_warning = RemovedInNextVersionWarning msg = "`Manager` is deprecated, use `fake.path.Foo` instead." with self.assertWarnsMessage(RemovedInNextVersionWarning, msg): isinstance(object, Manager)
01cc522b06e793714be31d60e485a4d9a86793b04c7b16f07cab218110c9e369
import sys from types import ModuleType from django.conf import CSRF_COOKIE_MASKED_DEPRECATED_MSG, Settings, settings from django.test import SimpleTestCase from django.utils.deprecation import RemovedInDjango50Warning class CsrfCookieMaskedDeprecationTests(SimpleTestCase): msg = CSRF_COOKIE_MASKED_DEPRECATED_MSG def test_override_settings_warning(self): with self.assertRaisesMessage(RemovedInDjango50Warning, self.msg): with self.settings(CSRF_COOKIE_MASKED=True): pass def test_settings_init_warning(self): settings_module = ModuleType("fake_settings_module") settings_module.USE_TZ = False settings_module.CSRF_COOKIE_MASKED = True sys.modules["fake_settings_module"] = settings_module try: with self.assertRaisesMessage(RemovedInDjango50Warning, self.msg): Settings("fake_settings_module") finally: del sys.modules["fake_settings_module"] def test_access(self): # Warning is not raised on access. self.assertEqual(settings.CSRF_COOKIE_MASKED, False)
8774c70ca22793cfeaabc44e18cdd5f225c23f6cf30fd42bb276eb2950b11831
import asyncio import threading from asgiref.sync import async_to_sync from django.contrib.admindocs.middleware import XViewMiddleware from django.contrib.auth.middleware import ( AuthenticationMiddleware, RemoteUserMiddleware, ) from django.contrib.flatpages.middleware import FlatpageFallbackMiddleware from django.contrib.messages.middleware import MessageMiddleware from django.contrib.redirects.middleware import RedirectFallbackMiddleware from django.contrib.sessions.middleware import SessionMiddleware from django.contrib.sites.middleware import CurrentSiteMiddleware from django.db import connection from django.http.request import HttpRequest from django.http.response import HttpResponse from django.middleware.cache import ( CacheMiddleware, FetchFromCacheMiddleware, UpdateCacheMiddleware, ) from django.middleware.clickjacking import XFrameOptionsMiddleware from django.middleware.common import BrokenLinkEmailsMiddleware, CommonMiddleware from django.middleware.csrf import CsrfViewMiddleware from django.middleware.gzip import GZipMiddleware from django.middleware.http import ConditionalGetMiddleware from django.middleware.locale import LocaleMiddleware from django.middleware.security import SecurityMiddleware from django.test import SimpleTestCase from django.utils.deprecation import MiddlewareMixin class MiddlewareMixinTests(SimpleTestCase): middlewares = [ AuthenticationMiddleware, BrokenLinkEmailsMiddleware, CacheMiddleware, CommonMiddleware, ConditionalGetMiddleware, CsrfViewMiddleware, CurrentSiteMiddleware, FetchFromCacheMiddleware, FlatpageFallbackMiddleware, GZipMiddleware, LocaleMiddleware, MessageMiddleware, RedirectFallbackMiddleware, RemoteUserMiddleware, SecurityMiddleware, SessionMiddleware, UpdateCacheMiddleware, XFrameOptionsMiddleware, XViewMiddleware, ] def test_repr(self): class GetResponse: def __call__(self): return HttpResponse() def get_response(): return HttpResponse() self.assertEqual( repr(MiddlewareMixin(GetResponse())), "<MiddlewareMixin get_response=GetResponse>", ) self.assertEqual( repr(MiddlewareMixin(get_response)), "<MiddlewareMixin get_response=" "MiddlewareMixinTests.test_repr.<locals>.get_response>", ) self.assertEqual( repr(CsrfViewMiddleware(GetResponse())), "<CsrfViewMiddleware get_response=GetResponse>", ) self.assertEqual( repr(CsrfViewMiddleware(get_response)), "<CsrfViewMiddleware get_response=" "MiddlewareMixinTests.test_repr.<locals>.get_response>", ) def test_passing_explicit_none(self): msg = "get_response must be provided." for middleware in self.middlewares: with self.subTest(middleware=middleware): with self.assertRaisesMessage(ValueError, msg): middleware(None) def test_coroutine(self): async def async_get_response(request): return HttpResponse() def sync_get_response(request): return HttpResponse() for middleware in self.middlewares: with self.subTest(middleware=middleware.__qualname__): # Middleware appears as coroutine if get_function is # a coroutine. middleware_instance = middleware(async_get_response) self.assertIs(asyncio.iscoroutinefunction(middleware_instance), True) # Middleware doesn't appear as coroutine if get_function is not # a coroutine. middleware_instance = middleware(sync_get_response) self.assertIs(asyncio.iscoroutinefunction(middleware_instance), False) def test_sync_to_async_uses_base_thread_and_connection(self): """ The process_request() and process_response() hooks must be called with the sync_to_async thread_sensitive flag enabled, so that database operations use the correct thread and connection. """ def request_lifecycle(): """Fake request_started/request_finished.""" return (threading.get_ident(), id(connection)) async def get_response(self): return HttpResponse() class SimpleMiddleWare(MiddlewareMixin): def process_request(self, request): request.thread_and_connection = request_lifecycle() def process_response(self, request, response): response.thread_and_connection = request_lifecycle() return response threads_and_connections = [] threads_and_connections.append(request_lifecycle()) request = HttpRequest() response = async_to_sync(SimpleMiddleWare(get_response))(request) threads_and_connections.append(request.thread_and_connection) threads_and_connections.append(response.thread_and_connection) threads_and_connections.append(request_lifecycle()) self.assertEqual(len(threads_and_connections), 4) self.assertEqual(len(set(threads_and_connections)), 1)
ad46cb45c713707e755ca875a0f7029011597de3224084e2819d496ea2d37e6b
import base64 import hashlib import os import shutil import sys import tempfile as sys_tempfile import unittest from io import BytesIO, StringIO from unittest import mock from urllib.parse import quote from django.core.exceptions import SuspiciousFileOperation from django.core.files import temp as tempfile from django.core.files.uploadedfile import SimpleUploadedFile, UploadedFile from django.http.multipartparser import ( FILE, MultiPartParser, MultiPartParserError, Parser, parse_header, ) from django.test import SimpleTestCase, TestCase, client, override_settings from . import uploadhandler from .models import FileModel UNICODE_FILENAME = "test-0123456789_中文_Orléans.jpg" MEDIA_ROOT = sys_tempfile.mkdtemp() UPLOAD_TO = os.path.join(MEDIA_ROOT, "test_upload") CANDIDATE_TRAVERSAL_FILE_NAMES = [ "/tmp/hax0rd.txt", # Absolute path, *nix-style. "C:\\Windows\\hax0rd.txt", # Absolute path, win-style. "C:/Windows/hax0rd.txt", # Absolute path, broken-style. "\\tmp\\hax0rd.txt", # Absolute path, broken in a different way. "/tmp\\hax0rd.txt", # Absolute path, broken by mixing. "subdir/hax0rd.txt", # Descendant path, *nix-style. "subdir\\hax0rd.txt", # Descendant path, win-style. "sub/dir\\hax0rd.txt", # Descendant path, mixed. "../../hax0rd.txt", # Relative path, *nix-style. "..\\..\\hax0rd.txt", # Relative path, win-style. "../..\\hax0rd.txt", # Relative path, mixed. "..&#x2F;hax0rd.txt", # HTML entities. "..&sol;hax0rd.txt", # HTML entities. ] CANDIDATE_INVALID_FILE_NAMES = [ "/tmp/", # Directory, *nix-style. "c:\\tmp\\", # Directory, win-style. "/tmp/.", # Directory dot, *nix-style. "c:\\tmp\\.", # Directory dot, *nix-style. "/tmp/..", # Parent directory, *nix-style. "c:\\tmp\\..", # Parent directory, win-style. "", # Empty filename. ] @override_settings( MEDIA_ROOT=MEDIA_ROOT, ROOT_URLCONF="file_uploads.urls", MIDDLEWARE=[] ) class FileUploadTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() os.makedirs(MEDIA_ROOT, exist_ok=True) cls.addClassCleanup(shutil.rmtree, MEDIA_ROOT) def test_upload_name_is_validated(self): candidates = [ "/tmp/", "/tmp/..", "/tmp/.", ] if sys.platform == "win32": candidates.extend( [ "c:\\tmp\\", "c:\\tmp\\..", "c:\\tmp\\.", ] ) for file_name in candidates: with self.subTest(file_name=file_name): self.assertRaises(SuspiciousFileOperation, UploadedFile, name=file_name) def test_simple_upload(self): with open(__file__, "rb") as fp: post_data = { "name": "Ringo", "file_field": fp, } response = self.client.post("/upload/", post_data) self.assertEqual(response.status_code, 200) def test_large_upload(self): file = tempfile.NamedTemporaryFile with file(suffix=".file1") as file1, file(suffix=".file2") as file2: file1.write(b"a" * (2**21)) file1.seek(0) file2.write(b"a" * (10 * 2**20)) file2.seek(0) post_data = { "name": "Ringo", "file_field1": file1, "file_field2": file2, } for key in list(post_data): try: post_data[key + "_hash"] = hashlib.sha1( post_data[key].read() ).hexdigest() post_data[key].seek(0) except AttributeError: post_data[key + "_hash"] = hashlib.sha1( post_data[key].encode() ).hexdigest() response = self.client.post("/verify/", post_data) self.assertEqual(response.status_code, 200) def _test_base64_upload(self, content, encode=base64.b64encode): payload = client.FakePayload( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="test.txt"', "Content-Type: application/octet-stream", "Content-Transfer-Encoding: base64", "", ] ) ) payload.write(b"\r\n" + encode(content.encode()) + b"\r\n") payload.write("--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo_content/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.json()["file"], content) def test_base64_upload(self): self._test_base64_upload("This data will be transmitted base64-encoded.") def test_big_base64_upload(self): self._test_base64_upload("Big data" * 68000) # > 512Kb def test_big_base64_newlines_upload(self): self._test_base64_upload("Big data" * 68000, encode=base64.encodebytes) def test_base64_invalid_upload(self): payload = client.FakePayload( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="test.txt"', "Content-Type: application/octet-stream", "Content-Transfer-Encoding: base64", "", ] ) ) payload.write(b"\r\n!\r\n") payload.write("--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo_content/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.json()["file"], "") def test_unicode_file_name(self): with sys_tempfile.TemporaryDirectory() as temp_dir: # This file contains Chinese symbols and an accented char in the name. with open(os.path.join(temp_dir, UNICODE_FILENAME), "w+b") as file1: file1.write(b"b" * (2**10)) file1.seek(0) response = self.client.post("/unicode_name/", {"file_unicode": file1}) self.assertEqual(response.status_code, 200) def test_unicode_file_name_rfc2231(self): """ Test receiving file upload when filename is encoded with RFC2231 (#22971). """ payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file_unicode"; ' "filename*=UTF-8''%s" % quote(UNICODE_FILENAME), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", "\r\n--" + client.BOUNDARY + "--\r\n", ] ) ) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/unicode_name/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_unicode_name_rfc2231(self): """ Test receiving file upload when filename is encoded with RFC2231 (#22971). """ payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, "Content-Disposition: form-data; name*=UTF-8''file_unicode; " "filename*=UTF-8''%s" % quote(UNICODE_FILENAME), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", "\r\n--" + client.BOUNDARY + "--\r\n", ] ) ) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/unicode_name/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_unicode_file_name_rfc2231_with_double_quotes(self): payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file_unicode"; ' "filename*=\"UTF-8''%s\"" % quote(UNICODE_FILENAME), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", "\r\n--" + client.BOUNDARY + "--\r\n", ] ) ) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/unicode_name/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_unicode_name_rfc2231_with_double_quotes(self): payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, "Content-Disposition: form-data; name*=\"UTF-8''file_unicode\"; " "filename*=\"UTF-8''%s\"" % quote(UNICODE_FILENAME), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", "\r\n--" + client.BOUNDARY + "--\r\n", ] ) ) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/unicode_name/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) def test_blank_filenames(self): """ Receiving file upload when filename is blank (before and after sanitization) should be okay. """ filenames = [ "", # Normalized by MultiPartParser.IE_sanitize(). "C:\\Windows\\", # Normalized by os.path.basename(). "/", "ends-with-slash/", ] payload = client.FakePayload() for i, name in enumerate(filenames): payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", ] ) ) payload.write("\r\n--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) self.assertEqual(response.status_code, 200) # Empty filenames should be ignored received = response.json() for i, name in enumerate(filenames): self.assertIsNone(received.get("file%s" % i)) def test_non_printable_chars_in_file_names(self): file_name = "non-\x00printable\x00\n_chars.txt\x00" payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, f'Content-Disposition: form-data; name="file"; ' f'filename="{file_name}"', "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", ] ) ) payload.write("\r\n--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) # Non-printable chars are sanitized. received = response.json() self.assertEqual(received["file"], "non-printable_chars.txt") def test_dangerous_file_names(self): """Uploaded file names should be sanitized before ever reaching the view.""" # This test simulates possible directory traversal attacks by a # malicious uploader We have to do some monkeybusiness here to construct # a malicious payload with an invalid file name (containing os.sep or # os.pardir). This similar to what an attacker would need to do when # trying such an attack. payload = client.FakePayload() for i, name in enumerate(CANDIDATE_TRAVERSAL_FILE_NAMES): payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file%s"; filename="%s"' % (i, name), "Content-Type: application/octet-stream", "", "You got pwnd.\r\n", ] ) ) payload.write("\r\n--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) # The filenames should have been sanitized by the time it got to the view. received = response.json() for i, name in enumerate(CANDIDATE_TRAVERSAL_FILE_NAMES): got = received["file%s" % i] self.assertEqual(got, "hax0rd.txt") def test_filename_overflow(self): """File names over 256 characters (dangerous on some platforms) get fixed up.""" long_str = "f" * 300 cases = [ # field name, filename, expected ("long_filename", "%s.txt" % long_str, "%s.txt" % long_str[:251]), ("long_extension", "foo.%s" % long_str, ".%s" % long_str[:254]), ("no_extension", long_str, long_str[:255]), ("no_filename", ".%s" % long_str, ".%s" % long_str[:254]), ("long_everything", "%s.%s" % (long_str, long_str), ".%s" % long_str[:254]), ] payload = client.FakePayload() for name, filename, _ in cases: payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="{}"; filename="{}"', "Content-Type: application/octet-stream", "", "Oops.", "", ] ).format(name, filename) ) payload.write("\r\n--" + client.BOUNDARY + "--\r\n") r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) result = response.json() for name, _, expected in cases: got = result[name] self.assertEqual(expected, got, "Mismatch for {}".format(name)) self.assertLess( len(got), 256, "Got a long file name (%s characters)." % len(got) ) def test_file_content(self): file = tempfile.NamedTemporaryFile with file(suffix=".ctype_extra") as no_content_type, file( suffix=".ctype_extra" ) as simple_file: no_content_type.write(b"no content") no_content_type.seek(0) simple_file.write(b"text content") simple_file.seek(0) simple_file.content_type = "text/plain" string_io = StringIO("string content") bytes_io = BytesIO(b"binary content") response = self.client.post( "/echo_content/", { "no_content_type": no_content_type, "simple_file": simple_file, "string": string_io, "binary": bytes_io, }, ) received = response.json() self.assertEqual(received["no_content_type"], "no content") self.assertEqual(received["simple_file"], "text content") self.assertEqual(received["string"], "string content") self.assertEqual(received["binary"], "binary content") def test_content_type_extra(self): """Uploaded files may have content type parameters available.""" file = tempfile.NamedTemporaryFile with file(suffix=".ctype_extra") as no_content_type, file( suffix=".ctype_extra" ) as simple_file: no_content_type.write(b"something") no_content_type.seek(0) simple_file.write(b"something") simple_file.seek(0) simple_file.content_type = "text/plain; test-key=test_value" response = self.client.post( "/echo_content_type_extra/", { "no_content_type": no_content_type, "simple_file": simple_file, }, ) received = response.json() self.assertEqual(received["no_content_type"], {}) self.assertEqual(received["simple_file"], {"test-key": "test_value"}) def test_truncated_multipart_handled_gracefully(self): """ If passed an incomplete multipart message, MultiPartParser does not attempt to read beyond the end of the stream, and simply will handle the part that can be parsed gracefully. """ payload_str = "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="file"; filename="foo.txt"', "Content-Type: application/octet-stream", "", "file contents" "--" + client.BOUNDARY + "--", "", ] ) payload = client.FakePayload(payload_str[:-10]) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } self.assertEqual(self.client.request(**r).json(), {}) def test_empty_multipart_handled_gracefully(self): """ If passed an empty multipart message, MultiPartParser will return an empty QueryDict. """ r = { "CONTENT_LENGTH": 0, "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/echo/", "REQUEST_METHOD": "POST", "wsgi.input": client.FakePayload(b""), } self.assertEqual(self.client.request(**r).json(), {}) def test_custom_upload_handler(self): file = tempfile.NamedTemporaryFile with file() as smallfile, file() as bigfile: # A small file (under the 5M quota) smallfile.write(b"a" * (2**21)) smallfile.seek(0) # A big file (over the quota) bigfile.write(b"a" * (10 * 2**20)) bigfile.seek(0) # Small file posting should work. self.assertIn("f", self.client.post("/quota/", {"f": smallfile}).json()) # Large files don't go through. self.assertNotIn("f", self.client.post("/quota/", {"f": bigfile}).json()) def test_broken_custom_upload_handler(self): with tempfile.NamedTemporaryFile() as file: file.write(b"a" * (2**21)) file.seek(0) msg = ( "You cannot alter upload handlers after the upload has been processed." ) with self.assertRaisesMessage(AttributeError, msg): self.client.post("/quota/broken/", {"f": file}) def test_stop_upload_temporary_file_handler(self): with tempfile.NamedTemporaryFile() as temp_file: temp_file.write(b"a") temp_file.seek(0) response = self.client.post("/temp_file/stop_upload/", {"file": temp_file}) temp_path = response.json()["temp_path"] self.assertIs(os.path.exists(temp_path), False) def test_upload_interrupted_temporary_file_handler(self): # Simulate an interrupted upload by omitting the closing boundary. class MockedParser(Parser): def __iter__(self): for item in super().__iter__(): item_type, meta_data, field_stream = item yield item_type, meta_data, field_stream if item_type == FILE: return with tempfile.NamedTemporaryFile() as temp_file: temp_file.write(b"a") temp_file.seek(0) with mock.patch( "django.http.multipartparser.Parser", MockedParser, ): response = self.client.post( "/temp_file/upload_interrupted/", {"file": temp_file}, ) temp_path = response.json()["temp_path"] self.assertIs(os.path.exists(temp_path), False) def test_fileupload_getlist(self): file = tempfile.NamedTemporaryFile with file() as file1, file() as file2, file() as file2a: file1.write(b"a" * (2**23)) file1.seek(0) file2.write(b"a" * (2 * 2**18)) file2.seek(0) file2a.write(b"a" * (5 * 2**20)) file2a.seek(0) response = self.client.post( "/getlist_count/", { "file1": file1, "field1": "test", "field2": "test3", "field3": "test5", "field4": "test6", "field5": "test7", "file2": (file2, file2a), }, ) got = response.json() self.assertEqual(got.get("file1"), 1) self.assertEqual(got.get("file2"), 2) def test_fileuploads_closed_at_request_end(self): file = tempfile.NamedTemporaryFile with file() as f1, file() as f2a, file() as f2b: response = self.client.post( "/fd_closing/t/", { "file": f1, "file2": (f2a, f2b), }, ) request = response.wsgi_request # The files were parsed. self.assertTrue(hasattr(request, "_files")) file = request._files["file"] self.assertTrue(file.closed) files = request._files.getlist("file2") self.assertTrue(files[0].closed) self.assertTrue(files[1].closed) def test_no_parsing_triggered_by_fd_closing(self): file = tempfile.NamedTemporaryFile with file() as f1, file() as f2a, file() as f2b: response = self.client.post( "/fd_closing/f/", { "file": f1, "file2": (f2a, f2b), }, ) request = response.wsgi_request # The fd closing logic doesn't trigger parsing of the stream self.assertFalse(hasattr(request, "_files")) def test_file_error_blocking(self): """ The server should not block when there are upload errors (bug #8622). This can happen if something -- i.e. an exception handler -- tries to access POST while handling an error in parsing POST. This shouldn't cause an infinite loop! """ class POSTAccessingHandler(client.ClientHandler): """A handler that'll access POST during an exception.""" def handle_uncaught_exception(self, request, resolver, exc_info): ret = super().handle_uncaught_exception(request, resolver, exc_info) request.POST # evaluate return ret # Maybe this is a little more complicated that it needs to be; but if # the django.test.client.FakePayload.read() implementation changes then # this test would fail. So we need to know exactly what kind of error # it raises when there is an attempt to read more than the available bytes: try: client.FakePayload(b"a").read(2) except Exception as err: reference_error = err # install the custom handler that tries to access request.POST self.client.handler = POSTAccessingHandler() with open(__file__, "rb") as fp: post_data = { "name": "Ringo", "file_field": fp, } try: self.client.post("/upload_errors/", post_data) except reference_error.__class__ as err: self.assertNotEqual( str(err), str(reference_error), "Caught a repeated exception that'll cause an infinite loop in " "file uploads.", ) except Exception as err: # CustomUploadError is the error that should have been raised self.assertEqual(err.__class__, uploadhandler.CustomUploadError) def test_filename_case_preservation(self): """ The storage backend shouldn't mess with the case of the filenames uploaded. """ # Synthesize the contents of a file upload with a mixed case filename # so we don't have to carry such a file in the Django tests source code # tree. vars = {"boundary": "oUrBoUnDaRyStRiNg"} post_data = [ "--%(boundary)s", 'Content-Disposition: form-data; name="file_field"; ' 'filename="MiXeD_cAsE.txt"', "Content-Type: application/octet-stream", "", "file contents\n", "--%(boundary)s--\r\n", ] response = self.client.post( "/filename_case/", "\r\n".join(post_data) % vars, "multipart/form-data; boundary=%(boundary)s" % vars, ) self.assertEqual(response.status_code, 200) id = int(response.content) obj = FileModel.objects.get(pk=id) # The name of the file uploaded and the file stored in the server-side # shouldn't differ. self.assertEqual(os.path.basename(obj.testfile.path), "MiXeD_cAsE.txt") def test_filename_traversal_upload(self): os.makedirs(UPLOAD_TO, exist_ok=True) tests = [ "..&#x2F;test.txt", "..&sol;test.txt", ] for file_name in tests: with self.subTest(file_name=file_name): payload = client.FakePayload() payload.write( "\r\n".join( [ "--" + client.BOUNDARY, 'Content-Disposition: form-data; name="my_file"; ' 'filename="%s";' % file_name, "Content-Type: text/plain", "", "file contents.\r\n", "\r\n--" + client.BOUNDARY + "--\r\n", ] ), ) r = { "CONTENT_LENGTH": len(payload), "CONTENT_TYPE": client.MULTIPART_CONTENT, "PATH_INFO": "/upload_traversal/", "REQUEST_METHOD": "POST", "wsgi.input": payload, } response = self.client.request(**r) result = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(result["file_name"], "test.txt") self.assertIs( os.path.exists(os.path.join(MEDIA_ROOT, "test.txt")), False, ) self.assertIs( os.path.exists(os.path.join(UPLOAD_TO, "test.txt")), True, ) @override_settings(MEDIA_ROOT=MEDIA_ROOT) class DirectoryCreationTests(SimpleTestCase): """ Tests for error handling during directory creation via _save_FIELD_file (ticket #6450) """ @classmethod def setUpClass(cls): super().setUpClass() os.makedirs(MEDIA_ROOT, exist_ok=True) cls.addClassCleanup(shutil.rmtree, MEDIA_ROOT) def setUp(self): self.obj = FileModel() @unittest.skipIf( sys.platform == "win32", "Python on Windows doesn't have working os.chmod()." ) def test_readonly_root(self): """Permission errors are not swallowed""" os.chmod(MEDIA_ROOT, 0o500) self.addCleanup(os.chmod, MEDIA_ROOT, 0o700) with self.assertRaises(PermissionError): self.obj.testfile.save( "foo.txt", SimpleUploadedFile("foo.txt", b"x"), save=False ) def test_not_a_directory(self): # Create a file with the upload directory name open(UPLOAD_TO, "wb").close() self.addCleanup(os.remove, UPLOAD_TO) msg = "%s exists and is not a directory." % UPLOAD_TO with self.assertRaisesMessage(FileExistsError, msg): with SimpleUploadedFile("foo.txt", b"x") as file: self.obj.testfile.save("foo.txt", file, save=False) class MultiParserTests(SimpleTestCase): def test_empty_upload_handlers(self): # We're not actually parsing here; just checking if the parser properly # instantiates with empty upload handlers. MultiPartParser( { "CONTENT_TYPE": "multipart/form-data; boundary=_foo", "CONTENT_LENGTH": "1", }, StringIO("x"), [], "utf-8", ) def test_invalid_content_type(self): with self.assertRaisesMessage( MultiPartParserError, "Invalid Content-Type: text/plain" ): MultiPartParser( { "CONTENT_TYPE": "text/plain", "CONTENT_LENGTH": "1", }, StringIO("x"), [], "utf-8", ) def test_negative_content_length(self): with self.assertRaisesMessage( MultiPartParserError, "Invalid content length: -1" ): MultiPartParser( { "CONTENT_TYPE": "multipart/form-data; boundary=_foo", "CONTENT_LENGTH": -1, }, StringIO("x"), [], "utf-8", ) def test_bad_type_content_length(self): multipart_parser = MultiPartParser( { "CONTENT_TYPE": "multipart/form-data; boundary=_foo", "CONTENT_LENGTH": "a", }, StringIO("x"), [], "utf-8", ) self.assertEqual(multipart_parser._content_length, 0) def test_sanitize_file_name(self): parser = MultiPartParser( { "CONTENT_TYPE": "multipart/form-data; boundary=_foo", "CONTENT_LENGTH": "1", }, StringIO("x"), [], "utf-8", ) for file_name in CANDIDATE_TRAVERSAL_FILE_NAMES: with self.subTest(file_name=file_name): self.assertEqual(parser.sanitize_file_name(file_name), "hax0rd.txt") def test_sanitize_invalid_file_name(self): parser = MultiPartParser( { "CONTENT_TYPE": "multipart/form-data; boundary=_foo", "CONTENT_LENGTH": "1", }, StringIO("x"), [], "utf-8", ) for file_name in CANDIDATE_INVALID_FILE_NAMES: with self.subTest(file_name=file_name): self.assertIsNone(parser.sanitize_file_name(file_name)) def test_rfc2231_parsing(self): test_data = ( ( b"Content-Type: application/x-stuff; " b"title*=us-ascii'en-us'This%20is%20%2A%2A%2Afun%2A%2A%2A", "This is ***fun***", ), ( b"Content-Type: application/x-stuff; title*=UTF-8''foo-%c3%a4.html", "foo-ä.html", ), ( b"Content-Type: application/x-stuff; title*=iso-8859-1''foo-%E4.html", "foo-ä.html", ), ) for raw_line, expected_title in test_data: parsed = parse_header(raw_line) self.assertEqual(parsed[1]["title"], expected_title) def test_rfc2231_wrong_title(self): """ Test wrongly formatted RFC 2231 headers (missing double single quotes). Parsing should not crash (#24209). """ test_data = ( ( b"Content-Type: application/x-stuff; " b"title*='This%20is%20%2A%2A%2Afun%2A%2A%2A", b"'This%20is%20%2A%2A%2Afun%2A%2A%2A", ), (b"Content-Type: application/x-stuff; title*='foo.html", b"'foo.html"), (b"Content-Type: application/x-stuff; title*=bar.html", b"bar.html"), ) for raw_line, expected_title in test_data: parsed = parse_header(raw_line) self.assertEqual(parsed[1]["title"], expected_title)
6ef5078f0d9a5e552a4de07a285e693ac6182133fb7f9048f1ac7c763f985673
from django.db import models class FileModel(models.Model): testfile = models.FileField(upload_to="test_upload")
4a6cd8bdc5c0f51c1314dd515e9730d62c08ffb745f3d6a5ae51a137dd7f6221
""" Upload handlers to test the upload API. """ import os from tempfile import NamedTemporaryFile from django.core.files.uploadhandler import ( FileUploadHandler, StopUpload, TemporaryFileUploadHandler, ) class QuotaUploadHandler(FileUploadHandler): """ This test upload handler terminates the connection if more than a quota (5MB) is uploaded. """ QUOTA = 5 * 2**20 # 5 MB def __init__(self, request=None): super().__init__(request) self.total_upload = 0 def receive_data_chunk(self, raw_data, start): self.total_upload += len(raw_data) if self.total_upload >= self.QUOTA: raise StopUpload(connection_reset=True) return raw_data def file_complete(self, file_size): return None class StopUploadTemporaryFileHandler(TemporaryFileUploadHandler): """A handler that raises a StopUpload exception.""" def receive_data_chunk(self, raw_data, start): raise StopUpload() class CustomUploadError(Exception): pass class ErroringUploadHandler(FileUploadHandler): """A handler that raises an exception.""" def receive_data_chunk(self, raw_data, start): raise CustomUploadError("Oops!") class TraversalUploadHandler(FileUploadHandler): """A handler with potential directory-traversal vulnerability.""" def __init__(self, request=None): from .views import UPLOAD_TO super().__init__(request) self.upload_dir = UPLOAD_TO def file_complete(self, file_size): self.file.seek(0) self.file.size = file_size with open(os.path.join(self.upload_dir, self.file_name), "wb") as fp: fp.write(self.file.read()) return self.file def new_file( self, field_name, file_name, content_type, content_length, charset=None, content_type_extra=None, ): super().new_file( file_name, file_name, content_length, content_length, charset, content_type_extra, ) self.file = NamedTemporaryFile(suffix=".upload", dir=self.upload_dir) def receive_data_chunk(self, raw_data, start): self.file.write(raw_data)
7add11d5da264c0ec12469cda31a2ceb982557c68fc6c6a66a13c9508ebc3fb2
from django.urls import path, re_path from . import views urlpatterns = [ path("upload/", views.file_upload_view), path("upload_traversal/", views.file_upload_traversal_view), path("verify/", views.file_upload_view_verify), path("unicode_name/", views.file_upload_unicode_name), path("echo/", views.file_upload_echo), path("echo_content_type_extra/", views.file_upload_content_type_extra), path("echo_content/", views.file_upload_echo_content), path("quota/", views.file_upload_quota), path("quota/broken/", views.file_upload_quota_broken), path("getlist_count/", views.file_upload_getlist_count), path("upload_errors/", views.file_upload_errors), path("temp_file/stop_upload/", views.file_stop_upload_temporary_file), path("temp_file/upload_interrupted/", views.file_upload_interrupted_temporary_file), path("filename_case/", views.file_upload_filename_case_view), re_path(r"^fd_closing/(?P<access>t|f)/$", views.file_upload_fd_closing), ]
44c55705105e727e8e9c5c1a6fe77d06563f969c372396fd885ed01c6e5e1665
import hashlib import os from django.core.files.uploadedfile import UploadedFile from django.core.files.uploadhandler import TemporaryFileUploadHandler from django.http import HttpResponse, HttpResponseServerError, JsonResponse from .models import FileModel from .tests import UNICODE_FILENAME, UPLOAD_TO from .uploadhandler import ( ErroringUploadHandler, QuotaUploadHandler, StopUploadTemporaryFileHandler, TraversalUploadHandler, ) def file_upload_view(request): """ A file upload can be updated into the POST dictionary. """ form_data = request.POST.copy() form_data.update(request.FILES) if isinstance(form_data.get("file_field"), UploadedFile) and isinstance( form_data["name"], str ): # If a file is posted, the dummy client should only post the file name, # not the full path. if os.path.dirname(form_data["file_field"].name) != "": return HttpResponseServerError() return HttpResponse() else: return HttpResponseServerError() def file_upload_view_verify(request): """ Use the sha digest hash to verify the uploaded contents. """ form_data = request.POST.copy() form_data.update(request.FILES) for key, value in form_data.items(): if key.endswith("_hash"): continue if key + "_hash" not in form_data: continue submitted_hash = form_data[key + "_hash"] if isinstance(value, UploadedFile): new_hash = hashlib.sha1(value.read()).hexdigest() else: new_hash = hashlib.sha1(value.encode()).hexdigest() if new_hash != submitted_hash: return HttpResponseServerError() # Adding large file to the database should succeed largefile = request.FILES["file_field2"] obj = FileModel() obj.testfile.save(largefile.name, largefile) return HttpResponse() def file_upload_unicode_name(request): # Check to see if Unicode name came through properly. if not request.FILES["file_unicode"].name.endswith(UNICODE_FILENAME): return HttpResponseServerError() # Check to make sure the exotic characters are preserved even # through file save. uni_named_file = request.FILES["file_unicode"] FileModel.objects.create(testfile=uni_named_file) full_name = "%s/%s" % (UPLOAD_TO, uni_named_file.name) return HttpResponse() if os.path.exists(full_name) else HttpResponseServerError() def file_upload_echo(request): """ Simple view to echo back info about uploaded files for tests. """ r = {k: f.name for k, f in request.FILES.items()} return JsonResponse(r) def file_upload_echo_content(request): """ Simple view to echo back the content of uploaded files for tests. """ def read_and_close(f): with f: return f.read().decode() r = {k: read_and_close(f) for k, f in request.FILES.items()} return JsonResponse(r) def file_upload_quota(request): """ Dynamically add in an upload handler. """ request.upload_handlers.insert(0, QuotaUploadHandler()) return file_upload_echo(request) def file_upload_quota_broken(request): """ You can't change handlers after reading FILES; this view shouldn't work. """ response = file_upload_echo(request) request.upload_handlers.insert(0, QuotaUploadHandler()) return response def file_stop_upload_temporary_file(request): request.upload_handlers.insert(0, StopUploadTemporaryFileHandler()) request.upload_handlers.pop(2) request.FILES # Trigger file parsing. return JsonResponse( {"temp_path": request.upload_handlers[0].file.temporary_file_path()}, ) def file_upload_interrupted_temporary_file(request): request.upload_handlers.insert(0, TemporaryFileUploadHandler()) request.upload_handlers.pop(2) request.FILES # Trigger file parsing. return JsonResponse( {"temp_path": request.upload_handlers[0].file.temporary_file_path()}, ) def file_upload_getlist_count(request): """ Check the .getlist() function to ensure we receive the correct number of files. """ file_counts = {} for key in request.FILES: file_counts[key] = len(request.FILES.getlist(key)) return JsonResponse(file_counts) def file_upload_errors(request): request.upload_handlers.insert(0, ErroringUploadHandler()) return file_upload_echo(request) def file_upload_filename_case_view(request): """ Check adding the file to the database will preserve the filename case. """ file = request.FILES["file_field"] obj = FileModel() obj.testfile.save(file.name, file) return HttpResponse("%d" % obj.pk) def file_upload_content_type_extra(request): """ Simple view to echo back extra content-type parameters. """ params = {} for file_name, uploadedfile in request.FILES.items(): params[file_name] = { k: v.decode() for k, v in uploadedfile.content_type_extra.items() } return JsonResponse(params) def file_upload_fd_closing(request, access): if access == "t": request.FILES # Trigger file parsing. return HttpResponse() def file_upload_traversal_view(request): request.upload_handlers.insert(0, TraversalUploadHandler()) request.FILES # Trigger file parsing. return JsonResponse( {"file_name": request.upload_handlers[0].file_name}, )
10d8d35a60afe0e0627131397825f126a4e63a14ee0b5cd8a9d9f2dafedb8ba6
from django.conf import settings from django.contrib.auth.models import User from django.contrib.flatpages.models import FlatPage from django.contrib.sites.models import Site from django.test import TestCase, modify_settings, override_settings from .settings import FLATPAGES_TEMPLATES class TestDataMixin: @classmethod def setUpTestData(cls): # don't use the manager because we want to ensure the site exists # with pk=1, regardless of whether or not it already exists. cls.site1 = Site(pk=1, domain="example.com", name="example.com") cls.site1.save() cls.fp1 = FlatPage.objects.create( url="/flatpage/", title="A Flatpage", content="Isn't it flat!", enable_comments=False, template_name="", registration_required=False, ) cls.fp2 = FlatPage.objects.create( url="/location/flatpage/", title="A Nested Flatpage", content="Isn't it flat and deep!", enable_comments=False, template_name="", registration_required=False, ) cls.fp3 = FlatPage.objects.create( url="/sekrit/", title="Sekrit Flatpage", content="Isn't it sekrit!", enable_comments=False, template_name="", registration_required=True, ) cls.fp4 = FlatPage.objects.create( url="/location/sekrit/", title="Sekrit Nested Flatpage", content="Isn't it sekrit and deep!", enable_comments=False, template_name="", registration_required=True, ) cls.fp1.sites.add(cls.site1) cls.fp2.sites.add(cls.site1) cls.fp3.sites.add(cls.site1) cls.fp4.sites.add(cls.site1) @modify_settings(INSTALLED_APPS={"append": "django.contrib.flatpages"}) @override_settings( LOGIN_URL="/accounts/login/", MIDDLEWARE=[ "django.middleware.common.CommonMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", # no 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware' ], ROOT_URLCONF="flatpages_tests.urls", TEMPLATES=FLATPAGES_TEMPLATES, SITE_ID=1, ) class FlatpageViewTests(TestDataMixin, TestCase): def test_view_flatpage(self): "A flatpage can be served through a view" response = self.client.get("/flatpage_root/flatpage/") self.assertContains(response, "<p>Isn't it flat!</p>") def test_view_non_existent_flatpage(self): """A nonexistent flatpage raises 404 when served through a view.""" response = self.client.get("/flatpage_root/no_such_flatpage/") self.assertEqual(response.status_code, 404) def test_view_authenticated_flatpage(self): "A flatpage served through a view can require authentication" response = self.client.get("/flatpage_root/sekrit/") self.assertRedirects(response, "/accounts/login/?next=/flatpage_root/sekrit/") user = User.objects.create_user("testuser", "[email protected]", "s3krit") self.client.force_login(user) response = self.client.get("/flatpage_root/sekrit/") self.assertContains(response, "<p>Isn't it sekrit!</p>") def test_fallback_flatpage(self): "A fallback flatpage won't be served if the middleware is disabled" response = self.client.get("/flatpage/") self.assertEqual(response.status_code, 404) def test_fallback_non_existent_flatpage(self): """ A nonexistent flatpage won't be served if the fallback middleware is disabled. """ response = self.client.get("/no_such_flatpage/") self.assertEqual(response.status_code, 404) def test_view_flatpage_special_chars(self): "A flatpage with special chars in the URL can be served through a view" fp = FlatPage.objects.create( url="/some.very_special~chars-here/", title="A very special page", content="Isn't it special!", enable_comments=False, registration_required=False, ) fp.sites.add(settings.SITE_ID) response = self.client.get("/flatpage_root/some.very_special~chars-here/") self.assertContains(response, "<p>Isn't it special!</p>") @modify_settings(INSTALLED_APPS={"append": "django.contrib.flatpages"}) @override_settings( APPEND_SLASH=True, LOGIN_URL="/accounts/login/", MIDDLEWARE=[ "django.middleware.common.CommonMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", # no 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware' ], ROOT_URLCONF="flatpages_tests.urls", TEMPLATES=FLATPAGES_TEMPLATES, SITE_ID=1, ) class FlatpageViewAppendSlashTests(TestDataMixin, TestCase): def test_redirect_view_flatpage(self): "A flatpage can be served through a view and should add a slash" response = self.client.get("/flatpage_root/flatpage") self.assertRedirects(response, "/flatpage_root/flatpage/", status_code=301) def test_redirect_view_non_existent_flatpage(self): """ A nonexistent flatpage raises 404 when served through a view and should not add a slash. """ response = self.client.get("/flatpage_root/no_such_flatpage") self.assertEqual(response.status_code, 404) def test_redirect_fallback_flatpage(self): """ A fallback flatpage won't be served if the middleware is disabled and should not add a slash. """ response = self.client.get("/flatpage") self.assertEqual(response.status_code, 404) def test_redirect_fallback_non_existent_flatpage(self): """ A nonexistent flatpage won't be served if the fallback middleware is disabled and should not add a slash. """ response = self.client.get("/no_such_flatpage") self.assertEqual(response.status_code, 404) def test_redirect_view_flatpage_special_chars(self): """ A flatpage with special chars in the URL can be served through a view and should add a slash. """ fp = FlatPage.objects.create( url="/some.very_special~chars-here/", title="A very special page", content="Isn't it special!", enable_comments=False, registration_required=False, ) fp.sites.add(settings.SITE_ID) response = self.client.get("/flatpage_root/some.very_special~chars-here") self.assertRedirects( response, "/flatpage_root/some.very_special~chars-here/", status_code=301 )
fc0a7ff9718d6ca78636992523663d1f83c20d90fda9df8e33af1468de615759
from django.contrib.flatpages.models import FlatPage from django.test import SimpleTestCase, override_settings from django.test.utils import override_script_prefix class FlatpageModelTests(SimpleTestCase): def setUp(self): self.page = FlatPage(title="Café!", url="/café/") def test_get_absolute_url_urlencodes(self): self.assertEqual(self.page.get_absolute_url(), "/caf%C3%A9/") @override_script_prefix("/prefix/") def test_get_absolute_url_honors_script_prefix(self): self.assertEqual(self.page.get_absolute_url(), "/prefix/caf%C3%A9/") def test_str(self): self.assertEqual(str(self.page), "/café/ -- Café!") @override_settings(ROOT_URLCONF="flatpages_tests.urls") def test_get_absolute_url_include(self): self.assertEqual(self.page.get_absolute_url(), "/flatpage_root/caf%C3%A9/") @override_settings(ROOT_URLCONF="flatpages_tests.no_slash_urls") def test_get_absolute_url_include_no_slash(self): self.assertEqual(self.page.get_absolute_url(), "/flatpagecaf%C3%A9/") @override_settings(ROOT_URLCONF="flatpages_tests.absolute_urls") def test_get_absolute_url_with_hardcoded_url(self): fp = FlatPage(title="Test", url="/hardcoded/") self.assertEqual(fp.get_absolute_url(), "/flatpage/")
2add8bb7f77cc3721e910c73cc55a7024be8d06098eb77506d0a2ccc04275b8d
from django.contrib.auth.models import User from django.contrib.flatpages.models import FlatPage from django.contrib.sites.models import Site from django.test import Client, TestCase, modify_settings, override_settings from .settings import FLATPAGES_TEMPLATES @modify_settings(INSTALLED_APPS={"append": "django.contrib.flatpages"}) @override_settings( LOGIN_URL="/accounts/login/", MIDDLEWARE=[ "django.middleware.common.CommonMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.contrib.flatpages.middleware.FlatpageFallbackMiddleware", ], ROOT_URLCONF="flatpages_tests.urls", CSRF_FAILURE_VIEW="django.views.csrf.csrf_failure", TEMPLATES=FLATPAGES_TEMPLATES, SITE_ID=1, ) class FlatpageCSRFTests(TestCase): @classmethod def setUpTestData(cls): # don't use the manager because we want to ensure the site exists # with pk=1, regardless of whether or not it already exists. cls.site1 = Site(pk=1, domain="example.com", name="example.com") cls.site1.save() cls.fp1 = FlatPage.objects.create( url="/flatpage/", title="A Flatpage", content="Isn't it flat!", enable_comments=False, template_name="", registration_required=False, ) cls.fp2 = FlatPage.objects.create( url="/location/flatpage/", title="A Nested Flatpage", content="Isn't it flat and deep!", enable_comments=False, template_name="", registration_required=False, ) cls.fp3 = FlatPage.objects.create( url="/sekrit/", title="Sekrit Flatpage", content="Isn't it sekrit!", enable_comments=False, template_name="", registration_required=True, ) cls.fp4 = FlatPage.objects.create( url="/location/sekrit/", title="Sekrit Nested Flatpage", content="Isn't it sekrit and deep!", enable_comments=False, template_name="", registration_required=True, ) cls.fp1.sites.add(cls.site1) cls.fp2.sites.add(cls.site1) cls.fp3.sites.add(cls.site1) cls.fp4.sites.add(cls.site1) def setUp(self): self.client = Client(enforce_csrf_checks=True) def test_view_flatpage(self): "A flatpage can be served through a view, even when the middleware is in use" response = self.client.get("/flatpage_root/flatpage/") self.assertContains(response, "<p>Isn't it flat!</p>") def test_view_non_existent_flatpage(self): """ A nonexistent flatpage raises 404 when served through a view, even when the middleware is in use. """ response = self.client.get("/flatpage_root/no_such_flatpage/") self.assertEqual(response.status_code, 404) def test_view_authenticated_flatpage(self): "A flatpage served through a view can require authentication" response = self.client.get("/flatpage_root/sekrit/") self.assertRedirects(response, "/accounts/login/?next=/flatpage_root/sekrit/") user = User.objects.create_user("testuser", "[email protected]", "s3krit") self.client.force_login(user) response = self.client.get("/flatpage_root/sekrit/") self.assertContains(response, "<p>Isn't it sekrit!</p>") def test_fallback_flatpage(self): "A flatpage can be served by the fallback middleware" response = self.client.get("/flatpage/") self.assertContains(response, "<p>Isn't it flat!</p>") def test_fallback_non_existent_flatpage(self): """ A nonexistent flatpage raises a 404 when served by the fallback middleware. """ response = self.client.get("/no_such_flatpage/") self.assertEqual(response.status_code, 404) def test_post_view_flatpage(self): """ POSTing to a flatpage served through a view will raise a CSRF error if no token is provided. """ response = self.client.post("/flatpage_root/flatpage/") self.assertEqual(response.status_code, 403) def test_post_fallback_flatpage(self): """ POSTing to a flatpage served by the middleware will raise a CSRF error if no token is provided. """ response = self.client.post("/flatpage/") self.assertEqual(response.status_code, 403) def test_post_unknown_page(self): "POSTing to an unknown page isn't caught as a 403 CSRF error" response = self.client.post("/no_such_page/") self.assertEqual(response.status_code, 404)
205f39e9b55f2f945d7523db64f6c4f0d9d424565251d10e10de3d5c582ad6e2
from django.contrib.flatpages import views from django.urls import path urlpatterns = [ path("flatpage/", views.flatpage, {"url": "/hardcoded/"}), ]
88903ba6870e9c439409946d6f18bd1c928ec89f65df00a8b4853c40940524a1
from django.urls import include, path urlpatterns = [ path("flatpage", include("django.contrib.flatpages.urls")), ]