hash
stringlengths
64
64
content
stringlengths
0
1.51M
4236a8750a4f6768e34d6e313cc8b1732eeda96b401989a07f433852cb573c7e
import copy import unittest from io import StringIO from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.db import ( DEFAULT_DB_ALIAS, DatabaseError, NotSupportedError, connection, connections, ) from django.db.backends.base.base import BaseDatabaseWrapper from django.test import TestCase, override_settings @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests") class Tests(TestCase): databases = {"default", "other"} def test_nodb_cursor(self): """ The _nodb_cursor() fallbacks to the default connection database when access to the 'postgres' database is not granted. """ orig_connect = BaseDatabaseWrapper.connect def mocked_connect(self): if self.settings_dict["NAME"] is None: raise DatabaseError() return orig_connect(self) with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) self.assertIsNone(cursor.db.settings_dict["NAME"]) self.assertIs(cursor.closed, True) self.assertIsNone(cursor.db.connection) # Now assume the 'postgres' db isn't available msg = ( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' " "database and will use the first PostgreSQL database instead." ) with self.assertWarnsMessage(RuntimeWarning, msg): with mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ): with mock.patch.object( connection, "settings_dict", {**connection.settings_dict, "NAME": "postgres"}, ): with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) self.assertIs(cursor.closed, True) self.assertIsNone(cursor.db.connection) self.assertIsNotNone(cursor.db.settings_dict["NAME"]) self.assertEqual( cursor.db.settings_dict["NAME"], connections["other"].settings_dict["NAME"] ) # Cursor is yielded only for the first PostgreSQL database. with self.assertWarnsMessage(RuntimeWarning, msg): with mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ): with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) def test_nodb_cursor_raises_postgres_authentication_failure(self): """ _nodb_cursor() re-raises authentication failure to the 'postgres' db when other connection to the PostgreSQL database isn't available. """ def mocked_connect(self): raise DatabaseError() def mocked_all(self): test_connection = copy.copy(connections[DEFAULT_DB_ALIAS]) test_connection.settings_dict = copy.deepcopy(connection.settings_dict) test_connection.settings_dict["NAME"] = "postgres" return [test_connection] msg = ( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' " "database and will use the first PostgreSQL database instead." ) with self.assertWarnsMessage(RuntimeWarning, msg): mocker_connections_all = mock.patch( "django.utils.connection.BaseConnectionHandler.all", side_effect=mocked_all, autospec=True, ) mocker_connect = mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ) with mocker_connections_all, mocker_connect: with self.assertRaises(DatabaseError): with connection._nodb_cursor(): pass def test_nodb_cursor_reraise_exceptions(self): with self.assertRaisesMessage(DatabaseError, "exception"): with connection._nodb_cursor(): raise DatabaseError("exception") def test_database_name_too_long(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() max_name_length = connection.ops.max_name_length() settings["NAME"] = "a" + (max_name_length * "a") msg = ( "The database name '%s' (%d characters) is longer than " "PostgreSQL's limit of %s characters. Supply a shorter NAME in " "settings.DATABASES." ) % (settings["NAME"], max_name_length + 1, max_name_length) with self.assertRaisesMessage(ImproperlyConfigured, msg): DatabaseWrapper(settings).get_connection_params() def test_database_name_empty(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["NAME"] = "" msg = ( "settings.DATABASES is improperly configured. Please supply the " "NAME or OPTIONS['service'] value." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): DatabaseWrapper(settings).get_connection_params() def test_service_name(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["OPTIONS"] = {"service": "my_service"} settings["NAME"] = "" params = DatabaseWrapper(settings).get_connection_params() self.assertEqual(params["service"], "my_service") self.assertNotIn("database", params) def test_service_name_default_db(self): # None is used to connect to the default 'postgres' db. from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["NAME"] = None settings["OPTIONS"] = {"service": "django_test"} params = DatabaseWrapper(settings).get_connection_params() self.assertEqual(params["database"], "postgres") self.assertNotIn("service", params) def test_connect_and_rollback(self): """ PostgreSQL shouldn't roll back SET TIME ZONE, even if the first transaction is rolled back (#17062). """ new_connection = connection.copy() try: # Ensure the database default time zone is different than # the time zone in new_connection.settings_dict. We can # get the default time zone by reset & show. with new_connection.cursor() as cursor: cursor.execute("RESET TIMEZONE") cursor.execute("SHOW TIMEZONE") db_default_tz = cursor.fetchone()[0] new_tz = "Europe/Paris" if db_default_tz == "UTC" else "UTC" new_connection.close() # Invalidate timezone name cache, because the setting_changed # handler cannot know about new_connection. del new_connection.timezone_name # Fetch a new connection with the new_tz as default # time zone, run a query and rollback. with self.settings(TIME_ZONE=new_tz): new_connection.set_autocommit(False) new_connection.rollback() # Now let's see if the rollback rolled back the SET TIME ZONE. with new_connection.cursor() as cursor: cursor.execute("SHOW TIMEZONE") tz = cursor.fetchone()[0] self.assertEqual(new_tz, tz) finally: new_connection.close() def test_connect_non_autocommit(self): """ The connection wrapper shouldn't believe that autocommit is enabled after setting the time zone when AUTOCOMMIT is False (#21452). """ new_connection = connection.copy() new_connection.settings_dict["AUTOCOMMIT"] = False try: # Open a database connection. with new_connection.cursor(): self.assertFalse(new_connection.get_autocommit()) finally: new_connection.close() def test_connect_isolation_level(self): """ The transaction level can be configured with DATABASES ['OPTIONS']['isolation_level']. """ from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE as serializable # Since this is a django.test.TestCase, a transaction is in progress # and the isolation level isn't reported as 0. This test assumes that # PostgreSQL is configured with the default isolation level. # Check the level on the psycopg2 connection, not the Django wrapper. self.assertIsNone(connection.connection.isolation_level) new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["isolation_level"] = serializable try: # Start a transaction so the isolation level isn't reported as 0. new_connection.set_autocommit(False) # Check the level on the psycopg2 connection, not the Django wrapper. self.assertEqual(new_connection.connection.isolation_level, serializable) finally: new_connection.close() def test_connect_no_is_usable_checks(self): new_connection = connection.copy() try: with mock.patch.object(new_connection, "is_usable") as is_usable: new_connection.connect() is_usable.assert_not_called() finally: new_connection.close() def _select(self, val): with connection.cursor() as cursor: cursor.execute("SELECT %s", (val,)) return cursor.fetchone()[0] def test_select_ascii_array(self): a = ["awef"] b = self._select(a) self.assertEqual(a[0], b[0]) def test_select_unicode_array(self): a = ["ᄲawef"] b = self._select(a) self.assertEqual(a[0], b[0]) def test_lookup_cast(self): from django.db.backends.postgresql.operations import DatabaseOperations do = DatabaseOperations(connection=None) lookups = ( "iexact", "contains", "icontains", "startswith", "istartswith", "endswith", "iendswith", "regex", "iregex", ) for lookup in lookups: with self.subTest(lookup=lookup): self.assertIn("::text", do.lookup_cast(lookup)) for lookup in lookups: for field_type in ("CICharField", "CIEmailField", "CITextField"): with self.subTest(lookup=lookup, field_type=field_type): self.assertIn( "::citext", do.lookup_cast(lookup, internal_type=field_type) ) def test_correct_extraction_psycopg2_version(self): from django.db.backends.postgresql.base import psycopg2_version with mock.patch("psycopg2.__version__", "4.2.1 (dt dec pq3 ext lo64)"): self.assertEqual(psycopg2_version(), (4, 2, 1)) with mock.patch("psycopg2.__version__", "4.2b0.dev1 (dt dec pq3 ext lo64)"): self.assertEqual(psycopg2_version(), (4, 2)) @override_settings(DEBUG=True) def test_copy_cursors(self): out = StringIO() copy_expert_sql = "COPY django_session TO STDOUT (FORMAT CSV, HEADER)" with connection.cursor() as cursor: cursor.copy_expert(copy_expert_sql, out) cursor.copy_to(out, "django_session") self.assertEqual( [q["sql"] for q in connection.queries], [copy_expert_sql, "COPY django_session TO STDOUT"], ) def test_get_database_version(self): new_connection = connection.copy() new_connection.pg_version = 110009 self.assertEqual(new_connection.get_database_version(), (11, 9)) @mock.patch.object(connection, "get_database_version", return_value=(10,)) def test_check_database_version_supported(self, mocked_get_database_version): msg = "PostgreSQL 11 or later is required (found 10)." with self.assertRaisesMessage(NotSupportedError, msg): connection.check_database_version_supported() self.assertTrue(mocked_get_database_version.called)
181592fa52fecf1c56c1f595721d01195d04dfdafb9aea4f1c0116b6eafb0db3
import ctypes import itertools import json import pickle import random from binascii import a2b_hex from io import BytesIO from unittest import mock, skipIf from django.contrib.gis import gdal from django.contrib.gis.geos import ( GeometryCollection, GEOSException, GEOSGeometry, LinearRing, LineString, MultiLineString, MultiPoint, MultiPolygon, Point, Polygon, fromfile, fromstr, ) from django.contrib.gis.geos.libgeos import geos_version_tuple from django.contrib.gis.shortcuts import numpy from django.template import Context from django.template.engine import Engine from django.test import SimpleTestCase from ..test_data import TestDataMixin class GEOSTest(SimpleTestCase, TestDataMixin): def test_wkt(self): "Testing WKT output." for g in self.geometries.wkt_out: geom = fromstr(g.wkt) if geom.hasz: self.assertEqual(g.ewkt, geom.wkt) def test_wkt_invalid(self): msg = "String input unrecognized as WKT EWKT, and HEXEWKB." with self.assertRaisesMessage(ValueError, msg): fromstr("POINT(٠٠١ ٠)") with self.assertRaisesMessage(ValueError, msg): fromstr("SRID=٧٥٨٣;POINT(100 0)") def test_hex(self): "Testing HEX output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) self.assertEqual(g.hex, geom.hex.decode()) def test_hexewkb(self): "Testing (HEX)EWKB output." # For testing HEX(EWKB). ogc_hex = b"01010000000000000000000000000000000000F03F" ogc_hex_3d = b"01010000800000000000000000000000000000F03F0000000000000040" # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));` hexewkb_2d = b"0101000020E61000000000000000000000000000000000F03F" # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));` hexewkb_3d = ( b"01010000A0E61000000000000000000000000000000000F03F0000000000000040" ) pnt_2d = Point(0, 1, srid=4326) pnt_3d = Point(0, 1, 2, srid=4326) # OGC-compliant HEX will not have SRID value. self.assertEqual(ogc_hex, pnt_2d.hex) self.assertEqual(ogc_hex_3d, pnt_3d.hex) # HEXEWKB should be appropriate for its dimension -- have to use an # a WKBWriter w/dimension set accordingly, else GEOS will insert # garbage into 3D coordinate if there is none. self.assertEqual(hexewkb_2d, pnt_2d.hexewkb) self.assertEqual(hexewkb_3d, pnt_3d.hexewkb) self.assertIs(GEOSGeometry(hexewkb_3d).hasz, True) # Same for EWKB. self.assertEqual(memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb) self.assertEqual(memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb) # Redundant sanity check. self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid) def test_kml(self): "Testing KML output." for tg in self.geometries.wkt_out: geom = fromstr(tg.wkt) kml = getattr(tg, "kml", False) if kml: self.assertEqual(kml, geom.kml) def test_errors(self): "Testing the Error handlers." # string-based for err in self.geometries.errors: with self.assertRaises((GEOSException, ValueError)): fromstr(err.wkt) # Bad WKB with self.assertRaises(GEOSException): GEOSGeometry(memoryview(b"0")) class NotAGeometry: pass # Some other object with self.assertRaises(TypeError): GEOSGeometry(NotAGeometry()) # None with self.assertRaises(TypeError): GEOSGeometry(None) def test_wkb(self): "Testing WKB output." for g in self.geometries.hex_wkt: geom = fromstr(g.wkt) wkb = geom.wkb self.assertEqual(wkb.hex().upper(), g.hex) def test_create_hex(self): "Testing creation from HEX." for g in self.geometries.hex_wkt: geom_h = GEOSGeometry(g.hex) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_create_wkb(self): "Testing creation from WKB." for g in self.geometries.hex_wkt: wkb = memoryview(bytes.fromhex(g.hex)) geom_h = GEOSGeometry(wkb) # we need to do this so decimal places get normalized geom_t = fromstr(g.wkt) self.assertEqual(geom_t.wkt, geom_h.wkt) def test_ewkt(self): "Testing EWKT." srids = (-1, 32140) for srid in srids: for p in self.geometries.polygons: ewkt = "SRID=%d;%s" % (srid, p.wkt) poly = fromstr(ewkt) self.assertEqual(srid, poly.srid) self.assertEqual(srid, poly.shell.srid) self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export def test_json(self): "Testing GeoJSON input/output (via GDAL)." for g in self.geometries.json_geoms: geom = GEOSGeometry(g.wkt) if not hasattr(g, "not_equal"): # Loading jsons to prevent decimal differences self.assertEqual(json.loads(g.json), json.loads(geom.json)) self.assertEqual(json.loads(g.json), json.loads(geom.geojson)) self.assertEqual(GEOSGeometry(g.wkt, 4326), GEOSGeometry(geom.json)) def test_json_srid(self): geojson_data = { "type": "Point", "coordinates": [2, 49], "crs": { "type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::4322"}, }, } self.assertEqual( GEOSGeometry(json.dumps(geojson_data)), Point(2, 49, srid=4322) ) def test_fromfile(self): "Testing the fromfile() factory." ref_pnt = GEOSGeometry("POINT(5 23)") wkt_f = BytesIO() wkt_f.write(ref_pnt.wkt.encode()) wkb_f = BytesIO() wkb_f.write(bytes(ref_pnt.wkb)) # Other tests use `fromfile()` on string filenames so those # aren't tested here. for fh in (wkt_f, wkb_f): fh.seek(0) pnt = fromfile(fh) self.assertEqual(ref_pnt, pnt) def test_eq(self): "Testing equivalence." p = fromstr("POINT(5 23)") self.assertEqual(p, p.wkt) self.assertNotEqual(p, "foo") ls = fromstr("LINESTRING(0 0, 1 1, 5 5)") self.assertEqual(ls, ls.wkt) self.assertNotEqual(p, "bar") self.assertEqual(p, "POINT(5.0 23.0)") # Error shouldn't be raise on equivalence testing with # an invalid type. for g in (p, ls): self.assertIsNotNone(g) self.assertNotEqual(g, {"foo": "bar"}) self.assertIsNot(g, False) def test_hash(self): point_1 = Point(5, 23) point_2 = Point(5, 23, srid=4326) point_3 = Point(5, 23, srid=32632) multipoint_1 = MultiPoint(point_1, srid=4326) multipoint_2 = MultiPoint(point_2) multipoint_3 = MultiPoint(point_3) self.assertNotEqual(hash(point_1), hash(point_2)) self.assertNotEqual(hash(point_1), hash(point_3)) self.assertNotEqual(hash(point_2), hash(point_3)) self.assertNotEqual(hash(multipoint_1), hash(multipoint_2)) self.assertEqual(hash(multipoint_2), hash(multipoint_3)) self.assertNotEqual(hash(multipoint_1), hash(point_1)) self.assertNotEqual(hash(multipoint_2), hash(point_2)) self.assertNotEqual(hash(multipoint_3), hash(point_3)) def test_eq_with_srid(self): "Testing non-equivalence with different srids." p0 = Point(5, 23) p1 = Point(5, 23, srid=4326) p2 = Point(5, 23, srid=32632) # GEOS self.assertNotEqual(p0, p1) self.assertNotEqual(p1, p2) # EWKT self.assertNotEqual(p0, p1.ewkt) self.assertNotEqual(p1, p0.ewkt) self.assertNotEqual(p1, p2.ewkt) # Equivalence with matching SRIDs self.assertEqual(p2, p2) self.assertEqual(p2, p2.ewkt) # WKT contains no SRID so will not equal self.assertNotEqual(p2, p2.wkt) # SRID of 0 self.assertEqual(p0, "SRID=0;POINT (5 23)") self.assertNotEqual(p1, "SRID=0;POINT (5 23)") def test_points(self): "Testing Point objects." prev = fromstr("POINT(0 0)") for p in self.geometries.points: # Creating the point from the WKT pnt = fromstr(p.wkt) self.assertEqual(pnt.geom_type, "Point") self.assertEqual(pnt.geom_typeid, 0) self.assertEqual(pnt.dims, 0) self.assertEqual(p.x, pnt.x) self.assertEqual(p.y, pnt.y) self.assertEqual(pnt, fromstr(p.wkt)) self.assertIs(pnt == prev, False) # Use assertIs() to test __eq__. # Making sure that the point's X, Y components are what we expect self.assertAlmostEqual(p.x, pnt.tuple[0], 9) self.assertAlmostEqual(p.y, pnt.tuple[1], 9) # Testing the third dimension, and getting the tuple arguments if hasattr(p, "z"): self.assertIs(pnt.hasz, True) self.assertEqual(p.z, pnt.z) self.assertEqual(p.z, pnt.tuple[2], 9) tup_args = (p.x, p.y, p.z) set_tup1 = (2.71, 3.14, 5.23) set_tup2 = (5.23, 2.71, 3.14) else: self.assertIs(pnt.hasz, False) self.assertIsNone(pnt.z) tup_args = (p.x, p.y) set_tup1 = (2.71, 3.14) set_tup2 = (3.14, 2.71) # Centroid operation on point should be point itself self.assertEqual(p.centroid, pnt.centroid.tuple) # Now testing the different constructors pnt2 = Point(tup_args) # e.g., Point((1, 2)) pnt3 = Point(*tup_args) # e.g., Point(1, 2) self.assertEqual(pnt, pnt2) self.assertEqual(pnt, pnt3) # Now testing setting the x and y pnt.y = 3.14 pnt.x = 2.71 self.assertEqual(3.14, pnt.y) self.assertEqual(2.71, pnt.x) # Setting via the tuple/coords property pnt.tuple = set_tup1 self.assertEqual(set_tup1, pnt.tuple) pnt.coords = set_tup2 self.assertEqual(set_tup2, pnt.coords) prev = pnt # setting the previous geometry def test_point_reverse(self): point = GEOSGeometry("POINT(144.963 -37.8143)", 4326) self.assertEqual(point.srid, 4326) point.reverse() self.assertEqual(point.ewkt, "SRID=4326;POINT (-37.8143 144.963)") def test_multipoints(self): "Testing MultiPoint objects." for mp in self.geometries.multipoints: mpnt = fromstr(mp.wkt) self.assertEqual(mpnt.geom_type, "MultiPoint") self.assertEqual(mpnt.geom_typeid, 4) self.assertEqual(mpnt.dims, 0) self.assertAlmostEqual(mp.centroid[0], mpnt.centroid.tuple[0], 9) self.assertAlmostEqual(mp.centroid[1], mpnt.centroid.tuple[1], 9) with self.assertRaises(IndexError): mpnt.__getitem__(len(mpnt)) self.assertEqual(mp.centroid, mpnt.centroid.tuple) self.assertEqual(mp.coords, tuple(m.tuple for m in mpnt)) for p in mpnt: self.assertEqual(p.geom_type, "Point") self.assertEqual(p.geom_typeid, 0) self.assertIs(p.empty, False) self.assertIs(p.valid, True) def test_linestring(self): "Testing LineString objects." prev = fromstr("POINT(0 0)") for line in self.geometries.linestrings: ls = fromstr(line.wkt) self.assertEqual(ls.geom_type, "LineString") self.assertEqual(ls.geom_typeid, 1) self.assertEqual(ls.dims, 1) self.assertIs(ls.empty, False) self.assertIs(ls.ring, False) if hasattr(line, "centroid"): self.assertEqual(line.centroid, ls.centroid.tuple) if hasattr(line, "tup"): self.assertEqual(line.tup, ls.tuple) self.assertEqual(ls, fromstr(line.wkt)) self.assertIs(ls == prev, False) # Use assertIs() to test __eq__. with self.assertRaises(IndexError): ls.__getitem__(len(ls)) prev = ls # Creating a LineString from a tuple, list, and numpy array self.assertEqual(ls, LineString(ls.tuple)) # tuple self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list # Point individual arguments self.assertEqual( ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt ) if numpy: self.assertEqual( ls, LineString(numpy.array(ls.tuple)) ) # as numpy array with self.assertRaisesMessage( TypeError, "Each coordinate should be a sequence (list or tuple)" ): LineString((0, 0)) with self.assertRaisesMessage( ValueError, "LineString requires at least 2 points, got 1." ): LineString([(0, 0)]) if numpy: with self.assertRaisesMessage( ValueError, "LineString requires at least 2 points, got 1." ): LineString(numpy.array([(0, 0)])) with mock.patch("django.contrib.gis.geos.linestring.numpy", False): with self.assertRaisesMessage( TypeError, "Invalid initialization input for LineStrings." ): LineString("wrong input") # Test __iter__(). self.assertEqual( list(LineString((0, 0), (1, 1), (2, 2))), [(0, 0), (1, 1), (2, 2)] ) def test_linestring_reverse(self): line = GEOSGeometry("LINESTRING(144.963 -37.8143,151.2607 -33.887)", 4326) self.assertEqual(line.srid, 4326) line.reverse() self.assertEqual( line.ewkt, "SRID=4326;LINESTRING (151.2607 -33.887, 144.963 -37.8143)" ) def _test_is_counterclockwise(self): lr = LinearRing((0, 0), (1, 0), (0, 1), (0, 0)) self.assertIs(lr.is_counterclockwise, True) lr.reverse() self.assertIs(lr.is_counterclockwise, False) msg = "Orientation of an empty LinearRing cannot be determined." with self.assertRaisesMessage(ValueError, msg): LinearRing().is_counterclockwise @skipIf(geos_version_tuple() < (3, 7), "GEOS >= 3.7.0 is required") def test_is_counterclockwise(self): self._test_is_counterclockwise() @skipIf(geos_version_tuple() < (3, 7), "GEOS >= 3.7.0 is required") def test_is_counterclockwise_geos_error(self): with mock.patch("django.contrib.gis.geos.prototypes.cs_is_ccw") as mocked: mocked.return_value = 0 mocked.func_name = "GEOSCoordSeq_isCCW" msg = 'Error encountered in GEOS C function "GEOSCoordSeq_isCCW".' with self.assertRaisesMessage(GEOSException, msg): LinearRing((0, 0), (1, 0), (0, 1), (0, 0)).is_counterclockwise @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.6.9") def test_is_counterclockwise_fallback(self): self._test_is_counterclockwise() def test_multilinestring(self): "Testing MultiLineString objects." prev = fromstr("POINT(0 0)") for line in self.geometries.multilinestrings: ml = fromstr(line.wkt) self.assertEqual(ml.geom_type, "MultiLineString") self.assertEqual(ml.geom_typeid, 5) self.assertEqual(ml.dims, 1) self.assertAlmostEqual(line.centroid[0], ml.centroid.x, 9) self.assertAlmostEqual(line.centroid[1], ml.centroid.y, 9) self.assertEqual(ml, fromstr(line.wkt)) self.assertIs(ml == prev, False) # Use assertIs() to test __eq__. prev = ml for ls in ml: self.assertEqual(ls.geom_type, "LineString") self.assertEqual(ls.geom_typeid, 1) self.assertIs(ls.empty, False) with self.assertRaises(IndexError): ml.__getitem__(len(ml)) self.assertEqual(ml.wkt, MultiLineString(*tuple(s.clone() for s in ml)).wkt) self.assertEqual( ml, MultiLineString(*tuple(LineString(s.tuple) for s in ml)) ) def test_linearring(self): "Testing LinearRing objects." for rr in self.geometries.linearrings: lr = fromstr(rr.wkt) self.assertEqual(lr.geom_type, "LinearRing") self.assertEqual(lr.geom_typeid, 2) self.assertEqual(lr.dims, 1) self.assertEqual(rr.n_p, len(lr)) self.assertIs(lr.valid, True) self.assertIs(lr.empty, False) # Creating a LinearRing from a tuple, list, and numpy array self.assertEqual(lr, LinearRing(lr.tuple)) self.assertEqual(lr, LinearRing(*lr.tuple)) self.assertEqual(lr, LinearRing([list(tup) for tup in lr.tuple])) if numpy: self.assertEqual(lr, LinearRing(numpy.array(lr.tuple))) with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 3." ): LinearRing((0, 0), (1, 1), (0, 0)) with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 1." ): LinearRing([(0, 0)]) if numpy: with self.assertRaisesMessage( ValueError, "LinearRing requires at least 4 points, got 1." ): LinearRing(numpy.array([(0, 0)])) def test_linearring_json(self): self.assertJSONEqual( LinearRing((0, 0), (0, 1), (1, 1), (0, 0)).json, '{"coordinates": [[0, 0], [0, 1], [1, 1], [0, 0]], "type": "LineString"}', ) def test_polygons_from_bbox(self): "Testing `from_bbox` class method." bbox = (-180, -90, 180, 90) p = Polygon.from_bbox(bbox) self.assertEqual(bbox, p.extent) # Testing numerical precision x = 3.14159265358979323 bbox = (0, 0, 1, x) p = Polygon.from_bbox(bbox) y = p.extent[-1] self.assertEqual(format(x, ".13f"), format(y, ".13f")) def test_polygons(self): "Testing Polygon objects." prev = fromstr("POINT(0 0)") for p in self.geometries.polygons: # Creating the Polygon, testing its properties. poly = fromstr(p.wkt) self.assertEqual(poly.geom_type, "Polygon") self.assertEqual(poly.geom_typeid, 3) self.assertEqual(poly.dims, 2) self.assertIs(poly.empty, False) self.assertIs(poly.ring, False) self.assertEqual(p.n_i, poly.num_interior_rings) self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__ self.assertEqual(p.n_p, poly.num_points) # Area & Centroid self.assertAlmostEqual(p.area, poly.area, 9) self.assertAlmostEqual(p.centroid[0], poly.centroid.tuple[0], 9) self.assertAlmostEqual(p.centroid[1], poly.centroid.tuple[1], 9) # Testing the geometry equivalence self.assertEqual(poly, fromstr(p.wkt)) # Should not be equal to previous geometry self.assertIs(poly == prev, False) # Use assertIs() to test __eq__. self.assertIs(poly != prev, True) # Use assertIs() to test __ne__. # Testing the exterior ring ring = poly.exterior_ring self.assertEqual(ring.geom_type, "LinearRing") self.assertEqual(ring.geom_typeid, 2) if p.ext_ring_cs: self.assertEqual(p.ext_ring_cs, ring.tuple) self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__ # Testing __getitem__ and __setitem__ on invalid indices with self.assertRaises(IndexError): poly.__getitem__(len(poly)) with self.assertRaises(IndexError): poly.__setitem__(len(poly), False) with self.assertRaises(IndexError): poly.__getitem__(-1 * len(poly) - 1) # Testing __iter__ for r in poly: self.assertEqual(r.geom_type, "LinearRing") self.assertEqual(r.geom_typeid, 2) # Testing polygon construction. with self.assertRaises(TypeError): Polygon(0, [1, 2, 3]) with self.assertRaises(TypeError): Polygon("foo") # Polygon(shell, (hole1, ... holeN)) ext_ring, *int_rings = poly self.assertEqual(poly, Polygon(ext_ring, int_rings)) # Polygon(shell_tuple, hole_tuple1, ... , hole_tupleN) ring_tuples = tuple(r.tuple for r in poly) self.assertEqual(poly, Polygon(*ring_tuples)) # Constructing with tuples of LinearRings. self.assertEqual(poly.wkt, Polygon(*tuple(r for r in poly)).wkt) self.assertEqual( poly.wkt, Polygon(*tuple(LinearRing(r.tuple) for r in poly)).wkt ) def test_polygons_templates(self): # Accessing Polygon attributes in templates should work. engine = Engine() template = engine.from_string("{{ polygons.0.wkt }}") polygons = [fromstr(p.wkt) for p in self.geometries.multipolygons[:2]] content = template.render(Context({"polygons": polygons})) self.assertIn("MULTIPOLYGON (((100", content) def test_polygon_comparison(self): p1 = Polygon(((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) p2 = Polygon(((0, 0), (0, 1), (1, 0), (0, 0))) self.assertGreater(p1, p2) self.assertLess(p2, p1) p3 = Polygon(((0, 0), (0, 1), (1, 1), (2, 0), (0, 0))) p4 = Polygon(((0, 0), (0, 1), (2, 2), (1, 0), (0, 0))) self.assertGreater(p4, p3) self.assertLess(p3, p4) def test_multipolygons(self): "Testing MultiPolygon objects." fromstr("POINT (0 0)") for mp in self.geometries.multipolygons: mpoly = fromstr(mp.wkt) self.assertEqual(mpoly.geom_type, "MultiPolygon") self.assertEqual(mpoly.geom_typeid, 6) self.assertEqual(mpoly.dims, 2) self.assertEqual(mp.valid, mpoly.valid) if mp.valid: self.assertEqual(mp.num_geom, mpoly.num_geom) self.assertEqual(mp.n_p, mpoly.num_coords) self.assertEqual(mp.num_geom, len(mpoly)) with self.assertRaises(IndexError): mpoly.__getitem__(len(mpoly)) for p in mpoly: self.assertEqual(p.geom_type, "Polygon") self.assertEqual(p.geom_typeid, 3) self.assertIs(p.valid, True) self.assertEqual( mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt ) def test_memory_hijinks(self): "Testing Geometry __del__() on rings and polygons." # #### Memory issues with rings and poly # These tests are needed to ensure sanity with writable geometries. # Getting a polygon with interior rings, and pulling out the interior rings poly = fromstr(self.geometries.polygons[1].wkt) ring1 = poly[0] ring2 = poly[1] # These deletes should be 'harmless' since they are done on child geometries del ring1 del ring2 ring1 = poly[0] ring2 = poly[1] # Deleting the polygon del poly # Access to these rings is OK since they are clones. str(ring1) str(ring2) def test_coord_seq(self): "Testing Coordinate Sequence objects." for p in self.geometries.polygons: if p.ext_ring_cs: # Constructing the polygon and getting the coordinate sequence poly = fromstr(p.wkt) cs = poly.exterior_ring.coord_seq self.assertEqual( p.ext_ring_cs, cs.tuple ) # done in the Polygon test too. self.assertEqual( len(p.ext_ring_cs), len(cs) ) # Making sure __len__ works # Checks __getitem__ and __setitem__ for i in range(len(p.ext_ring_cs)): c1 = p.ext_ring_cs[i] # Expected value c2 = cs[i] # Value from coordseq self.assertEqual(c1, c2) # Constructing the test value to set the coordinate sequence with if len(c1) == 2: tset = (5, 23) else: tset = (5, 23, 8) cs[i] = tset # Making sure every set point matches what we expect for j in range(len(tset)): cs[i] = tset self.assertEqual(tset[j], cs[i][j]) def test_relate_pattern(self): "Testing relate() and relate_pattern()." g = fromstr("POINT (0 0)") with self.assertRaises(GEOSException): g.relate_pattern(0, "invalid pattern, yo") for rg in self.geometries.relate_geoms: a = fromstr(rg.wkt_a) b = fromstr(rg.wkt_b) self.assertEqual(rg.result, a.relate_pattern(b, rg.pattern)) self.assertEqual(rg.pattern, a.relate(b)) def test_intersection(self): "Testing intersects() and intersection()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) i1 = fromstr(self.geometries.intersect_geoms[i].wkt) self.assertIs(a.intersects(b), True) i2 = a.intersection(b) self.assertTrue(i1.equals(i2)) self.assertTrue(i1.equals(a & b)) # __and__ is intersection operator a &= b # testing __iand__ self.assertTrue(i1.equals(a)) def test_union(self): "Testing union()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = a.union(b) self.assertTrue(u1.equals(u2)) self.assertTrue(u1.equals(a | b)) # __or__ is union operator a |= b # testing __ior__ self.assertTrue(u1.equals(a)) def test_unary_union(self): "Testing unary_union." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = GeometryCollection(a, b).unary_union self.assertTrue(u1.equals(u2)) def test_difference(self): "Testing difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.diff_geoms[i].wkt) d2 = a.difference(b) self.assertTrue(d1.equals(d2)) self.assertTrue(d1.equals(a - b)) # __sub__ is difference operator a -= b # testing __isub__ self.assertTrue(d1.equals(a)) def test_symdifference(self): "Testing sym_difference()." for i in range(len(self.geometries.topology_geoms)): a = fromstr(self.geometries.topology_geoms[i].wkt_a) b = fromstr(self.geometries.topology_geoms[i].wkt_b) d1 = fromstr(self.geometries.sdiff_geoms[i].wkt) d2 = a.sym_difference(b) self.assertTrue(d1.equals(d2)) self.assertTrue( d1.equals(a ^ b) ) # __xor__ is symmetric difference operator a ^= b # testing __ixor__ self.assertTrue(d1.equals(a)) def test_buffer(self): bg = self.geometries.buffer_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer(bg.width, quadsegs=1.1) self._test_buffer(self.geometries.buffer_geoms, "buffer") def test_buffer_with_style(self): bg = self.geometries.buffer_with_style_geoms[0] g = fromstr(bg.wkt) # Can't use a floating-point for the number of quadsegs. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, quadsegs=1.1) # Can't use a floating-point for the end cap style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, end_cap_style=1.2) # Can't use a end cap style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, end_cap_style=55) # Can't use a floating-point for the join style. with self.assertRaises(ctypes.ArgumentError): g.buffer_with_style(bg.width, join_style=1.3) # Can't use a join style that is not in the enum. with self.assertRaises(GEOSException): g.buffer_with_style(bg.width, join_style=66) self._test_buffer( itertools.chain( self.geometries.buffer_geoms, self.geometries.buffer_with_style_geoms ), "buffer_with_style", ) def _test_buffer(self, geometries, buffer_method_name): for bg in geometries: g = fromstr(bg.wkt) # The buffer we expect exp_buf = fromstr(bg.buffer_wkt) # Constructing our buffer buf_kwargs = { kwarg_name: getattr(bg, kwarg_name) for kwarg_name in ( "width", "quadsegs", "end_cap_style", "join_style", "mitre_limit", ) if hasattr(bg, kwarg_name) } buf = getattr(g, buffer_method_name)(**buf_kwargs) self.assertEqual(exp_buf.num_coords, buf.num_coords) self.assertEqual(len(exp_buf), len(buf)) # Now assuring that each point in the buffer is almost equal for j in range(len(exp_buf)): exp_ring = exp_buf[j] buf_ring = buf[j] self.assertEqual(len(exp_ring), len(buf_ring)) for k in range(len(exp_ring)): # Asserting the X, Y of each point are almost equal (due to # floating point imprecision). self.assertAlmostEqual(exp_ring[k][0], buf_ring[k][0], 9) self.assertAlmostEqual(exp_ring[k][1], buf_ring[k][1], 9) def test_covers(self): poly = Polygon(((0, 0), (0, 10), (10, 10), (10, 0), (0, 0))) self.assertTrue(poly.covers(Point(5, 5))) self.assertFalse(poly.covers(Point(100, 100))) def test_closed(self): ls_closed = LineString((0, 0), (1, 1), (0, 0)) ls_not_closed = LineString((0, 0), (1, 1)) self.assertFalse(ls_not_closed.closed) self.assertTrue(ls_closed.closed) def test_srid(self): "Testing the SRID property and keyword." # Testing SRID keyword on Point pnt = Point(5, 23, srid=4326) self.assertEqual(4326, pnt.srid) pnt.srid = 3084 self.assertEqual(3084, pnt.srid) with self.assertRaises(ctypes.ArgumentError): pnt.srid = "4326" # Testing SRID keyword on fromstr(), and on Polygon rings. poly = fromstr(self.geometries.polygons[1].wkt, srid=4269) self.assertEqual(4269, poly.srid) for ring in poly: self.assertEqual(4269, ring.srid) poly.srid = 4326 self.assertEqual(4326, poly.shell.srid) # Testing SRID keyword on GeometryCollection gc = GeometryCollection( Point(5, 23), LineString((0, 0), (1.5, 1.5), (3, 3)), srid=32021 ) self.assertEqual(32021, gc.srid) for i in range(len(gc)): self.assertEqual(32021, gc[i].srid) # GEOS may get the SRID from HEXEWKB # 'POINT(5 23)' at SRID=4326 in hex form -- obtained from PostGIS # using `SELECT GeomFromText('POINT (5 23)', 4326);`. hex = "0101000020E610000000000000000014400000000000003740" p1 = fromstr(hex) self.assertEqual(4326, p1.srid) p2 = fromstr(p1.hex) self.assertIsNone(p2.srid) p3 = fromstr(p1.hex, srid=-1) # -1 is intended. self.assertEqual(-1, p3.srid) # Testing that geometry SRID could be set to its own value pnt_wo_srid = Point(1, 1) pnt_wo_srid.srid = pnt_wo_srid.srid # Input geometries that have an SRID. self.assertEqual(GEOSGeometry(pnt.ewkt, srid=pnt.srid).srid, pnt.srid) self.assertEqual(GEOSGeometry(pnt.ewkb, srid=pnt.srid).srid, pnt.srid) with self.assertRaisesMessage( ValueError, "Input geometry already has SRID: %d." % pnt.srid ): GEOSGeometry(pnt.ewkt, srid=1) with self.assertRaisesMessage( ValueError, "Input geometry already has SRID: %d." % pnt.srid ): GEOSGeometry(pnt.ewkb, srid=1) def test_custom_srid(self): """Test with a null srid and a srid unknown to GDAL.""" for srid in [None, 999999]: pnt = Point(111200, 220900, srid=srid) self.assertTrue( pnt.ewkt.startswith( ("SRID=%s;" % srid if srid else "") + "POINT (111200" ) ) self.assertIsInstance(pnt.ogr, gdal.OGRGeometry) self.assertIsNone(pnt.srs) # Test conversion from custom to a known srid c2w = gdal.CoordTransform( gdal.SpatialReference( "+proj=mill +lat_0=0 +lon_0=0 +x_0=0 +y_0=0 +R_A +ellps=WGS84 " "+datum=WGS84 +units=m +no_defs" ), gdal.SpatialReference(4326), ) new_pnt = pnt.transform(c2w, clone=True) self.assertEqual(new_pnt.srid, 4326) self.assertAlmostEqual(new_pnt.x, 1, 1) self.assertAlmostEqual(new_pnt.y, 2, 1) def test_mutable_geometries(self): "Testing the mutability of Polygons and Geometry Collections." # ### Testing the mutability of Polygons ### for p in self.geometries.polygons: poly = fromstr(p.wkt) # Should only be able to use __setitem__ with LinearRing geometries. with self.assertRaises(TypeError): poly.__setitem__(0, LineString((1, 1), (2, 2))) # Constructing the new shell by adding 500 to every point in the old shell. shell_tup = poly.shell.tuple new_coords = [] for point in shell_tup: new_coords.append((point[0] + 500.0, point[1] + 500.0)) new_shell = LinearRing(*tuple(new_coords)) # Assigning polygon's exterior ring w/the new shell poly.exterior_ring = new_shell str(new_shell) # new shell is still accessible self.assertEqual(poly.exterior_ring, new_shell) self.assertEqual(poly[0], new_shell) # ### Testing the mutability of Geometry Collections for tg in self.geometries.multipoints: mp = fromstr(tg.wkt) for i in range(len(mp)): # Creating a random point. pnt = mp[i] new = Point(random.randint(21, 100), random.randint(21, 100)) # Testing the assignment mp[i] = new str(new) # what was used for the assignment is still accessible self.assertEqual(mp[i], new) self.assertEqual(mp[i].wkt, new.wkt) self.assertNotEqual(pnt, mp[i]) # MultiPolygons involve much more memory management because each # Polygon w/in the collection has its own rings. for tg in self.geometries.multipolygons: mpoly = fromstr(tg.wkt) for i in range(len(mpoly)): poly = mpoly[i] old_poly = mpoly[i] # Offsetting the each ring in the polygon by 500. for j in range(len(poly)): r = poly[j] for k in range(len(r)): r[k] = (r[k][0] + 500.0, r[k][1] + 500.0) poly[j] = r self.assertNotEqual(mpoly[i], poly) # Testing the assignment mpoly[i] = poly str(poly) # Still accessible self.assertEqual(mpoly[i], poly) self.assertNotEqual(mpoly[i], old_poly) # Extreme (!!) __setitem__ -- no longer works, have to detect # in the first object that __setitem__ is called in the subsequent # objects -- maybe mpoly[0, 0, 0] = (3.14, 2.71)? # mpoly[0][0][0] = (3.14, 2.71) # self.assertEqual((3.14, 2.71), mpoly[0][0][0]) # Doing it more slowly.. # self.assertEqual((3.14, 2.71), mpoly[0].shell[0]) # del mpoly def test_point_list_assignment(self): p = Point(0, 0) p[:] = (1, 2, 3) self.assertEqual(p, Point(1, 2, 3)) p[:] = () self.assertEqual(p.wkt, Point()) p[:] = (1, 2) self.assertEqual(p.wkt, Point(1, 2)) with self.assertRaises(ValueError): p[:] = (1,) with self.assertRaises(ValueError): p[:] = (1, 2, 3, 4, 5) def test_linestring_list_assignment(self): ls = LineString((0, 0), (1, 1)) ls[:] = () self.assertEqual(ls, LineString()) ls[:] = ((0, 0), (1, 1), (2, 2)) self.assertEqual(ls, LineString((0, 0), (1, 1), (2, 2))) with self.assertRaises(ValueError): ls[:] = (1,) def test_linearring_list_assignment(self): ls = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) ls[:] = () self.assertEqual(ls, LinearRing()) ls[:] = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) self.assertEqual(ls, LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) with self.assertRaises(ValueError): ls[:] = ((0, 0), (1, 1), (2, 2)) def test_polygon_list_assignment(self): pol = Polygon() pol[:] = (((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)),) self.assertEqual( pol, Polygon( ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)), ), ) pol[:] = () self.assertEqual(pol, Polygon()) def test_geometry_collection_list_assignment(self): p = Point() gc = GeometryCollection() gc[:] = [p] self.assertEqual(gc, GeometryCollection(p)) gc[:] = () self.assertEqual(gc, GeometryCollection()) def test_threed(self): "Testing three-dimensional geometries." # Testing a 3D Point pnt = Point(2, 3, 8) self.assertEqual((2.0, 3.0, 8.0), pnt.coords) with self.assertRaises(TypeError): pnt.tuple = (1.0, 2.0) pnt.coords = (1.0, 2.0, 3.0) self.assertEqual((1.0, 2.0, 3.0), pnt.coords) # Testing a 3D LineString ls = LineString((2.0, 3.0, 8.0), (50.0, 250.0, -117.0)) self.assertEqual(((2.0, 3.0, 8.0), (50.0, 250.0, -117.0)), ls.tuple) with self.assertRaises(TypeError): ls.__setitem__(0, (1.0, 2.0)) ls[0] = (1.0, 2.0, 3.0) self.assertEqual((1.0, 2.0, 3.0), ls[0]) def test_distance(self): "Testing the distance() function." # Distance to self should be 0. pnt = Point(0, 0) self.assertEqual(0.0, pnt.distance(Point(0, 0))) # Distance should be 1 self.assertEqual(1.0, pnt.distance(Point(0, 1))) # Distance should be ~ sqrt(2) self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11) # Distances are from the closest vertex in each geometry -- # should be 3 (distance from (2, 2) to (5, 2)). ls1 = LineString((0, 0), (1, 1), (2, 2)) ls2 = LineString((5, 2), (6, 1), (7, 0)) self.assertEqual(3, ls1.distance(ls2)) def test_length(self): "Testing the length property." # Points have 0 length. pnt = Point(0, 0) self.assertEqual(0.0, pnt.length) # Should be ~ sqrt(2) ls = LineString((0, 0), (1, 1)) self.assertAlmostEqual(1.41421356237, ls.length, 11) # Should be circumference of Polygon poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0))) self.assertEqual(4.0, poly.length) # Should be sum of each element's length in collection. mpoly = MultiPolygon(poly.clone(), poly) self.assertEqual(8.0, mpoly.length) def test_emptyCollections(self): "Testing empty geometries and collections." geoms = [ GeometryCollection([]), fromstr("GEOMETRYCOLLECTION EMPTY"), GeometryCollection(), fromstr("POINT EMPTY"), Point(), fromstr("LINESTRING EMPTY"), LineString(), fromstr("POLYGON EMPTY"), Polygon(), fromstr("MULTILINESTRING EMPTY"), MultiLineString(), fromstr("MULTIPOLYGON EMPTY"), MultiPolygon(()), MultiPolygon(), ] if numpy: geoms.append(LineString(numpy.array([]))) for g in geoms: self.assertIs(g.empty, True) # Testing len() and num_geom. if isinstance(g, Polygon): self.assertEqual(1, len(g)) # Has one empty linear ring self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g[0])) elif isinstance(g, (Point, LineString)): self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g)) else: self.assertEqual(0, g.num_geom) self.assertEqual(0, len(g)) # Testing __getitem__ (doesn't work on Point or Polygon) if isinstance(g, Point): with self.assertRaises(IndexError): g.x elif isinstance(g, Polygon): lr = g.shell self.assertEqual("LINEARRING EMPTY", lr.wkt) self.assertEqual(0, len(lr)) self.assertIs(lr.empty, True) with self.assertRaises(IndexError): lr.__getitem__(0) else: with self.assertRaises(IndexError): g.__getitem__(0) def test_collection_dims(self): gc = GeometryCollection([]) self.assertEqual(gc.dims, -1) gc = GeometryCollection(Point(0, 0)) self.assertEqual(gc.dims, 0) gc = GeometryCollection(LineString((0, 0), (1, 1)), Point(0, 0)) self.assertEqual(gc.dims, 1) gc = GeometryCollection( LineString((0, 0), (1, 1)), Polygon(((0, 0), (0, 1), (1, 1), (0, 0))), Point(0, 0), ) self.assertEqual(gc.dims, 2) def test_collections_of_collections(self): "Testing GeometryCollection handling of other collections." # Creating a GeometryCollection WKT string composed of other # collections and polygons. coll = [mp.wkt for mp in self.geometries.multipolygons if mp.valid] coll.extend(mls.wkt for mls in self.geometries.multilinestrings) coll.extend(p.wkt for p in self.geometries.polygons) coll.extend(mp.wkt for mp in self.geometries.multipoints) gc_wkt = "GEOMETRYCOLLECTION(%s)" % ",".join(coll) # Should construct ok from WKT gc1 = GEOSGeometry(gc_wkt) # Should also construct ok from individual geometry arguments. gc2 = GeometryCollection(*tuple(g for g in gc1)) # And, they should be equal. self.assertEqual(gc1, gc2) def test_gdal(self): "Testing `ogr` and `srs` properties." g1 = fromstr("POINT(5 23)") self.assertIsInstance(g1.ogr, gdal.OGRGeometry) self.assertIsNone(g1.srs) g1_3d = fromstr("POINT(5 23 8)") self.assertIsInstance(g1_3d.ogr, gdal.OGRGeometry) self.assertEqual(g1_3d.ogr.z, 8) g2 = fromstr("LINESTRING(0 0, 5 5, 23 23)", srid=4326) self.assertIsInstance(g2.ogr, gdal.OGRGeometry) self.assertIsInstance(g2.srs, gdal.SpatialReference) self.assertEqual(g2.hex, g2.ogr.hex) self.assertEqual("WGS 84", g2.srs.name) def test_copy(self): "Testing use with the Python `copy` module." import copy poly = GEOSGeometry( "POLYGON((0 0, 0 23, 23 23, 23 0, 0 0), (5 5, 5 10, 10 10, 10 5, 5 5))" ) cpy1 = copy.copy(poly) cpy2 = copy.deepcopy(poly) self.assertNotEqual(poly._ptr, cpy1._ptr) self.assertNotEqual(poly._ptr, cpy2._ptr) def test_transform(self): "Testing `transform` method." orig = GEOSGeometry("POINT (-104.609 38.255)", 4326) trans = GEOSGeometry("POINT (992385.4472045 481455.4944650)", 2774) # Using a srid, a SpatialReference object, and a CoordTransform object # for transformations. t1, t2, t3 = orig.clone(), orig.clone(), orig.clone() t1.transform(trans.srid) t2.transform(gdal.SpatialReference("EPSG:2774")) ct = gdal.CoordTransform( gdal.SpatialReference("WGS84"), gdal.SpatialReference(2774) ) t3.transform(ct) # Testing use of the `clone` keyword. k1 = orig.clone() k2 = k1.transform(trans.srid, clone=True) self.assertEqual(k1, orig) self.assertNotEqual(k1, k2) # Different PROJ versions use different transformations, all are # correct as having a 1 meter accuracy. prec = -1 for p in (t1, t2, t3, k2): self.assertAlmostEqual(trans.x, p.x, prec) self.assertAlmostEqual(trans.y, p.y, prec) def test_transform_3d(self): p3d = GEOSGeometry("POINT (5 23 100)", 4326) p3d.transform(2774) self.assertAlmostEqual(p3d.z, 100, 3) def test_transform_noop(self): """Testing `transform` method (SRID match)""" # transform() should no-op if source & dest SRIDs match, # regardless of whether GDAL is available. g = GEOSGeometry("POINT (-104.609 38.255)", 4326) gt = g.tuple g.transform(4326) self.assertEqual(g.tuple, gt) self.assertEqual(g.srid, 4326) g = GEOSGeometry("POINT (-104.609 38.255)", 4326) g1 = g.transform(4326, clone=True) self.assertEqual(g1.tuple, g.tuple) self.assertEqual(g1.srid, 4326) self.assertIsNot(g1, g, "Clone didn't happen") def test_transform_nosrid(self): """Testing `transform` method (no SRID or negative SRID)""" g = GEOSGeometry("POINT (-104.609 38.255)", srid=None) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry("POINT (-104.609 38.255)", srid=None) with self.assertRaises(GEOSException): g.transform(2774, clone=True) g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1) with self.assertRaises(GEOSException): g.transform(2774) g = GEOSGeometry("POINT (-104.609 38.255)", srid=-1) with self.assertRaises(GEOSException): g.transform(2774, clone=True) def test_extent(self): "Testing `extent` method." # The xmin, ymin, xmax, ymax of the MultiPoint should be returned. mp = MultiPoint(Point(5, 23), Point(0, 0), Point(10, 50)) self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent) pnt = Point(5.23, 17.8) # Extent of points is just the point itself repeated. self.assertEqual((5.23, 17.8, 5.23, 17.8), pnt.extent) # Testing on the 'real world' Polygon. poly = fromstr(self.geometries.polygons[3].wkt) ring = poly.shell x, y = ring.x, ring.y xmin, ymin = min(x), min(y) xmax, ymax = max(x), max(y) self.assertEqual((xmin, ymin, xmax, ymax), poly.extent) def test_pickle(self): "Testing pickling and unpickling support." # Creating a list of test geometries for pickling, # and setting the SRID on some of them. def get_geoms(lst, srid=None): return [GEOSGeometry(tg.wkt, srid) for tg in lst] tgeoms = get_geoms(self.geometries.points) tgeoms.extend(get_geoms(self.geometries.multilinestrings, 4326)) tgeoms.extend(get_geoms(self.geometries.polygons, 3084)) tgeoms.extend(get_geoms(self.geometries.multipolygons, 3857)) tgeoms.append(Point(srid=4326)) tgeoms.append(Point()) for geom in tgeoms: s1 = pickle.dumps(geom) g1 = pickle.loads(s1) self.assertEqual(geom, g1) self.assertEqual(geom.srid, g1.srid) def test_prepared(self): "Testing PreparedGeometry support." # Creating a simple multipolygon and getting a prepared version. mpoly = GEOSGeometry( "MULTIPOLYGON(((0 0,0 5,5 5,5 0,0 0)),((5 5,5 10,10 10,10 5,5 5)))" ) prep = mpoly.prepared # A set of test points. pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)] for pnt in pnts: # Results should be the same (but faster) self.assertEqual(mpoly.contains(pnt), prep.contains(pnt)) self.assertEqual(mpoly.intersects(pnt), prep.intersects(pnt)) self.assertEqual(mpoly.covers(pnt), prep.covers(pnt)) self.assertTrue(prep.crosses(fromstr("LINESTRING(1 1, 15 15)"))) self.assertTrue(prep.disjoint(Point(-5, -5))) poly = Polygon(((-1, -1), (1, 1), (1, 0), (-1, -1))) self.assertTrue(prep.overlaps(poly)) poly = Polygon(((-5, 0), (-5, 5), (0, 5), (-5, 0))) self.assertTrue(prep.touches(poly)) poly = Polygon(((-1, -1), (-1, 11), (11, 11), (11, -1), (-1, -1))) self.assertTrue(prep.within(poly)) # Original geometry deletion should not crash the prepared one (#21662) del mpoly self.assertTrue(prep.covers(Point(5, 5))) def test_line_merge(self): "Testing line merge support" ref_geoms = ( fromstr("LINESTRING(1 1, 1 1, 3 3)"), fromstr("MULTILINESTRING((1 1, 3 3), (3 3, 4 2))"), ) ref_merged = ( fromstr("LINESTRING(1 1, 3 3)"), fromstr("LINESTRING (1 1, 3 3, 4 2)"), ) for geom, merged in zip(ref_geoms, ref_merged): self.assertEqual(merged, geom.merged) def test_valid_reason(self): "Testing IsValidReason support" g = GEOSGeometry("POINT(0 0)") self.assertTrue(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertEqual(g.valid_reason, "Valid Geometry") g = GEOSGeometry("LINESTRING(0 0, 0 0)") self.assertFalse(g.valid) self.assertIsInstance(g.valid_reason, str) self.assertTrue( g.valid_reason.startswith("Too few points in geometry component") ) def test_linearref(self): "Testing linear referencing" ls = fromstr("LINESTRING(0 0, 0 10, 10 10, 10 0)") mls = fromstr("MULTILINESTRING((0 0, 0 10), (10 0, 10 10))") self.assertEqual(ls.project(Point(0, 20)), 10.0) self.assertEqual(ls.project(Point(7, 6)), 24) self.assertEqual(ls.project_normalized(Point(0, 20)), 1.0 / 3) self.assertEqual(ls.interpolate(10), Point(0, 10)) self.assertEqual(ls.interpolate(24), Point(10, 6)) self.assertEqual(ls.interpolate_normalized(1.0 / 3), Point(0, 10)) self.assertEqual(mls.project(Point(0, 20)), 10) self.assertEqual(mls.project(Point(7, 6)), 16) self.assertEqual(mls.interpolate(9), Point(0, 9)) self.assertEqual(mls.interpolate(17), Point(10, 7)) def test_deconstructible(self): """ Geometry classes should be deconstructible. """ point = Point(4.337844, 50.827537, srid=4326) path, args, kwargs = point.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.point.Point") self.assertEqual(args, (4.337844, 50.827537)) self.assertEqual(kwargs, {"srid": 4326}) ls = LineString(((0, 0), (1, 1))) path, args, kwargs = ls.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString") self.assertEqual(args, (((0, 0), (1, 1)),)) self.assertEqual(kwargs, {}) ls2 = LineString([Point(0, 0), Point(1, 1)], srid=4326) path, args, kwargs = ls2.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LineString") self.assertEqual(args, ([Point(0, 0), Point(1, 1)],)) self.assertEqual(kwargs, {"srid": 4326}) ext_coords = ((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)) int_coords = ((0.4, 0.4), (0.4, 0.6), (0.6, 0.6), (0.6, 0.4), (0.4, 0.4)) poly = Polygon(ext_coords, int_coords) path, args, kwargs = poly.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.polygon.Polygon") self.assertEqual(args, (ext_coords, int_coords)) self.assertEqual(kwargs, {}) lr = LinearRing((0, 0), (0, 1), (1, 1), (0, 0)) path, args, kwargs = lr.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.linestring.LinearRing") self.assertEqual(args, ((0, 0), (0, 1), (1, 1), (0, 0))) self.assertEqual(kwargs, {}) mp = MultiPoint(Point(0, 0), Point(1, 1)) path, args, kwargs = mp.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPoint") self.assertEqual(args, (Point(0, 0), Point(1, 1))) self.assertEqual(kwargs, {}) ls1 = LineString((0, 0), (1, 1)) ls2 = LineString((2, 2), (3, 3)) mls = MultiLineString(ls1, ls2) path, args, kwargs = mls.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiLineString") self.assertEqual(args, (ls1, ls2)) self.assertEqual(kwargs, {}) p1 = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) p2 = Polygon(((1, 1), (1, 2), (2, 2), (1, 1))) mp = MultiPolygon(p1, p2) path, args, kwargs = mp.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.MultiPolygon") self.assertEqual(args, (p1, p2)) self.assertEqual(kwargs, {}) poly = Polygon(((0, 0), (0, 1), (1, 1), (0, 0))) gc = GeometryCollection(Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly) path, args, kwargs = gc.deconstruct() self.assertEqual(path, "django.contrib.gis.geos.collections.GeometryCollection") self.assertEqual( args, (Point(0, 0), MultiPoint(Point(0, 0), Point(1, 1)), poly) ) self.assertEqual(kwargs, {}) def test_subclassing(self): """ GEOSGeometry subclass may itself be subclassed without being forced-cast to the parent class during `__init__`. """ class ExtendedPolygon(Polygon): def __init__(self, *args, data=0, **kwargs): super().__init__(*args, **kwargs) self._data = data def __str__(self): return "EXT_POLYGON - data: %d - %s" % (self._data, self.wkt) ext_poly = ExtendedPolygon(((0, 0), (0, 1), (1, 1), (0, 0)), data=3) self.assertEqual(type(ext_poly), ExtendedPolygon) # ExtendedPolygon.__str__ should be called (instead of Polygon.__str__). self.assertEqual( str(ext_poly), "EXT_POLYGON - data: 3 - POLYGON ((0 0, 0 1, 1 1, 0 0))" ) self.assertJSONEqual( ext_poly.json, '{"coordinates": [[[0, 0], [0, 1], [1, 1], [0, 0]]], "type": "Polygon"}', ) def test_geos_version_tuple(self): versions = ( (b"3.0.0rc4-CAPI-1.3.3", (3, 0, 0)), (b"3.0.0-CAPI-1.4.1", (3, 0, 0)), (b"3.4.0dev-CAPI-1.8.0", (3, 4, 0)), (b"3.4.0dev-CAPI-1.8.0 r0", (3, 4, 0)), (b"3.6.2-CAPI-1.10.2 4d2925d6", (3, 6, 2)), ) for version_string, version_tuple in versions: with self.subTest(version_string=version_string): with mock.patch( "django.contrib.gis.geos.libgeos.geos_version", lambda: version_string, ): self.assertEqual(geos_version_tuple(), version_tuple) def test_from_gml(self): self.assertEqual( GEOSGeometry("POINT(0 0)"), GEOSGeometry.from_gml( '<gml:Point gml:id="p21" ' 'srsName="http://www.opengis.net/def/crs/EPSG/0/4326">' ' <gml:pos srsDimension="2">0 0</gml:pos>' "</gml:Point>" ), ) def test_from_ewkt(self): self.assertEqual( GEOSGeometry.from_ewkt("SRID=1;POINT(1 1)"), Point(1, 1, srid=1) ) self.assertEqual(GEOSGeometry.from_ewkt("POINT(1 1)"), Point(1, 1)) def test_from_ewkt_empty_string(self): msg = "Expected WKT but got an empty string." with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("") with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRID=1;") def test_from_ewkt_invalid_srid(self): msg = "EWKT has invalid SRID part." with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRUD=1;POINT(1 1)") with self.assertRaisesMessage(ValueError, msg): GEOSGeometry.from_ewkt("SRID=WGS84;POINT(1 1)") def test_fromstr_scientific_wkt(self): self.assertEqual(GEOSGeometry("POINT(1.0e-1 1.0e+1)"), Point(0.1, 10)) def test_normalize(self): multipoint = MultiPoint(Point(0, 0), Point(2, 2), Point(1, 1)) normalized = MultiPoint(Point(2, 2), Point(1, 1), Point(0, 0)) # Geometry is normalized in-place and nothing is returned. multipoint_1 = multipoint.clone() self.assertIsNone(multipoint_1.normalize()) self.assertEqual(multipoint_1, normalized) # If the `clone` keyword is set, then the geometry is not modified and # a normalized clone of the geometry is returned instead. multipoint_2 = multipoint.normalize(clone=True) self.assertEqual(multipoint_2, normalized) self.assertNotEqual(multipoint, normalized) @skipIf(geos_version_tuple() < (3, 8), "GEOS >= 3.8.0 is required") def test_make_valid(self): poly = GEOSGeometry("POLYGON((0 0, 0 23, 23 0, 23 23, 0 0))") self.assertIs(poly.valid, False) valid_poly = poly.make_valid() self.assertIs(valid_poly.valid, True) self.assertNotEqual(valid_poly, poly) valid_poly2 = valid_poly.make_valid() self.assertIs(valid_poly2.valid, True) self.assertEqual(valid_poly, valid_poly2) @mock.patch("django.contrib.gis.geos.libgeos.geos_version", lambda: b"3.7.3") def test_make_valid_geos_version(self): msg = "GEOSGeometry.make_valid() requires GEOS >= 3.8.0." poly = GEOSGeometry("POLYGON((0 0, 0 23, 23 0, 23 23, 0 0))") with self.assertRaisesMessage(GEOSException, msg): poly.make_valid() def test_empty_point(self): p = Point(srid=4326) self.assertEqual(p.ogr.ewkt, p.ewkt) self.assertEqual(p.transform(2774, clone=True), Point(srid=2774)) p.transform(2774) self.assertEqual(p, Point(srid=2774)) def test_linestring_iter(self): ls = LineString((0, 0), (1, 1)) it = iter(ls) # Step into CoordSeq iterator. next(it) ls[:] = [] with self.assertRaises(IndexError): next(it)
f796c7d5f5ec1bea4a141a16d1c66525acb70f1a6c608776b88b362df3010733
from django.utils.version import get_version VERSION = (4, 2, 0, "alpha", 0) __version__ = get_version(VERSION) def setup(set_prefix=True): """ Configure the settings (this happens as a side effect of accessing the first setting), configure logging and populate the app registry. Set the thread-local urlresolvers script prefix if `set_prefix` is True. """ from django.apps import apps from django.conf import settings from django.urls import set_script_prefix from django.utils.log import configure_logging configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) if set_prefix: set_script_prefix( "/" if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME ) apps.populate(settings.INSTALLED_APPS)
746ca667b952f601bc3a3ec2e53c79c43f16102458d24ea6d9da9a86eec86dbf
#!/usr/bin/env python import argparse import atexit import copy import gc import multiprocessing import os import shutil import socket import subprocess import sys import tempfile import warnings from pathlib import Path try: import django except ImportError as e: raise RuntimeError( "Django module not found, reference tests/README.rst for instructions." ) from e else: from django.apps import apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import connection, connections from django.test import TestCase, TransactionTestCase from django.test.runner import get_max_test_processes, parallel_type from django.test.selenium import SeleniumTestCaseBase from django.test.utils import NullTimeKeeper, TimeKeeper, get_runner from django.utils.deprecation import ( RemovedInDjango50Warning, RemovedInDjango51Warning, ) from django.utils.log import DEFAULT_LOGGING try: import MySQLdb except ImportError: pass else: # Ignore informational warnings from QuerySet.explain(). warnings.filterwarnings("ignore", r"\(1003, *", category=MySQLdb.Warning) # Make deprecation warnings errors to ensure no usage of deprecated features. warnings.simplefilter("error", RemovedInDjango50Warning) warnings.simplefilter("error", RemovedInDjango51Warning) # Make resource and runtime warning errors to ensure no usage of error prone # patterns. warnings.simplefilter("error", ResourceWarning) warnings.simplefilter("error", RuntimeWarning) # Ignore known warnings in test dependencies. warnings.filterwarnings( "ignore", "'U' mode is deprecated", DeprecationWarning, module="docutils.io" ) # Reduce garbage collection frequency to improve performance. Since CPython # uses refcounting, garbage collection only collects objects with cyclic # references, which are a minority, so the garbage collection threshold can be # larger than the default threshold of 700 allocations + deallocations without # much increase in memory usage. gc.set_threshold(100_000) RUNTESTS_DIR = os.path.abspath(os.path.dirname(__file__)) TEMPLATE_DIR = os.path.join(RUNTESTS_DIR, "templates") # Create a specific subdirectory for the duration of the test suite. TMPDIR = tempfile.mkdtemp(prefix="django_") # Set the TMPDIR environment variable in addition to tempfile.tempdir # so that children processes inherit it. tempfile.tempdir = os.environ["TMPDIR"] = TMPDIR # Removing the temporary TMPDIR. atexit.register(shutil.rmtree, TMPDIR) # This is a dict mapping RUNTESTS_DIR subdirectory to subdirectories of that # directory to skip when searching for test modules. SUBDIRS_TO_SKIP = { "": {"import_error_package", "test_runner_apps"}, "gis_tests": {"data"}, } ALWAYS_INSTALLED_APPS = [ "django.contrib.contenttypes", "django.contrib.auth", "django.contrib.sites", "django.contrib.sessions", "django.contrib.messages", "django.contrib.admin.apps.SimpleAdminConfig", "django.contrib.staticfiles", ] ALWAYS_MIDDLEWARE = [ "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", ] # Need to add the associated contrib app to INSTALLED_APPS in some cases to # avoid "RuntimeError: Model class X doesn't declare an explicit app_label # and isn't in an application in INSTALLED_APPS." CONTRIB_TESTS_TO_APPS = { "deprecation": ["django.contrib.flatpages", "django.contrib.redirects"], "flatpages_tests": ["django.contrib.flatpages"], "redirects_tests": ["django.contrib.redirects"], } def get_test_modules(gis_enabled): """ Scan the tests directory and yield the names of all test modules. The yielded names have either one dotted part like "test_runner" or, in the case of GIS tests, two dotted parts like "gis_tests.gdal_tests". """ discovery_dirs = [""] if gis_enabled: # GIS tests are in nested apps discovery_dirs.append("gis_tests") else: SUBDIRS_TO_SKIP[""].add("gis_tests") for dirname in discovery_dirs: dirpath = os.path.join(RUNTESTS_DIR, dirname) subdirs_to_skip = SUBDIRS_TO_SKIP[dirname] with os.scandir(dirpath) as entries: for f in entries: if ( "." in f.name or os.path.basename(f.name) in subdirs_to_skip or f.is_file() or not os.path.exists(os.path.join(f.path, "__init__.py")) ): continue test_module = f.name if dirname: test_module = dirname + "." + test_module yield test_module def get_label_module(label): """Return the top-level module part for a test label.""" path = Path(label) if len(path.parts) == 1: # Interpret the label as a dotted module name. return label.split(".")[0] # Otherwise, interpret the label as a path. Check existence first to # provide a better error message than relative_to() if it doesn't exist. if not path.exists(): raise RuntimeError(f"Test label path {label} does not exist") path = path.resolve() rel_path = path.relative_to(RUNTESTS_DIR) return rel_path.parts[0] def get_filtered_test_modules(start_at, start_after, gis_enabled, test_labels=None): if test_labels is None: test_labels = [] # Reduce each test label to just the top-level module part. label_modules = set() for label in test_labels: test_module = get_label_module(label) label_modules.add(test_module) # It would be nice to put this validation earlier but it must come after # django.setup() so that connection.features.gis_enabled can be accessed. if "gis_tests" in label_modules and not gis_enabled: print("Aborting: A GIS database backend is required to run gis_tests.") sys.exit(1) def _module_match_label(module_name, label): # Exact or ancestor match. return module_name == label or module_name.startswith(label + ".") start_label = start_at or start_after for test_module in get_test_modules(gis_enabled): if start_label: if not _module_match_label(test_module, start_label): continue start_label = "" if not start_at: assert start_after # Skip the current one before starting. continue # If the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), include the test module. if not test_labels or any( _module_match_label(test_module, label_module) for label_module in label_modules ): yield test_module def setup_collect_tests(start_at, start_after, test_labels=None): state = { "INSTALLED_APPS": settings.INSTALLED_APPS, "ROOT_URLCONF": getattr(settings, "ROOT_URLCONF", ""), "TEMPLATES": settings.TEMPLATES, "LANGUAGE_CODE": settings.LANGUAGE_CODE, "STATIC_URL": settings.STATIC_URL, "STATIC_ROOT": settings.STATIC_ROOT, "MIDDLEWARE": settings.MIDDLEWARE, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = "urls" settings.STATIC_URL = "static/" settings.STATIC_ROOT = os.path.join(TMPDIR, "static") settings.TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [TEMPLATE_DIR], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ] settings.LANGUAGE_CODE = "en" settings.SITE_ID = 1 settings.MIDDLEWARE = ALWAYS_MIDDLEWARE settings.MIGRATION_MODULES = { # This lets us skip creating migrations for the test models as many of # them depend on one of the following contrib applications. "auth": None, "contenttypes": None, "sessions": None, } log_config = copy.deepcopy(DEFAULT_LOGGING) # Filter out non-error logging so we don't have to capture it in lots of # tests. log_config["loggers"]["django"]["level"] = "ERROR" settings.LOGGING = log_config settings.SILENCED_SYSTEM_CHECKS = [ "fields.W342", # ForeignKey(unique=True) -> OneToOneField ] # RemovedInDjango50Warning settings.FORM_RENDERER = "django.forms.renderers.DjangoDivFormRenderer" # Load all the ALWAYS_INSTALLED_APPS. django.setup() # This flag must be evaluated after django.setup() because otherwise it can # raise AppRegistryNotReady when running gis_tests in isolation on some # backends (e.g. PostGIS). gis_enabled = connection.features.gis_enabled test_modules = list( get_filtered_test_modules( start_at, start_after, gis_enabled, test_labels=test_labels, ) ) return test_modules, state def teardown_collect_tests(state): # Restore the old settings. for key, value in state.items(): setattr(settings, key, value) def get_installed(): return [app_config.name for app_config in apps.get_app_configs()] # This function should be called only after calling django.setup(), # since it calls connection.features.gis_enabled. def get_apps_to_install(test_modules): for test_module in test_modules: if test_module in CONTRIB_TESTS_TO_APPS: yield from CONTRIB_TESTS_TO_APPS[test_module] yield test_module # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring # @override_settings(INSTALLED_APPS=...) on all test cases. if connection.features.gis_enabled: yield "django.contrib.gis" def setup_run_tests(verbosity, start_at, start_after, test_labels=None): test_modules, state = setup_collect_tests( start_at, start_after, test_labels=test_labels ) installed_apps = set(get_installed()) for app in get_apps_to_install(test_modules): if app in installed_apps: continue if verbosity >= 2: print(f"Importing application {app}") settings.INSTALLED_APPS.append(app) installed_apps.add(app) apps.set_installed_apps(settings.INSTALLED_APPS) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception( "Please define available_apps in TransactionTestCase and its subclasses." ) TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None # Set an environment variable that other code may consult to see if # Django's own test suite is running. os.environ["RUNNING_DJANGOS_TEST_SUITE"] = "true" test_labels = test_labels or test_modules return test_labels, state def teardown_run_tests(state): teardown_collect_tests(state) # Discard the multiprocessing.util finalizer that tries to remove a # temporary directory that's already removed by this script's # atexit.register(shutil.rmtree, TMPDIR) handler. Prevents # FileNotFoundError at the end of a test run (#27890). from multiprocessing.util import _finalizer_registry _finalizer_registry.pop((-100, 0), None) del os.environ["RUNNING_DJANGOS_TEST_SUITE"] class ActionSelenium(argparse.Action): """ Validate the comma-separated list of requested browsers. """ def __call__(self, parser, namespace, values, option_string=None): try: import selenium # NOQA except ImportError as e: raise ImproperlyConfigured(f"Error loading selenium module: {e}") browsers = values.split(",") for browser in browsers: try: SeleniumTestCaseBase.import_webdriver(browser) except ImportError: raise argparse.ArgumentError( self, "Selenium browser specification '%s' is not valid." % browser ) setattr(namespace, self.dest, browsers) def django_tests( verbosity, interactive, failfast, keepdb, reverse, test_labels, debug_sql, parallel, tags, exclude_tags, test_name_patterns, start_at, start_after, pdb, buffer, timing, shuffle, ): if parallel in {0, "auto"}: max_parallel = get_max_test_processes() else: max_parallel = parallel if verbosity >= 1: msg = "Testing against Django installed in '%s'" % os.path.dirname( django.__file__ ) if max_parallel > 1: msg += " with up to %d processes" % max_parallel print(msg) process_setup_args = (verbosity, start_at, start_after, test_labels) test_labels, state = setup_run_tests(*process_setup_args) # Run the test suite, including the extra validation tests. if not hasattr(settings, "TEST_RUNNER"): settings.TEST_RUNNER = "django.test.runner.DiscoverRunner" if parallel in {0, "auto"}: # This doesn't work before django.setup() on some databases. if all(conn.features.can_clone_databases for conn in connections.all()): parallel = max_parallel else: parallel = 1 TestRunner = get_runner(settings) TestRunner.parallel_test_suite.process_setup = setup_run_tests TestRunner.parallel_test_suite.process_setup_args = process_setup_args test_runner = TestRunner( verbosity=verbosity, interactive=interactive, failfast=failfast, keepdb=keepdb, reverse=reverse, debug_sql=debug_sql, parallel=parallel, tags=tags, exclude_tags=exclude_tags, test_name_patterns=test_name_patterns, pdb=pdb, buffer=buffer, timing=timing, shuffle=shuffle, ) failures = test_runner.run_tests(test_labels) teardown_run_tests(state) return failures def collect_test_modules(start_at, start_after): test_modules, state = setup_collect_tests(start_at, start_after) teardown_collect_tests(state) return test_modules def get_subprocess_args(options): subprocess_args = [sys.executable, __file__, "--settings=%s" % options.settings] if options.failfast: subprocess_args.append("--failfast") if options.verbosity: subprocess_args.append("--verbosity=%s" % options.verbosity) if not options.interactive: subprocess_args.append("--noinput") if options.tags: subprocess_args.append("--tag=%s" % options.tags) if options.exclude_tags: subprocess_args.append("--exclude_tag=%s" % options.exclude_tags) if options.shuffle is not False: if options.shuffle is None: subprocess_args.append("--shuffle") else: subprocess_args.append("--shuffle=%s" % options.shuffle) return subprocess_args def bisect_tests(bisection_label, options, test_labels, start_at, start_after): if not test_labels: test_labels = collect_test_modules(start_at, start_after) print("***** Bisecting test suite: %s" % " ".join(test_labels)) # Make sure the bisection point isn't in the test list # Also remove tests that need to be run in specific combinations for label in [bisection_label, "model_inheritance_same_model_name"]: try: test_labels.remove(label) except ValueError: pass subprocess_args = get_subprocess_args(options) iteration = 1 while len(test_labels) > 1: midpoint = len(test_labels) // 2 test_labels_a = test_labels[:midpoint] + [bisection_label] test_labels_b = test_labels[midpoint:] + [bisection_label] print("***** Pass %da: Running the first half of the test suite" % iteration) print("***** Test labels: %s" % " ".join(test_labels_a)) failures_a = subprocess.run(subprocess_args + test_labels_a) print("***** Pass %db: Running the second half of the test suite" % iteration) print("***** Test labels: %s" % " ".join(test_labels_b)) print("") failures_b = subprocess.run(subprocess_args + test_labels_b) if failures_a.returncode and not failures_b.returncode: print("***** Problem found in first half. Bisecting again...") iteration += 1 test_labels = test_labels_a[:-1] elif failures_b.returncode and not failures_a.returncode: print("***** Problem found in second half. Bisecting again...") iteration += 1 test_labels = test_labels_b[:-1] elif failures_a.returncode and failures_b.returncode: print("***** Multiple sources of failure found") break else: print("***** No source of failure found... try pair execution (--pair)") break if len(test_labels) == 1: print("***** Source of error: %s" % test_labels[0]) def paired_tests(paired_test, options, test_labels, start_at, start_after): if not test_labels: test_labels = collect_test_modules(start_at, start_after) print("***** Trying paired execution") # Make sure the constant member of the pair isn't in the test list # Also remove tests that need to be run in specific combinations for label in [paired_test, "model_inheritance_same_model_name"]: try: test_labels.remove(label) except ValueError: pass subprocess_args = get_subprocess_args(options) for i, label in enumerate(test_labels): print( "***** %d of %d: Check test pairing with %s" % (i + 1, len(test_labels), label) ) failures = subprocess.call(subprocess_args + [label, paired_test]) if failures: print("***** Found problem pair with %s" % label) return print("***** No problem pair found") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Run the Django test suite.") parser.add_argument( "modules", nargs="*", metavar="module", help='Optional path(s) to test modules; e.g. "i18n" or ' '"i18n.tests.TranslationTests.test_lazy_objects".', ) parser.add_argument( "-v", "--verbosity", default=1, type=int, choices=[0, 1, 2, 3], help="Verbosity level; 0=minimal output, 1=normal output, 2=all output", ) parser.add_argument( "--noinput", action="store_false", dest="interactive", help="Tells Django to NOT prompt the user for input of any kind.", ) parser.add_argument( "--failfast", action="store_true", help="Tells Django to stop running the test suite after first failed test.", ) parser.add_argument( "--keepdb", action="store_true", help="Tells Django to preserve the test database between runs.", ) parser.add_argument( "--settings", help='Python path to settings module, e.g. "myproject.settings". If ' "this isn't provided, either the DJANGO_SETTINGS_MODULE " 'environment variable or "test_sqlite" will be used.', ) parser.add_argument( "--bisect", help="Bisect the test suite to discover a test that causes a test " "failure when combined with the named test.", ) parser.add_argument( "--pair", help="Run the test suite in pairs with the named test to find problem pairs.", ) parser.add_argument( "--shuffle", nargs="?", default=False, type=int, metavar="SEED", help=( "Shuffle the order of test cases to help check that tests are " "properly isolated." ), ) parser.add_argument( "--reverse", action="store_true", help="Sort test suites and test cases in opposite order to debug " "test side effects not apparent with normal execution lineup.", ) parser.add_argument( "--selenium", action=ActionSelenium, metavar="BROWSERS", help="A comma-separated list of browsers to run the Selenium tests against.", ) parser.add_argument( "--headless", action="store_true", help="Run selenium tests in headless mode, if the browser supports the option.", ) parser.add_argument( "--selenium-hub", help="A URL for a selenium hub instance to use in combination with --selenium.", ) parser.add_argument( "--external-host", default=socket.gethostname(), help=( "The external host that can be reached by the selenium hub instance when " "running Selenium tests via Selenium Hub." ), ) parser.add_argument( "--debug-sql", action="store_true", help="Turn on the SQL query logger within tests.", ) # 0 is converted to "auto" or 1 later on, depending on a method used by # multiprocessing to start subprocesses and on the backend support for # cloning databases. parser.add_argument( "--parallel", nargs="?", const="auto", default=0, type=parallel_type, metavar="N", help=( 'Run tests using up to N parallel processes. Use the value "auto" ' "to run one test process for each processor core." ), ) parser.add_argument( "--tag", dest="tags", action="append", help="Run only tests with the specified tags. Can be used multiple times.", ) parser.add_argument( "--exclude-tag", dest="exclude_tags", action="append", help="Do not run tests with the specified tag. Can be used multiple times.", ) parser.add_argument( "--start-after", dest="start_after", help="Run tests starting after the specified top-level module.", ) parser.add_argument( "--start-at", dest="start_at", help="Run tests starting at the specified top-level module.", ) parser.add_argument( "--pdb", action="store_true", help="Runs the PDB debugger on error or failure." ) parser.add_argument( "-b", "--buffer", action="store_true", help="Discard output of passing tests.", ) parser.add_argument( "--timing", action="store_true", help="Output timings, including database set up and total run time.", ) parser.add_argument( "-k", dest="test_name_patterns", action="append", help=( "Only run test methods and classes matching test name pattern. " "Same as unittest -k option. Can be used multiple times." ), ) options = parser.parse_args() using_selenium_hub = options.selenium and options.selenium_hub if options.selenium_hub and not options.selenium: parser.error( "--selenium-hub and --external-host require --selenium to be used." ) if using_selenium_hub and not options.external_host: parser.error("--selenium-hub and --external-host must be used together.") # Allow including a trailing slash on app_labels for tab completion convenience options.modules = [os.path.normpath(labels) for labels in options.modules] mutually_exclusive_options = [ options.start_at, options.start_after, options.modules, ] enabled_module_options = [ bool(option) for option in mutually_exclusive_options ].count(True) if enabled_module_options > 1: print( "Aborting: --start-at, --start-after, and test labels are mutually " "exclusive." ) sys.exit(1) for opt_name in ["start_at", "start_after"]: opt_val = getattr(options, opt_name) if opt_val: if "." in opt_val: print( "Aborting: --%s must be a top-level module." % opt_name.replace("_", "-") ) sys.exit(1) setattr(options, opt_name, os.path.normpath(opt_val)) if options.settings: os.environ["DJANGO_SETTINGS_MODULE"] = options.settings else: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_sqlite") options.settings = os.environ["DJANGO_SETTINGS_MODULE"] if options.selenium: if multiprocessing.get_start_method() == "spawn" and options.parallel != 1: parser.error( "You cannot use --selenium with parallel tests on this system. " "Pass --parallel=1 to use --selenium." ) if not options.tags: options.tags = ["selenium"] elif "selenium" not in options.tags: options.tags.append("selenium") if options.selenium_hub: SeleniumTestCaseBase.selenium_hub = options.selenium_hub SeleniumTestCaseBase.external_host = options.external_host SeleniumTestCaseBase.headless = options.headless SeleniumTestCaseBase.browsers = options.selenium if options.bisect: bisect_tests( options.bisect, options, options.modules, options.start_at, options.start_after, ) elif options.pair: paired_tests( options.pair, options, options.modules, options.start_at, options.start_after, ) else: time_keeper = TimeKeeper() if options.timing else NullTimeKeeper() with time_keeper.timed("Total run"): failures = django_tests( options.verbosity, options.interactive, options.failfast, options.keepdb, options.reverse, options.modules, options.debug_sql, options.parallel, options.tags, options.exclude_tags, getattr(options, "test_name_patterns", None), options.start_at, options.start_after, options.pdb, options.buffer, options.timing, options.shuffle, ) time_keeper.print_results() if failures: sys.exit(1)
1df9919927dfe1c5dac459292c9cdc3b5347d4398dd81ef534e456f17b4076ec
# Django documentation build configuration file, created by # sphinx-quickstart on Thu Mar 27 09:06:53 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't picklable (module imports are okay, they're removed automatically). # # All configuration values have a default; values that are commented out # serve to show the default. import sys from os.path import abspath, dirname, join # Workaround for sphinx-build recursion limit overflow: # pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL) # RuntimeError: maximum recursion depth exceeded while pickling an object # # Python's default allowed recursion depth is 1000 but this isn't enough for # building docs/ref/settings.txt sometimes. # https://groups.google.com/g/sphinx-dev/c/MtRf64eGtv4/discussion sys.setrecursionlimit(2000) # Make sure we get the version of this copy of Django sys.path.insert(1, dirname(dirname(abspath(__file__)))) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(abspath(join(dirname(__file__), "_ext"))) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = "4.5.0" # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "djangodocs", "sphinx.ext.extlinks", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", "sphinx.ext.autosectionlabel", ] # AutosectionLabel settings. # Uses a <page>:<label> schema which doesn't work for duplicate sub-section # labels, so set max depth. autosectionlabel_prefix_document = True autosectionlabel_maxdepth = 2 # Linkcheck settings. linkcheck_ignore = [ # Special-use addresses and domain names. (RFC 6761/6890) r"^https?://(?:127\.0\.0\.1|\[::1\])(?::\d+)?/", r"^https?://(?:[^/\.]+\.)*example\.(?:com|net|org)(?::\d+)?/", r"^https?://(?:[^/\.]+\.)*(?:example|invalid|localhost|test)(?::\d+)?/", # Pages that are inaccessible because they require authentication. r"^https://github\.com/[^/]+/[^/]+/fork", r"^https://code\.djangoproject\.com/github/login", r"^https://code\.djangoproject\.com/newticket", r"^https://(?:code|www)\.djangoproject\.com/admin/", r"^https://www\.djangoproject\.com/community/add/blogs/", r"^https://www\.google\.com/webmasters/tools/ping", r"^https://search\.google\.com/search-console/welcome", # Fragments used to dynamically switch content or populate fields. r"^https://web\.libera\.chat/#", r"^https://github\.com/[^#]+#L\d+-L\d+$", r"^https://help\.apple\.com/itc/podcasts_connect/#/itc", # Anchors on certain pages with missing a[name] attributes. r"^https://tools\.ietf\.org/html/rfc1123\.html#section-", ] # Spelling check needs an additional module that is not installed by default. # Add it only if spelling check is requested so docs can be generated without it. if "spelling" in sys.argv: extensions.append("sphinxcontrib.spelling") # Spelling language. spelling_lang = "en_US" # Location of word list. spelling_word_list_filename = "spelling_wordlist" spelling_warning = True # Add any paths that contain templates here, relative to this directory. # templates_path = [] # The suffix of source filenames. source_suffix = ".txt" # The encoding of source files. # source_encoding = 'utf-8-sig' # The root toctree document. root_doc = "contents" # General substitutions. project = "Django" copyright = "Django Software Foundation and contributors" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "4.2" # The full version, including alpha/beta/rc tags. try: from django import VERSION, get_version except ImportError: release = version else: def django_release(): pep440ver = get_version() if VERSION[3:5] == ("alpha", 0) and "dev" not in pep440ver: return pep440ver + ".dev" return pep440ver release = django_release() # The "development version" of Django django_next_version = "4.2" extlinks = { "bpo": ("https://bugs.python.org/issue?@action=redirect&bpo=%s", "bpo-%s"), "commit": ("https://github.com/django/django/commit/%s", "%s"), "cve": ("https://nvd.nist.gov/vuln/detail/CVE-%s", "CVE-%s"), # A file or directory. GitHub redirects from blob to tree if needed. "source": ("https://github.com/django/django/blob/main/%s", "%s"), "ticket": ("https://code.djangoproject.com/ticket/%s", "#%s"), } # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # Location for .po/.mo translation files used when language is set locale_dirs = ["locale/"] # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = "%B %d, %Y" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build", "_theme", "requirements.txt"] # The reST default role (used for this markup: `text`) to use for all documents. default_role = "default-role-error" # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "trac" # Links to Python's docs should reference the most recent version of the 3.x # branch, which is located at this URL. intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), "sphinx": ("https://www.sphinx-doc.org/en/master/", None), "psycopg2": ("https://www.psycopg.org/docs/", None), } # Python's docs don't change every week. intersphinx_cache_limit = 90 # days # The 'versionadded' and 'versionchanged' directives are overridden. suppress_warnings = ["app.add_directive"] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "djangodocs" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["_theme"] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = "%b %d, %Y" # Content template for the index page. # html_index = '' # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "Djangodoc" modindex_common_prefix = ["django."] # Appended to every page rst_epilog = """ .. |django-users| replace:: :ref:`django-users <django-users-mailing-list>` .. |django-developers| replace:: :ref:`django-developers <django-developers-mailing-list>` .. |django-announce| replace:: :ref:`django-announce <django-announce-mailing-list>` .. |django-updates| replace:: :ref:`django-updates <django-updates-mailing-list>` """ # NOQA # -- Options for LaTeX output -------------------------------------------------- # Use XeLaTeX for Unicode support. latex_engine = "xelatex" latex_use_xindy = False # Set font for CJK and fallbacks for unicode characters. latex_elements = { "fontpkg": r""" \setmainfont{Symbola} """, "preamble": r""" \usepackage{newunicodechar} \usepackage[UTF8]{ctex} \newunicodechar{π}{\ensuremath{\pi}} \newunicodechar{≤}{\ensuremath{\le}} \newunicodechar{≥}{\ensuremath{\ge}} \newunicodechar{♥}{\ensuremath{\heartsuit}} \newunicodechar{…}{\ensuremath{\ldots}} """, } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). # latex_documents = [] latex_documents = [ ( "contents", "django.tex", "Django Documentation", "Django Software Foundation", "manual", ), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( "ref/django-admin", "django-admin", "Utility script for the Django web framework", ["Django Software Foundation"], 1, ) ] # -- Options for Texinfo output ------------------------------------------------ # List of tuples (startdocname, targetname, title, author, dir_entry, # description, category, toctree_only) texinfo_documents = [ ( root_doc, "django", "", "", "Django", "Documentation of the Django framework", "Web development", False, ) ] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = "Django Software Foundation" epub_publisher = "Django Software Foundation" epub_copyright = copyright # The basename for the epub file. It defaults to the project name. # epub_basename = 'Django' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. epub_theme = "djangodocs-epub" # The language of the text. It defaults to the language option # or en if the language is not set. # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be an ISBN number # or the project homepage. # epub_identifier = '' # A unique identification for the text. # epub_uid = '' # A tuple containing the cover image and cover page html template filenames. epub_cover = ("", "epub-cover.html") # A sequence of (type, uri, title) tuples for the guide element of content.opf. # epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_post_files = [] # A list of files that should not be packed into the epub file. # epub_exclude_files = [] # The depth of the table of contents in toc.ncx. # epub_tocdepth = 3 # Allow duplicate toc entries. # epub_tocdup = True # Choose between 'default' and 'includehidden'. # epub_tocscope = 'default' # Fix unsupported image types using the PIL. # epub_fix_images = False # Scale large images. # epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. # epub_show_urls = 'inline' # If false, no index is generated. # epub_use_index = True
72d8f26fca22a74e2f77cb6208b741ddb2152b7a93ff433aa0930b9371e02207
import argparse import ctypes import faulthandler import io import itertools import logging import multiprocessing import os import pickle import random import sys import textwrap import unittest import warnings from collections import defaultdict from contextlib import contextmanager from importlib import import_module from io import StringIO from django.core.management import call_command from django.db import connections from django.test import SimpleTestCase, TestCase from django.test.utils import ( NullTimeKeeper, TimeKeeper, captured_stdout, iter_test_cases, ) from django.test.utils import setup_databases as _setup_databases from django.test.utils import setup_test_environment from django.test.utils import teardown_databases as _teardown_databases from django.test.utils import teardown_test_environment from django.utils.crypto import new_hash from django.utils.datastructures import OrderedSet from django.utils.deprecation import RemovedInDjango50Warning try: import ipdb as pdb except ImportError: import pdb try: import tblib.pickling_support except ImportError: tblib = None class DebugSQLTextTestResult(unittest.TextTestResult): def __init__(self, stream, descriptions, verbosity): self.logger = logging.getLogger("django.db.backends") self.logger.setLevel(logging.DEBUG) self.debug_sql_stream = None super().__init__(stream, descriptions, verbosity) def startTest(self, test): self.debug_sql_stream = StringIO() self.handler = logging.StreamHandler(self.debug_sql_stream) self.logger.addHandler(self.handler) super().startTest(test) def stopTest(self, test): super().stopTest(test) self.logger.removeHandler(self.handler) if self.showAll: self.debug_sql_stream.seek(0) self.stream.write(self.debug_sql_stream.read()) self.stream.writeln(self.separator2) def addError(self, test, err): super().addError(test, err) if self.debug_sql_stream is None: # Error before tests e.g. in setUpTestData(). sql = "" else: self.debug_sql_stream.seek(0) sql = self.debug_sql_stream.read() self.errors[-1] = self.errors[-1] + (sql,) def addFailure(self, test, err): super().addFailure(test, err) self.debug_sql_stream.seek(0) self.failures[-1] = self.failures[-1] + (self.debug_sql_stream.read(),) def addSubTest(self, test, subtest, err): super().addSubTest(test, subtest, err) if err is not None: self.debug_sql_stream.seek(0) errors = ( self.failures if issubclass(err[0], test.failureException) else self.errors ) errors[-1] = errors[-1] + (self.debug_sql_stream.read(),) def printErrorList(self, flavour, errors): for test, err, sql_debug in errors: self.stream.writeln(self.separator1) self.stream.writeln("%s: %s" % (flavour, self.getDescription(test))) self.stream.writeln(self.separator2) self.stream.writeln(err) self.stream.writeln(self.separator2) self.stream.writeln(sql_debug) class PDBDebugResult(unittest.TextTestResult): """ Custom result class that triggers a PDB session when an error or failure occurs. """ def addError(self, test, err): super().addError(test, err) self.debug(err) def addFailure(self, test, err): super().addFailure(test, err) self.debug(err) def addSubTest(self, test, subtest, err): if err is not None: self.debug(err) super().addSubTest(test, subtest, err) def debug(self, error): self._restoreStdout() self.buffer = False exc_type, exc_value, traceback = error print("\nOpening PDB: %r" % exc_value) pdb.post_mortem(traceback) class DummyList: """ Dummy list class for faking storage of results in unittest.TestResult. """ __slots__ = () def append(self, item): pass class RemoteTestResult(unittest.TestResult): """ Extend unittest.TestResult to record events in the child processes so they can be replayed in the parent process. Events include things like which tests succeeded or failed. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Fake storage of results to reduce memory usage. These are used by the # unittest default methods, but here 'events' is used instead. dummy_list = DummyList() self.failures = dummy_list self.errors = dummy_list self.skipped = dummy_list self.expectedFailures = dummy_list self.unexpectedSuccesses = dummy_list if tblib is not None: tblib.pickling_support.install() self.events = [] def __getstate__(self): # Make this class picklable by removing the file-like buffer # attributes. This is possible since they aren't used after unpickling # after being sent to ParallelTestSuite. state = self.__dict__.copy() state.pop("_stdout_buffer", None) state.pop("_stderr_buffer", None) state.pop("_original_stdout", None) state.pop("_original_stderr", None) return state @property def test_index(self): return self.testsRun - 1 def _confirm_picklable(self, obj): """ Confirm that obj can be pickled and unpickled as multiprocessing will need to pickle the exception in the child process and unpickle it in the parent process. Let the exception rise, if not. """ pickle.loads(pickle.dumps(obj)) def _print_unpicklable_subtest(self, test, subtest, pickle_exc): print( """ Subtest failed: test: {} subtest: {} Unfortunately, the subtest that failed cannot be pickled, so the parallel test runner cannot handle it cleanly. Here is the pickling error: > {} You should re-run this test with --parallel=1 to reproduce the failure with a cleaner failure message. """.format( test, subtest, pickle_exc ) ) def check_picklable(self, test, err): # Ensure that sys.exc_info() tuples are picklable. This displays a # clear multiprocessing.pool.RemoteTraceback generated in the child # process instead of a multiprocessing.pool.MaybeEncodingError, making # the root cause easier to figure out for users who aren't familiar # with the multiprocessing module. Since we're in a forked process, # our best chance to communicate with them is to print to stdout. try: self._confirm_picklable(err) except Exception as exc: original_exc_txt = repr(err[1]) original_exc_txt = textwrap.fill( original_exc_txt, 75, initial_indent=" ", subsequent_indent=" " ) pickle_exc_txt = repr(exc) pickle_exc_txt = textwrap.fill( pickle_exc_txt, 75, initial_indent=" ", subsequent_indent=" " ) if tblib is None: print( """ {} failed: {} Unfortunately, tracebacks cannot be pickled, making it impossible for the parallel test runner to handle this exception cleanly. In order to see the traceback, you should install tblib: python -m pip install tblib """.format( test, original_exc_txt ) ) else: print( """ {} failed: {} Unfortunately, the exception it raised cannot be pickled, making it impossible for the parallel test runner to handle it cleanly. Here's the error encountered while trying to pickle the exception: {} You should re-run this test with the --parallel=1 option to reproduce the failure and get a correct traceback. """.format( test, original_exc_txt, pickle_exc_txt ) ) raise def check_subtest_picklable(self, test, subtest): try: self._confirm_picklable(subtest) except Exception as exc: self._print_unpicklable_subtest(test, subtest, exc) raise def startTestRun(self): super().startTestRun() self.events.append(("startTestRun",)) def stopTestRun(self): super().stopTestRun() self.events.append(("stopTestRun",)) def startTest(self, test): super().startTest(test) self.events.append(("startTest", self.test_index)) def stopTest(self, test): super().stopTest(test) self.events.append(("stopTest", self.test_index)) def addError(self, test, err): self.check_picklable(test, err) self.events.append(("addError", self.test_index, err)) super().addError(test, err) def addFailure(self, test, err): self.check_picklable(test, err) self.events.append(("addFailure", self.test_index, err)) super().addFailure(test, err) def addSubTest(self, test, subtest, err): # Follow Python's implementation of unittest.TestResult.addSubTest() by # not doing anything when a subtest is successful. if err is not None: # Call check_picklable() before check_subtest_picklable() since # check_picklable() performs the tblib check. self.check_picklable(test, err) self.check_subtest_picklable(test, subtest) self.events.append(("addSubTest", self.test_index, subtest, err)) super().addSubTest(test, subtest, err) def addSuccess(self, test): self.events.append(("addSuccess", self.test_index)) super().addSuccess(test) def addSkip(self, test, reason): self.events.append(("addSkip", self.test_index, reason)) super().addSkip(test, reason) def addExpectedFailure(self, test, err): # If tblib isn't installed, pickling the traceback will always fail. # However we don't want tblib to be required for running the tests # when they pass or fail as expected. Drop the traceback when an # expected failure occurs. if tblib is None: err = err[0], err[1], None self.check_picklable(test, err) self.events.append(("addExpectedFailure", self.test_index, err)) super().addExpectedFailure(test, err) def addUnexpectedSuccess(self, test): self.events.append(("addUnexpectedSuccess", self.test_index)) super().addUnexpectedSuccess(test) def wasSuccessful(self): """Tells whether or not this result was a success.""" failure_types = {"addError", "addFailure", "addSubTest", "addUnexpectedSuccess"} return all(e[0] not in failure_types for e in self.events) def _exc_info_to_string(self, err, test): # Make this method no-op. It only powers the default unittest behavior # for recording errors, but this class pickles errors into 'events' # instead. return "" class RemoteTestRunner: """ Run tests and record everything but don't display anything. The implementation matches the unpythonic coding style of unittest2. """ resultclass = RemoteTestResult def __init__(self, failfast=False, resultclass=None, buffer=False): self.failfast = failfast self.buffer = buffer if resultclass is not None: self.resultclass = resultclass def run(self, test): result = self.resultclass() unittest.registerResult(result) result.failfast = self.failfast result.buffer = self.buffer test(result) return result def get_max_test_processes(): """ The maximum number of test processes when using the --parallel option. """ # The current implementation of the parallel test runner requires # multiprocessing to start subprocesses with fork() or spawn(). if multiprocessing.get_start_method() not in {"fork", "spawn"}: return 1 try: return int(os.environ["DJANGO_TEST_PROCESSES"]) except KeyError: return multiprocessing.cpu_count() def parallel_type(value): """Parse value passed to the --parallel option.""" if value == "auto": return value try: return int(value) except ValueError: raise argparse.ArgumentTypeError( f"{value!r} is not an integer or the string 'auto'" ) _worker_id = 0 def _init_worker( counter, initial_settings=None, serialized_contents=None, process_setup=None, process_setup_args=None, ): """ Switch to databases dedicated to this worker. This helper lives at module-level because of the multiprocessing module's requirements. """ global _worker_id with counter.get_lock(): counter.value += 1 _worker_id = counter.value start_method = multiprocessing.get_start_method() if start_method == "spawn": if process_setup and callable(process_setup): if process_setup_args is None: process_setup_args = () process_setup(*process_setup_args) setup_test_environment() for alias in connections: connection = connections[alias] if start_method == "spawn": # Restore initial settings in spawned processes. connection.settings_dict.update(initial_settings[alias]) if value := serialized_contents.get(alias): connection._test_serialized_contents = value connection.creation.setup_worker_connection(_worker_id) with captured_stdout(): call_command("check", databases=connections) def _run_subsuite(args): """ Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult. This helper lives at module-level and its arguments are wrapped in a tuple because of the multiprocessing module's requirements. """ runner_class, subsuite_index, subsuite, failfast, buffer = args runner = runner_class(failfast=failfast, buffer=buffer) result = runner.run(subsuite) return subsuite_index, result.events class ParallelTestSuite(unittest.TestSuite): """ Run a series of tests in parallel in several processes. While the unittest module's documentation implies that orchestrating the execution of tests is the responsibility of the test runner, in practice, it appears that TestRunner classes are more concerned with formatting and displaying test results. Since there are fewer use cases for customizing TestSuite than TestRunner, implementing parallelization at the level of the TestSuite improves interoperability with existing custom test runners. A single instance of a test runner can still collect results from all tests without being aware that they have been run in parallel. """ # In case someone wants to modify these in a subclass. init_worker = _init_worker process_setup_args = () run_subsuite = _run_subsuite runner_class = RemoteTestRunner def __init__(self, subsuites, processes, failfast=False, buffer=False): self.subsuites = subsuites self.processes = processes self.failfast = failfast self.buffer = buffer self.initial_settings = None self.serialized_contents = None super().__init__() def process_setup(self, *args): """ Stub method to simplify run() implementation. "self" is never actually passed because a function implementing this method (__func__) is always used, not the method itself. """ pass def run(self, result): """ Distribute test cases across workers. Return an identifier of each test case with its result in order to use imap_unordered to show results as soon as they're available. To minimize pickling errors when getting results from workers: - pass back numeric indexes in self.subsuites instead of tests - make tracebacks picklable with tblib, if available Even with tblib, errors may still occur for dynamically created exception classes which cannot be unpickled. """ self.initialize_suite() counter = multiprocessing.Value(ctypes.c_int, 0) pool = multiprocessing.Pool( processes=self.processes, initializer=self.init_worker.__func__, initargs=[ counter, self.initial_settings, self.serialized_contents, self.process_setup.__func__, self.process_setup_args, ], ) args = [ (self.runner_class, index, subsuite, self.failfast, self.buffer) for index, subsuite in enumerate(self.subsuites) ] test_results = pool.imap_unordered(self.run_subsuite.__func__, args) while True: if result.shouldStop: pool.terminate() break try: subsuite_index, events = test_results.next(timeout=0.1) except multiprocessing.TimeoutError: continue except StopIteration: pool.close() break tests = list(self.subsuites[subsuite_index]) for event in events: event_name = event[0] handler = getattr(result, event_name, None) if handler is None: continue test = tests[event[1]] args = event[2:] handler(test, *args) pool.join() return result def __iter__(self): return iter(self.subsuites) def initialize_suite(self): if multiprocessing.get_start_method() == "spawn": self.initial_settings = { alias: connections[alias].settings_dict for alias in connections } self.serialized_contents = { alias: connections[alias]._test_serialized_contents for alias in connections if alias in self.serialized_aliases } class Shuffler: """ This class implements shuffling with a special consistency property. Consistency means that, for a given seed and key function, if two sets of items are shuffled, the resulting order will agree on the intersection of the two sets. For example, if items are removed from an original set, the shuffled order for the new set will be the shuffled order of the original set restricted to the smaller set. """ # This doesn't need to be cryptographically strong, so use what's fastest. hash_algorithm = "md5" @classmethod def _hash_text(cls, text): h = new_hash(cls.hash_algorithm, usedforsecurity=False) h.update(text.encode("utf-8")) return h.hexdigest() def __init__(self, seed=None): if seed is None: # Limit seeds to 10 digits for simpler output. seed = random.randint(0, 10**10 - 1) seed_source = "generated" else: seed_source = "given" self.seed = seed self.seed_source = seed_source @property def seed_display(self): return f"{self.seed!r} ({self.seed_source})" def _hash_item(self, item, key): text = "{}{}".format(self.seed, key(item)) return self._hash_text(text) def shuffle(self, items, key): """ Return a new list of the items in a shuffled order. The `key` is a function that accepts an item in `items` and returns a string unique for that item that can be viewed as a string id. The order of the return value is deterministic. It depends on the seed and key function but not on the original order. """ hashes = {} for item in items: hashed = self._hash_item(item, key) if hashed in hashes: msg = "item {!r} has same hash {!r} as item {!r}".format( item, hashed, hashes[hashed], ) raise RuntimeError(msg) hashes[hashed] = item return [hashes[hashed] for hashed in sorted(hashes)] class DiscoverRunner: """A Django test runner that uses unittest2 test discovery.""" test_suite = unittest.TestSuite parallel_test_suite = ParallelTestSuite test_runner = unittest.TextTestRunner test_loader = unittest.defaultTestLoader reorder_by = (TestCase, SimpleTestCase) def __init__( self, pattern=None, top_level=None, verbosity=1, interactive=True, failfast=False, keepdb=False, reverse=False, debug_mode=False, debug_sql=False, parallel=0, tags=None, exclude_tags=None, test_name_patterns=None, pdb=False, buffer=False, enable_faulthandler=True, timing=False, shuffle=False, logger=None, **kwargs, ): self.pattern = pattern self.top_level = top_level self.verbosity = verbosity self.interactive = interactive self.failfast = failfast self.keepdb = keepdb self.reverse = reverse self.debug_mode = debug_mode self.debug_sql = debug_sql self.parallel = parallel self.tags = set(tags or []) self.exclude_tags = set(exclude_tags or []) if not faulthandler.is_enabled() and enable_faulthandler: try: faulthandler.enable(file=sys.stderr.fileno()) except (AttributeError, io.UnsupportedOperation): faulthandler.enable(file=sys.__stderr__.fileno()) self.pdb = pdb if self.pdb and self.parallel > 1: raise ValueError( "You cannot use --pdb with parallel tests; pass --parallel=1 to use it." ) self.buffer = buffer self.test_name_patterns = None self.time_keeper = TimeKeeper() if timing else NullTimeKeeper() if test_name_patterns: # unittest does not export the _convert_select_pattern function # that converts command-line arguments to patterns. self.test_name_patterns = { pattern if "*" in pattern else "*%s*" % pattern for pattern in test_name_patterns } self.shuffle = shuffle self._shuffler = None self.logger = logger @classmethod def add_arguments(cls, parser): parser.add_argument( "-t", "--top-level-directory", dest="top_level", help="Top level of project for unittest discovery.", ) parser.add_argument( "-p", "--pattern", default="test*.py", help="The test matching pattern. Defaults to test*.py.", ) parser.add_argument( "--keepdb", action="store_true", help="Preserves the test DB between runs." ) parser.add_argument( "--shuffle", nargs="?", default=False, type=int, metavar="SEED", help="Shuffles test case order.", ) parser.add_argument( "-r", "--reverse", action="store_true", help="Reverses test case order.", ) parser.add_argument( "--debug-mode", action="store_true", help="Sets settings.DEBUG to True.", ) parser.add_argument( "-d", "--debug-sql", action="store_true", help="Prints logged SQL queries on failure.", ) parser.add_argument( "--parallel", nargs="?", const="auto", default=0, type=parallel_type, metavar="N", help=( "Run tests using up to N parallel processes. Use the value " '"auto" to run one test process for each processor core.' ), ) parser.add_argument( "--tag", action="append", dest="tags", help="Run only tests with the specified tag. Can be used multiple times.", ) parser.add_argument( "--exclude-tag", action="append", dest="exclude_tags", help="Do not run tests with the specified tag. Can be used multiple times.", ) parser.add_argument( "--pdb", action="store_true", help="Runs a debugger (pdb, or ipdb if installed) on error or failure.", ) parser.add_argument( "-b", "--buffer", action="store_true", help="Discard output from passing tests.", ) parser.add_argument( "--no-faulthandler", action="store_false", dest="enable_faulthandler", help="Disables the Python faulthandler module during tests.", ) parser.add_argument( "--timing", action="store_true", help=("Output timings, including database set up and total run time."), ) parser.add_argument( "-k", action="append", dest="test_name_patterns", help=( "Only run test methods and classes that match the pattern " "or substring. Can be used multiple times. Same as " "unittest -k option." ), ) @property def shuffle_seed(self): if self._shuffler is None: return None return self._shuffler.seed def log(self, msg, level=None): """ Log the message at the given logging level (the default is INFO). If a logger isn't set, the message is instead printed to the console, respecting the configured verbosity. A verbosity of 0 prints no output, a verbosity of 1 prints INFO and above, and a verbosity of 2 or higher prints all levels. """ if level is None: level = logging.INFO if self.logger is None: if self.verbosity <= 0 or (self.verbosity == 1 and level < logging.INFO): return print(msg) else: self.logger.log(level, msg) def setup_test_environment(self, **kwargs): setup_test_environment(debug=self.debug_mode) unittest.installHandler() def setup_shuffler(self): if self.shuffle is False: return shuffler = Shuffler(seed=self.shuffle) self.log(f"Using shuffle seed: {shuffler.seed_display}") self._shuffler = shuffler @contextmanager def load_with_patterns(self): original_test_name_patterns = self.test_loader.testNamePatterns self.test_loader.testNamePatterns = self.test_name_patterns try: yield finally: # Restore the original patterns. self.test_loader.testNamePatterns = original_test_name_patterns def load_tests_for_label(self, label, discover_kwargs): label_as_path = os.path.abspath(label) tests = None # If a module, or "module.ClassName[.method_name]", just run those. if not os.path.exists(label_as_path): with self.load_with_patterns(): tests = self.test_loader.loadTestsFromName(label) if tests.countTestCases(): return tests # Try discovery if "label" is a package or directory. is_importable, is_package = try_importing(label) if is_importable: if not is_package: return tests elif not os.path.isdir(label_as_path): if os.path.exists(label_as_path): assert tests is None raise RuntimeError( f"One of the test labels is a path to a file: {label!r}, " f"which is not supported. Use a dotted module name or " f"path to a directory instead." ) return tests kwargs = discover_kwargs.copy() if os.path.isdir(label_as_path) and not self.top_level: kwargs["top_level_dir"] = find_top_level(label_as_path) with self.load_with_patterns(): tests = self.test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the top-level dir it calculated from this run, # to support running tests from two different top-levels. self.test_loader._top_level_dir = None return tests def build_suite(self, test_labels=None, extra_tests=None, **kwargs): if extra_tests is not None: warnings.warn( "The extra_tests argument is deprecated.", RemovedInDjango50Warning, stacklevel=2, ) test_labels = test_labels or ["."] extra_tests = extra_tests or [] discover_kwargs = {} if self.pattern is not None: discover_kwargs["pattern"] = self.pattern if self.top_level is not None: discover_kwargs["top_level_dir"] = self.top_level self.setup_shuffler() all_tests = [] for label in test_labels: tests = self.load_tests_for_label(label, discover_kwargs) all_tests.extend(iter_test_cases(tests)) all_tests.extend(iter_test_cases(extra_tests)) if self.tags or self.exclude_tags: if self.tags: self.log( "Including test tag(s): %s." % ", ".join(sorted(self.tags)), level=logging.DEBUG, ) if self.exclude_tags: self.log( "Excluding test tag(s): %s." % ", ".join(sorted(self.exclude_tags)), level=logging.DEBUG, ) all_tests = filter_tests_by_tags(all_tests, self.tags, self.exclude_tags) # Put the failures detected at load time first for quicker feedback. # _FailedTest objects include things like test modules that couldn't be # found or that couldn't be loaded due to syntax errors. test_types = (unittest.loader._FailedTest, *self.reorder_by) all_tests = list( reorder_tests( all_tests, test_types, shuffler=self._shuffler, reverse=self.reverse, ) ) self.log("Found %d test(s)." % len(all_tests)) suite = self.test_suite(all_tests) if self.parallel > 1: subsuites = partition_suite_by_case(suite) # Since tests are distributed across processes on a per-TestCase # basis, there's no need for more processes than TestCases. processes = min(self.parallel, len(subsuites)) # Update also "parallel" because it's used to determine the number # of test databases. self.parallel = processes if processes > 1: suite = self.parallel_test_suite( subsuites, processes, self.failfast, self.buffer, ) return suite def setup_databases(self, **kwargs): return _setup_databases( self.verbosity, self.interactive, time_keeper=self.time_keeper, keepdb=self.keepdb, debug_sql=self.debug_sql, parallel=self.parallel, **kwargs, ) def get_resultclass(self): if self.debug_sql: return DebugSQLTextTestResult elif self.pdb: return PDBDebugResult def get_test_runner_kwargs(self): return { "failfast": self.failfast, "resultclass": self.get_resultclass(), "verbosity": self.verbosity, "buffer": self.buffer, } def run_checks(self, databases): # Checks are run after database creation since some checks require # database access. call_command("check", verbosity=self.verbosity, databases=databases) def run_suite(self, suite, **kwargs): kwargs = self.get_test_runner_kwargs() runner = self.test_runner(**kwargs) try: return runner.run(suite) finally: if self._shuffler is not None: seed_display = self._shuffler.seed_display self.log(f"Used shuffle seed: {seed_display}") def teardown_databases(self, old_config, **kwargs): """Destroy all the non-mirror databases.""" _teardown_databases( old_config, verbosity=self.verbosity, parallel=self.parallel, keepdb=self.keepdb, ) def teardown_test_environment(self, **kwargs): unittest.removeHandler() teardown_test_environment() def suite_result(self, suite, result, **kwargs): return ( len(result.failures) + len(result.errors) + len(result.unexpectedSuccesses) ) def _get_databases(self, suite): databases = {} for test in iter_test_cases(suite): test_databases = getattr(test, "databases", None) if test_databases == "__all__": test_databases = connections if test_databases: serialized_rollback = getattr(test, "serialized_rollback", False) databases.update( (alias, serialized_rollback or databases.get(alias, False)) for alias in test_databases ) return databases def get_databases(self, suite): databases = self._get_databases(suite) unused_databases = [alias for alias in connections if alias not in databases] if unused_databases: self.log( "Skipping setup of unused database(s): %s." % ", ".join(sorted(unused_databases)), level=logging.DEBUG, ) return databases def run_tests(self, test_labels, extra_tests=None, **kwargs): """ Run the unit tests for all the test labels in the provided list. Test labels should be dotted Python paths to test modules, test classes, or test methods. Return the number of tests that failed. """ if extra_tests is not None: warnings.warn( "The extra_tests argument is deprecated.", RemovedInDjango50Warning, stacklevel=2, ) self.setup_test_environment() suite = self.build_suite(test_labels, extra_tests) databases = self.get_databases(suite) suite.serialized_aliases = set( alias for alias, serialize in databases.items() if serialize ) with self.time_keeper.timed("Total database setup"): old_config = self.setup_databases( aliases=databases, serialized_aliases=suite.serialized_aliases, ) run_failed = False try: self.run_checks(databases) result = self.run_suite(suite) except Exception: run_failed = True raise finally: try: with self.time_keeper.timed("Total database teardown"): self.teardown_databases(old_config) self.teardown_test_environment() except Exception: # Silence teardown exceptions if an exception was raised during # runs to avoid shadowing it. if not run_failed: raise self.time_keeper.print_results() return self.suite_result(suite, result) def try_importing(label): """ Try importing a test label, and return (is_importable, is_package). Relative labels like "." and ".." are seen as directories. """ try: mod = import_module(label) except (ImportError, TypeError): return (False, False) return (True, hasattr(mod, "__path__")) def find_top_level(top_level): # Try to be a bit smarter than unittest about finding the default top-level # for a given directory path, to avoid breaking relative imports. # (Unittest's default is to set top-level equal to the path, which means # relative imports will result in "Attempted relative import in # non-package."). # We'd be happy to skip this and require dotted module paths (which don't # cause this problem) instead of file paths (which do), but in the case of # a directory in the cwd, which would be equally valid if considered as a # top-level module or as a directory path, unittest unfortunately prefers # the latter. while True: init_py = os.path.join(top_level, "__init__.py") if not os.path.exists(init_py): break try_next = os.path.dirname(top_level) if try_next == top_level: # __init__.py all the way down? give up. break top_level = try_next return top_level def _class_shuffle_key(cls): return f"{cls.__module__}.{cls.__qualname__}" def shuffle_tests(tests, shuffler): """ Return an iterator over the given tests in a shuffled order, keeping tests next to other tests of their class. `tests` should be an iterable of tests. """ tests_by_type = {} for _, class_tests in itertools.groupby(tests, type): class_tests = list(class_tests) test_type = type(class_tests[0]) class_tests = shuffler.shuffle(class_tests, key=lambda test: test.id()) tests_by_type[test_type] = class_tests classes = shuffler.shuffle(tests_by_type, key=_class_shuffle_key) return itertools.chain(*(tests_by_type[cls] for cls in classes)) def reorder_test_bin(tests, shuffler=None, reverse=False): """ Return an iterator that reorders the given tests, keeping tests next to other tests of their class. `tests` should be an iterable of tests that supports reversed(). """ if shuffler is None: if reverse: return reversed(tests) # The function must return an iterator. return iter(tests) tests = shuffle_tests(tests, shuffler) if not reverse: return tests # Arguments to reversed() must be reversible. return reversed(list(tests)) def reorder_tests(tests, classes, reverse=False, shuffler=None): """ Reorder an iterable of tests, grouping by the given TestCase classes. This function also removes any duplicates and reorders so that tests of the same type are consecutive. The result is returned as an iterator. `classes` is a sequence of types. Tests that are instances of `classes[0]` are grouped first, followed by instances of `classes[1]`, etc. Tests that are not instances of any of the classes are grouped last. If `reverse` is True, the tests within each `classes` group are reversed, but without reversing the order of `classes` itself. The `shuffler` argument is an optional instance of this module's `Shuffler` class. If provided, tests will be shuffled within each `classes` group, but keeping tests with other tests of their TestCase class. Reversing is applied after shuffling to allow reversing the same random order. """ # Each bin maps TestCase class to OrderedSet of tests. This permits tests # to be grouped by TestCase class even if provided non-consecutively. bins = [defaultdict(OrderedSet) for i in range(len(classes) + 1)] *class_bins, last_bin = bins for test in tests: for test_bin, test_class in zip(class_bins, classes): if isinstance(test, test_class): break else: test_bin = last_bin test_bin[type(test)].add(test) for test_bin in bins: # Call list() since reorder_test_bin()'s input must support reversed(). tests = list(itertools.chain.from_iterable(test_bin.values())) yield from reorder_test_bin(tests, shuffler=shuffler, reverse=reverse) def partition_suite_by_case(suite): """Partition a test suite by test case, preserving the order of tests.""" suite_class = type(suite) all_tests = iter_test_cases(suite) return [suite_class(tests) for _, tests in itertools.groupby(all_tests, type)] def test_match_tags(test, tags, exclude_tags): if isinstance(test, unittest.loader._FailedTest): # Tests that couldn't load always match to prevent tests from falsely # passing due e.g. to syntax errors. return True test_tags = set(getattr(test, "tags", [])) test_fn_name = getattr(test, "_testMethodName", str(test)) if hasattr(test, test_fn_name): test_fn = getattr(test, test_fn_name) test_fn_tags = list(getattr(test_fn, "tags", [])) test_tags = test_tags.union(test_fn_tags) if tags and test_tags.isdisjoint(tags): return False return test_tags.isdisjoint(exclude_tags) def filter_tests_by_tags(tests, tags, exclude_tags): """Return the matching tests as an iterator.""" return (test for test in tests if test_match_tags(test, tags, exclude_tags))
6c7d4c1869e33c022c58bff743852e92e75347eee074cee62d02ed2adf920f79
"Functions that help with dynamically creating decorators for views." from functools import partial, update_wrapper, wraps class classonlymethod(classmethod): def __get__(self, instance, cls=None): if instance is not None: raise AttributeError( "This method is available only on the class, not on instances." ) return super().__get__(instance, cls) def _update_method_wrapper(_wrapper, decorator): # _multi_decorate()'s bound_method isn't available in this scope. Cheat by # using it on a dummy function. @decorator def dummy(*args, **kwargs): pass update_wrapper(_wrapper, dummy) def _multi_decorate(decorators, method): """ Decorate `method` with one or more function decorators. `decorators` can be a single decorator or an iterable of decorators. """ if hasattr(decorators, "__iter__"): # Apply a list/tuple of decorators if 'decorators' is one. Decorator # functions are applied so that the call order is the same as the # order in which they appear in the iterable. decorators = decorators[::-1] else: decorators = [decorators] def _wrapper(self, *args, **kwargs): # bound_method has the signature that 'decorator' expects i.e. no # 'self' argument, but it's a closure over self so it can call # 'func'. Also, wrap method.__get__() in a function because new # attributes can't be set on bound method objects, only on functions. bound_method = wraps(method)(partial(method.__get__(self, type(self)))) for dec in decorators: bound_method = dec(bound_method) return bound_method(*args, **kwargs) # Copy any attributes that a decorator adds to the function it decorates. for dec in decorators: _update_method_wrapper(_wrapper, dec) # Preserve any existing attributes of 'method', including the name. update_wrapper(_wrapper, method) return _wrapper def method_decorator(decorator, name=""): """ Convert a function decorator into a method decorator """ # 'obj' can be a class or a function. If 'obj' is a function at the time it # is passed to _dec, it will eventually be a method of the class it is # defined on. If 'obj' is a class, the 'name' is required to be the name # of the method that will be decorated. def _dec(obj): if not isinstance(obj, type): return _multi_decorate(decorator, obj) if not (name and hasattr(obj, name)): raise ValueError( "The keyword argument `name` must be the name of a method " "of the decorated class: %s. Got '%s' instead." % (obj, name) ) method = getattr(obj, name) if not callable(method): raise TypeError( "Cannot decorate '%s' as it isn't a callable attribute of " "%s (%s)." % (name, obj, method) ) _wrapper = _multi_decorate(decorator, method) setattr(obj, name, _wrapper) return obj # Don't worry about making _dec look similar to a list/tuple as it's rather # meaningless. if not hasattr(decorator, "__iter__"): update_wrapper(_dec, decorator) # Change the name to aid debugging. obj = decorator if hasattr(decorator, "__name__") else decorator.__class__ _dec.__name__ = "method_decorator(%s)" % obj.__name__ return _dec def decorator_from_middleware_with_args(middleware_class): """ Like decorator_from_middleware, but return a function that accepts the arguments to be passed to the middleware_class. Use like:: cache_page = decorator_from_middleware_with_args(CacheMiddleware) # ... @cache_page(3600) def my_view(request): # ... """ return make_middleware_decorator(middleware_class) def decorator_from_middleware(middleware_class): """ Given a middleware class (not an instance), return a view decorator. This lets you use middleware functionality on a per-view basis. The middleware is created with no params passed. """ return make_middleware_decorator(middleware_class)() def make_middleware_decorator(middleware_class): def _make_decorator(*m_args, **m_kwargs): def _decorator(view_func): middleware = middleware_class(view_func, *m_args, **m_kwargs) @wraps(view_func) def _wrapper_view(request, *args, **kwargs): if hasattr(middleware, "process_request"): result = middleware.process_request(request) if result is not None: return result if hasattr(middleware, "process_view"): result = middleware.process_view(request, view_func, args, kwargs) if result is not None: return result try: response = view_func(request, *args, **kwargs) except Exception as e: if hasattr(middleware, "process_exception"): result = middleware.process_exception(request, e) if result is not None: return result raise if hasattr(response, "render") and callable(response.render): if hasattr(middleware, "process_template_response"): response = middleware.process_template_response( request, response ) # Defer running of process_response until after the template # has been rendered: if hasattr(middleware, "process_response"): def callback(response): return middleware.process_response(request, response) response.add_post_render_callback(callback) else: if hasattr(middleware, "process_response"): return middleware.process_response(request, response) return response return _wrapper_view return _decorator return _make_decorator def sync_and_async_middleware(func): """ Mark a middleware factory as returning a hybrid middleware supporting both types of request. """ func.sync_capable = True func.async_capable = True return func def sync_only_middleware(func): """ Mark a middleware factory as returning a sync middleware. This is the default. """ func.sync_capable = True func.async_capable = False return func def async_only_middleware(func): """Mark a middleware factory as returning an async middleware.""" func.sync_capable = False func.async_capable = True return func
c1a6bf90d7e73cb0cad7c61a1f1e81e39e0c347d73563c90fd675da94d7c3d2e
import itertools import logging import os import signal import subprocess import sys import threading import time import traceback import weakref from collections import defaultdict from functools import lru_cache, wraps from pathlib import Path from types import ModuleType from zipimport import zipimporter import django from django.apps import apps from django.core.signals import request_finished from django.dispatch import Signal from django.utils.functional import cached_property from django.utils.version import get_version_tuple autoreload_started = Signal() file_changed = Signal() DJANGO_AUTORELOAD_ENV = "RUN_MAIN" logger = logging.getLogger("django.utils.autoreload") # If an error is raised while importing a file, it's not placed in sys.modules. # This means that any future modifications aren't caught. Keep a list of these # file paths to allow watching them in the future. _error_files = [] _exception = None try: import termios except ImportError: termios = None try: import pywatchman except ImportError: pywatchman = None def is_django_module(module): """Return True if the given module is nested under Django.""" return module.__name__.startswith("django.") def is_django_path(path): """Return True if the given file path is nested under Django.""" return Path(django.__file__).parent in Path(path).parents def check_errors(fn): @wraps(fn) def wrapper(*args, **kwargs): global _exception try: fn(*args, **kwargs) except Exception: _exception = sys.exc_info() et, ev, tb = _exception if getattr(ev, "filename", None) is None: # get the filename from the last item in the stack filename = traceback.extract_tb(tb)[-1][0] else: filename = ev.filename if filename not in _error_files: _error_files.append(filename) raise return wrapper def raise_last_exception(): global _exception if _exception is not None: raise _exception[1] def ensure_echo_on(): """ Ensure that echo mode is enabled. Some tools such as PDB disable it which causes usability issues after reload. """ if not termios or not sys.stdin.isatty(): return attr_list = termios.tcgetattr(sys.stdin) if not attr_list[3] & termios.ECHO: attr_list[3] |= termios.ECHO if hasattr(signal, "SIGTTOU"): old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN) else: old_handler = None termios.tcsetattr(sys.stdin, termios.TCSANOW, attr_list) if old_handler is not None: signal.signal(signal.SIGTTOU, old_handler) def iter_all_python_module_files(): # This is a hot path during reloading. Create a stable sorted list of # modules based on the module name and pass it to iter_modules_and_files(). # This ensures cached results are returned in the usual case that modules # aren't loaded on the fly. keys = sorted(sys.modules) modules = tuple( m for m in map(sys.modules.__getitem__, keys) if not isinstance(m, weakref.ProxyTypes) ) return iter_modules_and_files(modules, frozenset(_error_files)) @lru_cache(maxsize=1) def iter_modules_and_files(modules, extra_files): """Iterate through all modules needed to be watched.""" sys_file_paths = [] for module in modules: # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects # are added to sys.modules, however they are types not modules and so # cause issues here. if not isinstance(module, ModuleType): continue if module.__name__ in ("__main__", "__mp_main__"): # __main__ (usually manage.py) doesn't always have a __spec__ set. # Handle this by falling back to using __file__, resolved below. # See https://docs.python.org/reference/import.html#main-spec # __file__ may not exists, e.g. when running ipdb debugger. if hasattr(module, "__file__"): sys_file_paths.append(module.__file__) continue if getattr(module, "__spec__", None) is None: continue spec = module.__spec__ # Modules could be loaded from places without a concrete location. If # this is the case, skip them. if spec.has_location: origin = ( spec.loader.archive if isinstance(spec.loader, zipimporter) else spec.origin ) sys_file_paths.append(origin) results = set() for filename in itertools.chain(sys_file_paths, extra_files): if not filename: continue path = Path(filename) try: if not path.exists(): # The module could have been removed, don't fail loudly if this # is the case. continue except ValueError as e: # Network filesystems may return null bytes in file paths. logger.debug('"%s" raised when resolving path: "%s"', e, path) continue resolved_path = path.resolve().absolute() results.add(resolved_path) return frozenset(results) @lru_cache(maxsize=1) def common_roots(paths): """ Return a tuple of common roots that are shared between the given paths. File system watchers operate on directories and aren't cheap to create. Try to find the minimum set of directories to watch that encompass all of the files that need to be watched. """ # Inspired from Werkzeug: # https://github.com/pallets/werkzeug/blob/7477be2853df70a022d9613e765581b9411c3c39/werkzeug/_reloader.py # Create a sorted list of the path components, longest first. path_parts = sorted([x.parts for x in paths], key=len, reverse=True) tree = {} for chunks in path_parts: node = tree # Add each part of the path to the tree. for chunk in chunks: node = node.setdefault(chunk, {}) # Clear the last leaf in the tree. node.clear() # Turn the tree into a list of Path instances. def _walk(node, path): for prefix, child in node.items(): yield from _walk(child, path + (prefix,)) if not node: yield Path(*path) return tuple(_walk(tree, ())) def sys_path_directories(): """ Yield absolute directories from sys.path, ignoring entries that don't exist. """ for path in sys.path: path = Path(path) if not path.exists(): continue resolved_path = path.resolve().absolute() # If the path is a file (like a zip file), watch the parent directory. if resolved_path.is_file(): yield resolved_path.parent else: yield resolved_path def get_child_arguments(): """ Return the executable. This contains a workaround for Windows if the executable is reported to not have the .exe extension which can cause bugs on reloading. """ import __main__ py_script = Path(sys.argv[0]) args = [sys.executable] + ["-W%s" % o for o in sys.warnoptions] if sys.implementation.name == "cpython": args.extend( f"-X{key}" if value is True else f"-X{key}={value}" for key, value in sys._xoptions.items() ) # __spec__ is set when the server was started with the `-m` option, # see https://docs.python.org/3/reference/import.html#main-spec # __spec__ may not exist, e.g. when running in a Conda env. if getattr(__main__, "__spec__", None) is not None: spec = __main__.__spec__ if (spec.name == "__main__" or spec.name.endswith(".__main__")) and spec.parent: name = spec.parent else: name = spec.name args += ["-m", name] args += sys.argv[1:] elif not py_script.exists(): # sys.argv[0] may not exist for several reasons on Windows. # It may exist with a .exe extension or have a -script.py suffix. exe_entrypoint = py_script.with_suffix(".exe") if exe_entrypoint.exists(): # Should be executed directly, ignoring sys.executable. return [exe_entrypoint, *sys.argv[1:]] script_entrypoint = py_script.with_name("%s-script.py" % py_script.name) if script_entrypoint.exists(): # Should be executed as usual. return [*args, script_entrypoint, *sys.argv[1:]] raise RuntimeError("Script %s does not exist." % py_script) else: args += sys.argv return args def trigger_reload(filename): logger.info("%s changed, reloading.", filename) sys.exit(3) def restart_with_reloader(): new_environ = {**os.environ, DJANGO_AUTORELOAD_ENV: "true"} args = get_child_arguments() while True: p = subprocess.run(args, env=new_environ, close_fds=False) if p.returncode != 3: return p.returncode class BaseReloader: def __init__(self): self.extra_files = set() self.directory_globs = defaultdict(set) self._stop_condition = threading.Event() def watch_dir(self, path, glob): path = Path(path) try: path = path.absolute() except FileNotFoundError: logger.debug( "Unable to watch directory %s as it cannot be resolved.", path, exc_info=True, ) return logger.debug("Watching dir %s with glob %s.", path, glob) self.directory_globs[path].add(glob) def watched_files(self, include_globs=True): """ Yield all files that need to be watched, including module files and files within globs. """ yield from iter_all_python_module_files() yield from self.extra_files if include_globs: for directory, patterns in self.directory_globs.items(): for pattern in patterns: yield from directory.glob(pattern) def wait_for_apps_ready(self, app_reg, django_main_thread): """ Wait until Django reports that the apps have been loaded. If the given thread has terminated before the apps are ready, then a SyntaxError or other non-recoverable error has been raised. In that case, stop waiting for the apps_ready event and continue processing. Return True if the thread is alive and the ready event has been triggered, or False if the thread is terminated while waiting for the event. """ while django_main_thread.is_alive(): if app_reg.ready_event.wait(timeout=0.1): return True else: logger.debug("Main Django thread has terminated before apps are ready.") return False def run(self, django_main_thread): logger.debug("Waiting for apps ready_event.") self.wait_for_apps_ready(apps, django_main_thread) from django.urls import get_resolver # Prevent a race condition where URL modules aren't loaded when the # reloader starts by accessing the urlconf_module property. try: get_resolver().urlconf_module except Exception: # Loading the urlconf can result in errors during development. # If this occurs then swallow the error and continue. pass logger.debug("Apps ready_event triggered. Sending autoreload_started signal.") autoreload_started.send(sender=self) self.run_loop() def run_loop(self): ticker = self.tick() while not self.should_stop: try: next(ticker) except StopIteration: break self.stop() def tick(self): """ This generator is called in a loop from run_loop. It's important that the method takes care of pausing or otherwise waiting for a period of time. This split between run_loop() and tick() is to improve the testability of the reloader implementations by decoupling the work they do from the loop. """ raise NotImplementedError("subclasses must implement tick().") @classmethod def check_availability(cls): raise NotImplementedError("subclasses must implement check_availability().") def notify_file_changed(self, path): results = file_changed.send(sender=self, file_path=path) logger.debug("%s notified as changed. Signal results: %s.", path, results) if not any(res[1] for res in results): trigger_reload(path) # These are primarily used for testing. @property def should_stop(self): return self._stop_condition.is_set() def stop(self): self._stop_condition.set() class StatReloader(BaseReloader): SLEEP_TIME = 1 # Check for changes once per second. def tick(self): mtimes = {} while True: for filepath, mtime in self.snapshot_files(): old_time = mtimes.get(filepath) mtimes[filepath] = mtime if old_time is None: logger.debug("File %s first seen with mtime %s", filepath, mtime) continue elif mtime > old_time: logger.debug( "File %s previous mtime: %s, current mtime: %s", filepath, old_time, mtime, ) self.notify_file_changed(filepath) time.sleep(self.SLEEP_TIME) yield def snapshot_files(self): # watched_files may produce duplicate paths if globs overlap. seen_files = set() for file in self.watched_files(): if file in seen_files: continue try: mtime = file.stat().st_mtime except OSError: # This is thrown when the file does not exist. continue seen_files.add(file) yield file, mtime @classmethod def check_availability(cls): return True class WatchmanUnavailable(RuntimeError): pass class WatchmanReloader(BaseReloader): def __init__(self): self.roots = defaultdict(set) self.processed_request = threading.Event() self.client_timeout = int(os.environ.get("DJANGO_WATCHMAN_TIMEOUT", 5)) super().__init__() @cached_property def client(self): return pywatchman.client(timeout=self.client_timeout) def _watch_root(self, root): # In practice this shouldn't occur, however, it's possible that a # directory that doesn't exist yet is being watched. If it's outside of # sys.path then this will end up a new root. How to handle this isn't # clear: Not adding the root will likely break when subscribing to the # changes, however, as this is currently an internal API, no files # will be being watched outside of sys.path. Fixing this by checking # inside watch_glob() and watch_dir() is expensive, instead this could # could fall back to the StatReloader if this case is detected? For # now, watching its parent, if possible, is sufficient. if not root.exists(): if not root.parent.exists(): logger.warning( "Unable to watch root dir %s as neither it or its parent exist.", root, ) return root = root.parent result = self.client.query("watch-project", str(root.absolute())) if "warning" in result: logger.warning("Watchman warning: %s", result["warning"]) logger.debug("Watchman watch-project result: %s", result) return result["watch"], result.get("relative_path") @lru_cache def _get_clock(self, root): return self.client.query("clock", root)["clock"] def _subscribe(self, directory, name, expression): root, rel_path = self._watch_root(directory) # Only receive notifications of files changing, filtering out other types # like special files: https://facebook.github.io/watchman/docs/type only_files_expression = [ "allof", ["anyof", ["type", "f"], ["type", "l"]], expression, ] query = { "expression": only_files_expression, "fields": ["name"], "since": self._get_clock(root), "dedup_results": True, } if rel_path: query["relative_root"] = rel_path logger.debug( "Issuing watchman subscription %s, for root %s. Query: %s", name, root, query, ) self.client.query("subscribe", root, name, query) def _subscribe_dir(self, directory, filenames): if not directory.exists(): if not directory.parent.exists(): logger.warning( "Unable to watch directory %s as neither it or its parent exist.", directory, ) return prefix = "files-parent-%s" % directory.name filenames = ["%s/%s" % (directory.name, filename) for filename in filenames] directory = directory.parent expression = ["name", filenames, "wholename"] else: prefix = "files" expression = ["name", filenames] self._subscribe(directory, "%s:%s" % (prefix, directory), expression) def _watch_glob(self, directory, patterns): """ Watch a directory with a specific glob. If the directory doesn't yet exist, attempt to watch the parent directory and amend the patterns to include this. It's important this method isn't called more than one per directory when updating all subscriptions. Subsequent calls will overwrite the named subscription, so it must include all possible glob expressions. """ prefix = "glob" if not directory.exists(): if not directory.parent.exists(): logger.warning( "Unable to watch directory %s as neither it or its parent exist.", directory, ) return prefix = "glob-parent-%s" % directory.name patterns = ["%s/%s" % (directory.name, pattern) for pattern in patterns] directory = directory.parent expression = ["anyof"] for pattern in patterns: expression.append(["match", pattern, "wholename"]) self._subscribe(directory, "%s:%s" % (prefix, directory), expression) def watched_roots(self, watched_files): extra_directories = self.directory_globs.keys() watched_file_dirs = [f.parent for f in watched_files] sys_paths = list(sys_path_directories()) return frozenset((*extra_directories, *watched_file_dirs, *sys_paths)) def _update_watches(self): watched_files = list(self.watched_files(include_globs=False)) found_roots = common_roots(self.watched_roots(watched_files)) logger.debug("Watching %s files", len(watched_files)) logger.debug("Found common roots: %s", found_roots) # Setup initial roots for performance, shortest roots first. for root in sorted(found_roots): self._watch_root(root) for directory, patterns in self.directory_globs.items(): self._watch_glob(directory, patterns) # Group sorted watched_files by their parent directory. sorted_files = sorted(watched_files, key=lambda p: p.parent) for directory, group in itertools.groupby(sorted_files, key=lambda p: p.parent): # These paths need to be relative to the parent directory. self._subscribe_dir( directory, [str(p.relative_to(directory)) for p in group] ) def update_watches(self): try: self._update_watches() except Exception as ex: # If the service is still available, raise the original exception. if self.check_server_status(ex): raise def _check_subscription(self, sub): subscription = self.client.getSubscription(sub) if not subscription: return logger.debug("Watchman subscription %s has results.", sub) for result in subscription: # When using watch-project, it's not simple to get the relative # directory without storing some specific state. Store the full # path to the directory in the subscription name, prefixed by its # type (glob, files). root_directory = Path(result["subscription"].split(":", 1)[1]) logger.debug("Found root directory %s", root_directory) for file in result.get("files", []): self.notify_file_changed(root_directory / file) def request_processed(self, **kwargs): logger.debug("Request processed. Setting update_watches event.") self.processed_request.set() def tick(self): request_finished.connect(self.request_processed) self.update_watches() while True: if self.processed_request.is_set(): self.update_watches() self.processed_request.clear() try: self.client.receive() except pywatchman.SocketTimeout: pass except pywatchman.WatchmanError as ex: logger.debug("Watchman error: %s, checking server status.", ex) self.check_server_status(ex) else: for sub in list(self.client.subs.keys()): self._check_subscription(sub) yield # Protect against busy loops. time.sleep(0.1) def stop(self): self.client.close() super().stop() def check_server_status(self, inner_ex=None): """Return True if the server is available.""" try: self.client.query("version") except Exception: raise WatchmanUnavailable(str(inner_ex)) from inner_ex return True @classmethod def check_availability(cls): if not pywatchman: raise WatchmanUnavailable("pywatchman not installed.") client = pywatchman.client(timeout=0.1) try: result = client.capabilityCheck() except Exception: # The service is down? raise WatchmanUnavailable("Cannot connect to the watchman service.") version = get_version_tuple(result["version"]) # Watchman 4.9 includes multiple improvements to watching project # directories as well as case insensitive filesystems. logger.debug("Watchman version %s", version) if version < (4, 9): raise WatchmanUnavailable("Watchman 4.9 or later is required.") def get_reloader(): """Return the most suitable reloader for this environment.""" try: WatchmanReloader.check_availability() except WatchmanUnavailable: return StatReloader() return WatchmanReloader() def start_django(reloader, main_func, *args, **kwargs): ensure_echo_on() main_func = check_errors(main_func) django_main_thread = threading.Thread( target=main_func, args=args, kwargs=kwargs, name="django-main-thread" ) django_main_thread.daemon = True django_main_thread.start() while not reloader.should_stop: try: reloader.run(django_main_thread) except WatchmanUnavailable as ex: # It's possible that the watchman service shuts down or otherwise # becomes unavailable. In that case, use the StatReloader. reloader = StatReloader() logger.error("Error connecting to Watchman: %s", ex) logger.info( "Watching for file changes with %s", reloader.__class__.__name__ ) def run_with_reloader(main_func, *args, **kwargs): signal.signal(signal.SIGTERM, lambda *args: sys.exit(0)) try: if os.environ.get(DJANGO_AUTORELOAD_ENV) == "true": reloader = get_reloader() logger.info( "Watching for file changes with %s", reloader.__class__.__name__ ) start_django(reloader, main_func, *args, **kwargs) else: exit_code = restart_with_reloader() sys.exit(exit_code) except KeyboardInterrupt: pass
0e997c90d102625598e23c6c1e5597a970142810ca6f0055d8ded0d2377db195
import asyncio import inspect import warnings from asgiref.sync import sync_to_async class RemovedInDjango50Warning(DeprecationWarning): pass class RemovedInDjango51Warning(PendingDeprecationWarning): pass RemovedInNextVersionWarning = RemovedInDjango50Warning RemovedAfterNextVersionWarning = RemovedInDjango51Warning class warn_about_renamed_method: def __init__( self, class_name, old_method_name, new_method_name, deprecation_warning ): self.class_name = class_name self.old_method_name = old_method_name self.new_method_name = new_method_name self.deprecation_warning = deprecation_warning def __call__(self, f): def wrapper(*args, **kwargs): warnings.warn( "`%s.%s` is deprecated, use `%s` instead." % (self.class_name, self.old_method_name, self.new_method_name), self.deprecation_warning, 2, ) return f(*args, **kwargs) return wrapper class RenameMethodsBase(type): """ Handles the deprecation paths when renaming a method. It does the following: 1) Define the new method if missing and complain about it. 2) Define the old method if missing. 3) Complain whenever an old method is called. See #15363 for more details. """ renamed_methods = () def __new__(cls, name, bases, attrs): new_class = super().__new__(cls, name, bases, attrs) for base in inspect.getmro(new_class): class_name = base.__name__ for renamed_method in cls.renamed_methods: old_method_name = renamed_method[0] old_method = base.__dict__.get(old_method_name) new_method_name = renamed_method[1] new_method = base.__dict__.get(new_method_name) deprecation_warning = renamed_method[2] wrapper = warn_about_renamed_method(class_name, *renamed_method) # Define the new method if missing and complain about it if not new_method and old_method: warnings.warn( "`%s.%s` method should be renamed `%s`." % (class_name, old_method_name, new_method_name), deprecation_warning, 2, ) setattr(base, new_method_name, old_method) setattr(base, old_method_name, wrapper(old_method)) # Define the old method as a wrapped call to the new method. if not old_method and new_method: setattr(base, old_method_name, wrapper(new_method)) return new_class class DeprecationInstanceCheck(type): def __instancecheck__(self, instance): warnings.warn( "`%s` is deprecated, use `%s` instead." % (self.__name__, self.alternative), self.deprecation_warning, 2, ) return super().__instancecheck__(instance) class MiddlewareMixin: sync_capable = True async_capable = True def __init__(self, get_response): if get_response is None: raise ValueError("get_response must be provided.") self.get_response = get_response self._async_check() super().__init__() def __repr__(self): return "<%s get_response=%s>" % ( self.__class__.__qualname__, getattr( self.get_response, "__qualname__", self.get_response.__class__.__name__, ), ) def _async_check(self): """ If get_response is a coroutine function, turns us into async mode so a thread is not consumed during a whole request. """ if asyncio.iscoroutinefunction(self.get_response): # Mark the class as async-capable, but do the actual switch # inside __call__ to avoid swapping out dunder methods self._is_coroutine = asyncio.coroutines._is_coroutine else: self._is_coroutine = None def __call__(self, request): # Exit out to async mode, if needed if self._is_coroutine: return self.__acall__(request) response = None if hasattr(self, "process_request"): response = self.process_request(request) response = response or self.get_response(request) if hasattr(self, "process_response"): response = self.process_response(request, response) return response async def __acall__(self, request): """ Async version of __call__ that is swapped in when an async request is running. """ response = None if hasattr(self, "process_request"): response = await sync_to_async( self.process_request, thread_sensitive=True, )(request) response = response or await self.get_response(request) if hasattr(self, "process_response"): response = await sync_to_async( self.process_response, thread_sensitive=True, )(request, response) return response
f9d2a0bcecae003582f26a341791c7f8e69d912f3bc45e0e1f3741dff7e92d47
""" Functions for working with "safe strings": strings that can be displayed safely without further escaping in HTML. Marking something as a "safe string" means that the producer of the string has already turned characters that should not be interpreted by the HTML engine (e.g. '<') into the appropriate entities. """ from functools import wraps from django.utils.functional import keep_lazy class SafeData: __slots__ = () def __html__(self): """ Return the html representation of a string for interoperability. This allows other template engines to understand Django's SafeData. """ return self class SafeString(str, SafeData): """ A str subclass that has been specifically marked as "safe" for HTML output purposes. """ __slots__ = () def __add__(self, rhs): """ Concatenating a safe string with another safe bytestring or safe string is safe. Otherwise, the result is no longer safe. """ t = super().__add__(rhs) if isinstance(rhs, SafeData): return SafeString(t) return t def __str__(self): return self SafeText = SafeString # For backwards compatibility since Django 2.0. def _safety_decorator(safety_marker, func): @wraps(func) def wrapper(*args, **kwargs): return safety_marker(func(*args, **kwargs)) return wrapper @keep_lazy(SafeString) def mark_safe(s): """ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string is appropriate. If used on a method as a decorator, mark the returned data as safe. Can be called multiple times on a single string. """ if hasattr(s, "__html__"): return s if callable(s): return _safety_decorator(mark_safe, s) return SafeString(s)
c13fe5075fce6979141322f2e9abe6e4304ad3818b966d8756a8af9d67087463
import datetime import decimal import functools import re import unicodedata from importlib import import_module from django.conf import settings from django.utils import dateformat, numberformat from django.utils.functional import lazy from django.utils.translation import check_for_language, get_language, to_locale # format_cache is a mapping from (format_type, lang) to the format string. # By using the cache, it is possible to avoid running get_format_modules # repeatedly. _format_cache = {} _format_modules_cache = {} ISO_INPUT_FORMATS = { "DATE_INPUT_FORMATS": ["%Y-%m-%d"], "TIME_INPUT_FORMATS": ["%H:%M:%S", "%H:%M:%S.%f", "%H:%M"], "DATETIME_INPUT_FORMATS": [ "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M", "%Y-%m-%d", ], } FORMAT_SETTINGS = frozenset( [ "DECIMAL_SEPARATOR", "THOUSAND_SEPARATOR", "NUMBER_GROUPING", "FIRST_DAY_OF_WEEK", "MONTH_DAY_FORMAT", "TIME_FORMAT", "DATE_FORMAT", "DATETIME_FORMAT", "SHORT_DATE_FORMAT", "SHORT_DATETIME_FORMAT", "YEAR_MONTH_FORMAT", "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ] ) def reset_format_cache(): """Clear any cached formats. This method is provided primarily for testing purposes, so that the effects of cached formats can be removed. """ global _format_cache, _format_modules_cache _format_cache = {} _format_modules_cache = {} def iter_format_modules(lang, format_module_path=None): """Find format modules.""" if not check_for_language(lang): return if format_module_path is None: format_module_path = settings.FORMAT_MODULE_PATH format_locations = [] if format_module_path: if isinstance(format_module_path, str): format_module_path = [format_module_path] for path in format_module_path: format_locations.append(path + ".%s") format_locations.append("django.conf.locale.%s") locale = to_locale(lang) locales = [locale] if "_" in locale: locales.append(locale.split("_")[0]) for location in format_locations: for loc in locales: try: yield import_module("%s.formats" % (location % loc)) except ImportError: pass def get_format_modules(lang=None): """Return a list of the format modules found.""" if lang is None: lang = get_language() if lang not in _format_modules_cache: _format_modules_cache[lang] = list( iter_format_modules(lang, settings.FORMAT_MODULE_PATH) ) return _format_modules_cache[lang] def get_format(format_type, lang=None, use_l10n=None): """ For a specific format type, return the format for the current language (locale). Default to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT'. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ if use_l10n is None: try: use_l10n = settings._USE_L10N_INTERNAL except AttributeError: use_l10n = settings.USE_L10N if use_l10n and lang is None: lang = get_language() format_type = str(format_type) # format_type may be lazy. cache_key = (format_type, lang) try: return _format_cache[cache_key] except KeyError: pass # The requested format_type has not been cached yet. Try to find it in any # of the format_modules for the given lang if l10n is enabled. If it's not # there or if l10n is disabled, fall back to the project settings. val = None if use_l10n: for module in get_format_modules(lang): val = getattr(module, format_type, None) if val is not None: break if val is None: if format_type not in FORMAT_SETTINGS: return format_type val = getattr(settings, format_type) elif format_type in ISO_INPUT_FORMATS: # If a list of input formats from one of the format_modules was # retrieved, make sure the ISO_INPUT_FORMATS are in this list. val = list(val) for iso_input in ISO_INPUT_FORMATS.get(format_type, ()): if iso_input not in val: val.append(iso_input) _format_cache[cache_key] = val return val get_format_lazy = lazy(get_format, str, list, tuple) def date_format(value, format=None, use_l10n=None): """ Format a datetime.date or datetime.datetime object using a localizable format. If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.format( value, get_format(format or "DATE_FORMAT", use_l10n=use_l10n) ) def time_format(value, format=None, use_l10n=None): """ Format a datetime.time object using a localizable format. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.time_format( value, get_format(format or "TIME_FORMAT", use_l10n=use_l10n) ) def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False): """ Format a numeric value using localization settings. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ if use_l10n is None: try: use_l10n = settings._USE_L10N_INTERNAL except AttributeError: use_l10n = settings.USE_L10N lang = get_language() if use_l10n else None return numberformat.format( value, get_format("DECIMAL_SEPARATOR", lang, use_l10n=use_l10n), decimal_pos, get_format("NUMBER_GROUPING", lang, use_l10n=use_l10n), get_format("THOUSAND_SEPARATOR", lang, use_l10n=use_l10n), force_grouping=force_grouping, use_l10n=use_l10n, ) def localize(value, use_l10n=None): """ Check if value is a localizable type (date, number...) and return it formatted as a string using current locale format. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ if isinstance(value, str): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Make sure booleans don't get treated as numbers return str(value) elif isinstance(value, (decimal.Decimal, float, int)): if use_l10n is False: return str(value) return number_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.datetime): return date_format(value, "DATETIME_FORMAT", use_l10n=use_l10n) elif isinstance(value, datetime.date): return date_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.time): return time_format(value, "TIME_FORMAT", use_l10n=use_l10n) return value def localize_input(value, default=None): """ Check if an input value is a localizable type and return it formatted with the appropriate formatting string of the current locale. """ if isinstance(value, str): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Don't treat booleans as numbers. return str(value) elif isinstance(value, (decimal.Decimal, float, int)): return number_format(value) elif isinstance(value, datetime.datetime): format = default or get_format("DATETIME_INPUT_FORMATS")[0] format = sanitize_strftime_format(format) return value.strftime(format) elif isinstance(value, datetime.date): format = default or get_format("DATE_INPUT_FORMATS")[0] format = sanitize_strftime_format(format) return value.strftime(format) elif isinstance(value, datetime.time): format = default or get_format("TIME_INPUT_FORMATS")[0] return value.strftime(format) return value @functools.lru_cache def sanitize_strftime_format(fmt): """ Ensure that certain specifiers are correctly padded with leading zeros. For years < 1000 specifiers %C, %F, %G, and %Y don't work as expected for strftime provided by glibc on Linux as they don't pad the year or century with leading zeros. Support for specifying the padding explicitly is available, however, which can be used to fix this issue. FreeBSD, macOS, and Windows do not support explicitly specifying the padding, but return four digit years (with leading zeros) as expected. This function checks whether the %Y produces a correctly padded string and, if not, makes the following substitutions: - %C → %02C - %F → %010F - %G → %04G - %Y → %04Y See https://bugs.python.org/issue13305 for more details. """ if datetime.date(1, 1, 1).strftime("%Y") == "0001": return fmt mapping = {"C": 2, "F": 10, "G": 4, "Y": 4} return re.sub( r"((?:^|[^%])(?:%%)*)%([CFGY])", lambda m: r"%s%%0%s%s" % (m[1], mapping[m[2]], m[2]), fmt, ) def sanitize_separators(value): """ Sanitize a value according to the current decimal and thousand separator setting. Used with form field input. """ if isinstance(value, str): parts = [] decimal_separator = get_format("DECIMAL_SEPARATOR") if decimal_separator in value: value, decimals = value.split(decimal_separator, 1) parts.append(decimals) if settings.USE_THOUSAND_SEPARATOR: thousand_sep = get_format("THOUSAND_SEPARATOR") if ( thousand_sep == "." and value.count(".") == 1 and len(value.split(".")[-1]) != 3 ): # Special case where we suspect a dot meant decimal separator # (see #22171). pass else: for replacement in { thousand_sep, unicodedata.normalize("NFKD", thousand_sep), }: value = value.replace(replacement, "") parts.append(value) value = ".".join(reversed(parts)) return value
dc78da6d5056edf0392213aba8715900cbda28783aecc7757b7b731d72368518
""" This is the Django template system. How it works: The Lexer.tokenize() method converts a template string (i.e., a string containing markup with custom template tags) to tokens, which can be either plain text (TokenType.TEXT), variables (TokenType.VAR), or block statements (TokenType.BLOCK). The Parser() class takes a list of tokens in its constructor, and its parse() method returns a compiled template -- which is, under the hood, a list of Node objects. Each Node is responsible for creating some sort of output -- e.g. simple text (TextNode), variable values in a given context (VariableNode), results of basic logic (IfNode), results of looping (ForNode), or anything else. The core Node types are TextNode, VariableNode, IfNode and ForNode, but plugin modules can define their own custom node types. Each Node has a render() method, which takes a Context and returns a string of the rendered node. For example, the render() method of a Variable Node returns the variable's value as a string. The render() method of a ForNode returns the rendered output of whatever was inside the loop, recursively. The Template class is a convenient wrapper that takes care of template compilation and rendering. Usage: The only thing you should ever use directly in this file is the Template class. Create a compiled template object with a template_string, then call render() with a context. In the compilation stage, the TemplateSyntaxError exception will be raised if the template doesn't have proper syntax. Sample code: >>> from django import template >>> s = '<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>' >>> t = template.Template(s) (t is now a compiled template, and its render() method can be called multiple times with multiple contexts) >>> c = template.Context({'test':True, 'varvalue': 'Hello'}) >>> t.render(c) '<html><h1>Hello</h1></html>' >>> c = template.Context({'test':False, 'varvalue': 'Hello'}) >>> t.render(c) '<html></html>' """ import inspect import logging import re from enum import Enum from django.template.context import BaseContext from django.utils.formats import localize from django.utils.html import conditional_escape, escape from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import SafeData, SafeString, mark_safe from django.utils.text import get_text_list, smart_split, unescape_string_literal from django.utils.timezone import template_localtime from django.utils.translation import gettext_lazy, pgettext_lazy from .exceptions import TemplateSyntaxError # template syntax constants FILTER_SEPARATOR = "|" FILTER_ARGUMENT_SEPARATOR = ":" VARIABLE_ATTRIBUTE_SEPARATOR = "." BLOCK_TAG_START = "{%" BLOCK_TAG_END = "%}" VARIABLE_TAG_START = "{{" VARIABLE_TAG_END = "}}" COMMENT_TAG_START = "{#" COMMENT_TAG_END = "#}" SINGLE_BRACE_START = "{" SINGLE_BRACE_END = "}" # what to report as the origin for templates that come from non-loader sources # (e.g. strings) UNKNOWN_SOURCE = "<unknown source>" # Match BLOCK_TAG_*, VARIABLE_TAG_*, and COMMENT_TAG_* tags and capture the # entire tag, including start/end delimiters. Using re.compile() is faster # than instantiating SimpleLazyObject with _lazy_re_compile(). tag_re = re.compile(r"({%.*?%}|{{.*?}}|{#.*?#})") logger = logging.getLogger("django.template") class TokenType(Enum): TEXT = 0 VAR = 1 BLOCK = 2 COMMENT = 3 class VariableDoesNotExist(Exception): def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self): return self.msg % self.params class Origin: def __init__(self, name, template_name=None, loader=None): self.name = name self.template_name = template_name self.loader = loader def __str__(self): return self.name def __repr__(self): return "<%s name=%r>" % (self.__class__.__qualname__, self.name) def __eq__(self, other): return ( isinstance(other, Origin) and self.name == other.name and self.loader == other.loader ) @property def loader_name(self): if self.loader: return "%s.%s" % ( self.loader.__module__, self.loader.__class__.__name__, ) class Template: def __init__(self, template_string, origin=None, name=None, engine=None): # If Template is instantiated directly rather than from an Engine and # exactly one Django template engine is configured, use that engine. # This is required to preserve backwards-compatibility for direct use # e.g. Template('...').render(Context({...})) if engine is None: from .engine import Engine engine = Engine.get_default() if origin is None: origin = Origin(UNKNOWN_SOURCE) self.name = name self.origin = origin self.engine = engine self.source = str(template_string) # May be lazy. self.nodelist = self.compile_nodelist() def __iter__(self): for node in self.nodelist: yield from node def __repr__(self): return '<%s template_string="%s...">' % ( self.__class__.__qualname__, self.source[:20].replace("\n", ""), ) def _render(self, context): return self.nodelist.render(context) def render(self, context): "Display stage -- can be called many times" with context.render_context.push_state(self): if context.template is None: with context.bind_template(self): context.template_name = self.name return self._render(context) else: return self._render(context) def compile_nodelist(self): """ Parse and compile the template source into a nodelist. If debug is True and an exception occurs during parsing, the exception is annotated with contextual line information where it occurred in the template source. """ if self.engine.debug: lexer = DebugLexer(self.source) else: lexer = Lexer(self.source) tokens = lexer.tokenize() parser = Parser( tokens, self.engine.template_libraries, self.engine.template_builtins, self.origin, ) try: return parser.parse() except Exception as e: if self.engine.debug: e.template_debug = self.get_exception_info(e, e.token) raise def get_exception_info(self, exception, token): """ Return a dictionary containing contextual line information of where the exception occurred in the template. The following information is provided: message The message of the exception raised. source_lines The lines before, after, and including the line the exception occurred on. line The line number the exception occurred on. before, during, after The line the exception occurred on split into three parts: 1. The content before the token that raised the error. 2. The token that raised the error. 3. The content after the token that raised the error. total The number of lines in source_lines. top The line number where source_lines starts. bottom The line number where source_lines ends. start The start position of the token in the template source. end The end position of the token in the template source. """ start, end = token.position context_lines = 10 line = 0 upto = 0 source_lines = [] before = during = after = "" for num, next in enumerate(linebreak_iter(self.source)): if start >= upto and end <= next: line = num before = escape(self.source[upto:start]) during = escape(self.source[start:end]) after = escape(self.source[end:next]) source_lines.append((num, escape(self.source[upto:next]))) upto = next total = len(source_lines) top = max(1, line - context_lines) bottom = min(total, line + 1 + context_lines) # In some rare cases exc_value.args can be empty or an invalid # string. try: message = str(exception.args[0]) except (IndexError, UnicodeDecodeError): message = "(Could not get exception message)" return { "message": message, "source_lines": source_lines[top:bottom], "before": before, "during": during, "after": after, "top": top, "bottom": bottom, "total": total, "line": line, "name": self.origin.name, "start": start, "end": end, } def linebreak_iter(template_source): yield 0 p = template_source.find("\n") while p >= 0: yield p + 1 p = template_source.find("\n", p + 1) yield len(template_source) + 1 class Token: def __init__(self, token_type, contents, position=None, lineno=None): """ A token representing a string from the template. token_type A TokenType, either .TEXT, .VAR, .BLOCK, or .COMMENT. contents The token source string. position An optional tuple containing the start and end index of the token in the template source. This is used for traceback information when debug is on. lineno The line number the token appears on in the template source. This is used for traceback information and gettext files. """ self.token_type, self.contents = token_type, contents self.lineno = lineno self.position = position def __repr__(self): token_name = self.token_type.name.capitalize() return '<%s token: "%s...">' % ( token_name, self.contents[:20].replace("\n", ""), ) def split_contents(self): split = [] bits = smart_split(self.contents) for bit in bits: # Handle translation-marked template pieces if bit.startswith(('_("', "_('")): sentinel = bit[2] + ")" trans_bit = [bit] while not bit.endswith(sentinel): bit = next(bits) trans_bit.append(bit) bit = " ".join(trans_bit) split.append(bit) return split class Lexer: def __init__(self, template_string): self.template_string = template_string self.verbatim = False def __repr__(self): return '<%s template_string="%s...", verbatim=%s>' % ( self.__class__.__qualname__, self.template_string[:20].replace("\n", ""), self.verbatim, ) def tokenize(self): """ Return a list of tokens from a given template_string. """ in_tag = False lineno = 1 result = [] for token_string in tag_re.split(self.template_string): if token_string: result.append(self.create_token(token_string, None, lineno, in_tag)) lineno += token_string.count("\n") in_tag = not in_tag return result def create_token(self, token_string, position, lineno, in_tag): """ Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string. """ if in_tag: # The [0:2] and [2:-2] ranges below strip off *_TAG_START and # *_TAG_END. The 2's are hard-coded for performance. Using # len(BLOCK_TAG_START) would permit BLOCK_TAG_START to be # different, but it's not likely that the TAG_START values will # change anytime soon. token_start = token_string[0:2] if token_start == BLOCK_TAG_START: content = token_string[2:-2].strip() if self.verbatim: # Then a verbatim block is being processed. if content != self.verbatim: return Token(TokenType.TEXT, token_string, position, lineno) # Otherwise, the current verbatim block is ending. self.verbatim = False elif content[:9] in ("verbatim", "verbatim "): # Then a verbatim block is starting. self.verbatim = "end%s" % content return Token(TokenType.BLOCK, content, position, lineno) if not self.verbatim: content = token_string[2:-2].strip() if token_start == VARIABLE_TAG_START: return Token(TokenType.VAR, content, position, lineno) # BLOCK_TAG_START was handled above. assert token_start == COMMENT_TAG_START return Token(TokenType.COMMENT, content, position, lineno) return Token(TokenType.TEXT, token_string, position, lineno) class DebugLexer(Lexer): def _tag_re_split_positions(self): last = 0 for match in tag_re.finditer(self.template_string): start, end = match.span() yield last, start yield start, end last = end yield last, len(self.template_string) # This parallels the use of tag_re.split() in Lexer.tokenize(). def _tag_re_split(self): for position in self._tag_re_split_positions(): yield self.template_string[slice(*position)], position def tokenize(self): """ Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so only use it when debug is True. """ # For maintainability, it is helpful if the implementation below can # continue to closely parallel Lexer.tokenize()'s implementation. in_tag = False lineno = 1 result = [] for token_string, position in self._tag_re_split(): if token_string: result.append(self.create_token(token_string, position, lineno, in_tag)) lineno += token_string.count("\n") in_tag = not in_tag return result class Parser: def __init__(self, tokens, libraries=None, builtins=None, origin=None): # Reverse the tokens so delete_first_token(), prepend_token(), and # next_token() can operate at the end of the list in constant time. self.tokens = list(reversed(tokens)) self.tags = {} self.filters = {} self.command_stack = [] if libraries is None: libraries = {} if builtins is None: builtins = [] self.libraries = libraries for builtin in builtins: self.add_library(builtin) self.origin = origin def __repr__(self): return "<%s tokens=%r>" % (self.__class__.__qualname__, self.tokens) def parse(self, parse_until=None): """ Iterate through the parser tokens and compiles each one into a node. If parse_until is provided, parsing will stop once one of the specified tokens has been reached. This is formatted as a list of tokens, e.g. ['elif', 'else', 'endif']. If no matching token is reached, raise an exception with the unclosed block tag details. """ if parse_until is None: parse_until = [] nodelist = NodeList() while self.tokens: token = self.next_token() # Use the raw values here for TokenType.* for a tiny performance boost. token_type = token.token_type.value if token_type == 0: # TokenType.TEXT self.extend_nodelist(nodelist, TextNode(token.contents), token) elif token_type == 1: # TokenType.VAR if not token.contents: raise self.error( token, "Empty variable tag on line %d" % token.lineno ) try: filter_expression = self.compile_filter(token.contents) except TemplateSyntaxError as e: raise self.error(token, e) var_node = VariableNode(filter_expression) self.extend_nodelist(nodelist, var_node, token) elif token_type == 2: # TokenType.BLOCK try: command = token.contents.split()[0] except IndexError: raise self.error(token, "Empty block tag on line %d" % token.lineno) if command in parse_until: # A matching token has been reached. Return control to # the caller. Put the token back on the token list so the # caller knows where it terminated. self.prepend_token(token) return nodelist # Add the token to the command stack. This is used for error # messages if further parsing fails due to an unclosed block # tag. self.command_stack.append((command, token)) # Get the tag callback function from the ones registered with # the parser. try: compile_func = self.tags[command] except KeyError: self.invalid_block_tag(token, command, parse_until) # Compile the callback into a node object and add it to # the node list. try: compiled_result = compile_func(self, token) except Exception as e: raise self.error(token, e) self.extend_nodelist(nodelist, compiled_result, token) # Compile success. Remove the token from the command stack. self.command_stack.pop() if parse_until: self.unclosed_block_tag(parse_until) return nodelist def skip_past(self, endtag): while self.tokens: token = self.next_token() if token.token_type == TokenType.BLOCK and token.contents == endtag: return self.unclosed_block_tag([endtag]) def extend_nodelist(self, nodelist, node, token): # Check that non-text nodes don't appear before an extends tag. if node.must_be_first and nodelist.contains_nontext: raise self.error( token, "%r must be the first tag in the template." % node, ) if not isinstance(node, TextNode): nodelist.contains_nontext = True # Set origin and token here since we can't modify the node __init__() # method. node.token = token node.origin = self.origin nodelist.append(node) def error(self, token, e): """ Return an exception annotated with the originating token. Since the parser can be called recursively, check if a token is already set. This ensures the innermost token is highlighted if an exception occurs, e.g. a compile error within the body of an if statement. """ if not isinstance(e, Exception): e = TemplateSyntaxError(e) if not hasattr(e, "token"): e.token = token return e def invalid_block_tag(self, token, command, parse_until=None): if parse_until: raise self.error( token, "Invalid block tag on line %d: '%s', expected %s. Did you " "forget to register or load this tag?" % ( token.lineno, command, get_text_list(["'%s'" % p for p in parse_until], "or"), ), ) raise self.error( token, "Invalid block tag on line %d: '%s'. Did you forget to register " "or load this tag?" % (token.lineno, command), ) def unclosed_block_tag(self, parse_until): command, token = self.command_stack.pop() msg = "Unclosed tag on line %d: '%s'. Looking for one of: %s." % ( token.lineno, command, ", ".join(parse_until), ) raise self.error(token, msg) def next_token(self): return self.tokens.pop() def prepend_token(self, token): self.tokens.append(token) def delete_first_token(self): del self.tokens[-1] def add_library(self, lib): self.tags.update(lib.tags) self.filters.update(lib.filters) def compile_filter(self, token): """ Convenient wrapper for FilterExpression """ return FilterExpression(token, self) def find_filter(self, filter_name): if filter_name in self.filters: return self.filters[filter_name] else: raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name) # This only matches constant *strings* (things in quotes or marked for # translation). Numbers are treated as variables for implementation reasons # (so that they retain their type when passed to filters). constant_string = r""" (?:%(i18n_open)s%(strdq)s%(i18n_close)s| %(i18n_open)s%(strsq)s%(i18n_close)s| %(strdq)s| %(strsq)s) """ % { "strdq": r'"[^"\\]*(?:\\.[^"\\]*)*"', # double-quoted string "strsq": r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string "i18n_open": re.escape("_("), "i18n_close": re.escape(")"), } constant_string = constant_string.replace("\n", "") filter_raw_string = r""" ^(?P<constant>%(constant)s)| ^(?P<var>[%(var_chars)s]+|%(num)s)| (?:\s*%(filter_sep)s\s* (?P<filter_name>\w+) (?:%(arg_sep)s (?: (?P<constant_arg>%(constant)s)| (?P<var_arg>[%(var_chars)s]+|%(num)s) ) )? )""" % { "constant": constant_string, "num": r"[-+\.]?\d[\d\.e]*", "var_chars": r"\w\.", "filter_sep": re.escape(FILTER_SEPARATOR), "arg_sep": re.escape(FILTER_ARGUMENT_SEPARATOR), } filter_re = _lazy_re_compile(filter_raw_string, re.VERBOSE) class FilterExpression: """ Parse a variable token and its optional filters (all as a single string), and return a list of tuples of the filter name and arguments. Sample:: >>> token = 'variable|default:"Default value"|date:"Y-m-d"' >>> p = Parser('') >>> fe = FilterExpression(token, p) >>> len(fe.filters) 2 >>> fe.var <Variable: 'variable'> """ __slots__ = ("token", "filters", "var", "is_var") def __init__(self, token, parser): self.token = token matches = filter_re.finditer(token) var_obj = None filters = [] upto = 0 for match in matches: start = match.start() if upto != start: raise TemplateSyntaxError( "Could not parse some characters: " "%s|%s|%s" % (token[:upto], token[upto:start], token[start:]) ) if var_obj is None: var, constant = match["var"], match["constant"] if constant: try: var_obj = Variable(constant).resolve({}) except VariableDoesNotExist: var_obj = None elif var is None: raise TemplateSyntaxError( "Could not find variable at start of %s." % token ) else: var_obj = Variable(var) else: filter_name = match["filter_name"] args = [] constant_arg, var_arg = match["constant_arg"], match["var_arg"] if constant_arg: args.append((False, Variable(constant_arg).resolve({}))) elif var_arg: args.append((True, Variable(var_arg))) filter_func = parser.find_filter(filter_name) self.args_check(filter_name, filter_func, args) filters.append((filter_func, args)) upto = match.end() if upto != len(token): raise TemplateSyntaxError( "Could not parse the remainder: '%s' " "from '%s'" % (token[upto:], token) ) self.filters = filters self.var = var_obj self.is_var = isinstance(var_obj, Variable) def resolve(self, context, ignore_failures=False): if self.is_var: try: obj = self.var.resolve(context) except VariableDoesNotExist: if ignore_failures: obj = None else: string_if_invalid = context.template.engine.string_if_invalid if string_if_invalid: if "%s" in string_if_invalid: return string_if_invalid % self.var else: return string_if_invalid else: obj = string_if_invalid else: obj = self.var for func, args in self.filters: arg_vals = [] for lookup, arg in args: if not lookup: arg_vals.append(mark_safe(arg)) else: arg_vals.append(arg.resolve(context)) if getattr(func, "expects_localtime", False): obj = template_localtime(obj, context.use_tz) if getattr(func, "needs_autoescape", False): new_obj = func(obj, autoescape=context.autoescape, *arg_vals) else: new_obj = func(obj, *arg_vals) if getattr(func, "is_safe", False) and isinstance(obj, SafeData): obj = mark_safe(new_obj) else: obj = new_obj return obj def args_check(name, func, provided): provided = list(provided) # First argument, filter input, is implied. plen = len(provided) + 1 # Check to see if a decorator is providing the real function. func = inspect.unwrap(func) args, _, _, defaults, _, _, _ = inspect.getfullargspec(func) alen = len(args) dlen = len(defaults or []) # Not enough OR Too many if plen < (alen - dlen) or plen > alen: raise TemplateSyntaxError( "%s requires %d arguments, %d provided" % (name, alen - dlen, plen) ) return True args_check = staticmethod(args_check) def __str__(self): return self.token def __repr__(self): return "<%s %r>" % (self.__class__.__qualname__, self.token) class Variable: """ A template variable, resolvable against a given context. The variable may be a hard-coded string (if it begins and ends with single or double quote marks):: >>> c = {'article': {'section':'News'}} >>> Variable('article.section').resolve(c) 'News' >>> Variable('article').resolve(c) {'section': 'News'} >>> class AClass: pass >>> c = AClass() >>> c.article = AClass() >>> c.article.section = 'News' (The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.') """ __slots__ = ("var", "literal", "lookups", "translate", "message_context") def __init__(self, var): self.var = var self.literal = None self.lookups = None self.translate = False self.message_context = None if not isinstance(var, str): raise TypeError("Variable must be a string or number, got %s" % type(var)) try: # First try to treat this variable as a number. # # Note that this could cause an OverflowError here that we're not # catching. Since this should only happen at compile time, that's # probably OK. # Try to interpret values containing a period or an 'e'/'E' # (possibly scientific notation) as a float; otherwise, try int. if "." in var or "e" in var.lower(): self.literal = float(var) # "2." is invalid if var[-1] == ".": raise ValueError else: self.literal = int(var) except ValueError: # A ValueError means that the variable isn't a number. if var[0:2] == "_(" and var[-1] == ")": # The result of the lookup should be translated at rendering # time. self.translate = True var = var[2:-1] # If it's wrapped with quotes (single or double), then # we're also dealing with a literal. try: self.literal = mark_safe(unescape_string_literal(var)) except ValueError: # Otherwise we'll set self.lookups so that resolve() knows we're # dealing with a bonafide variable if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in var or var[0] == "_": raise TemplateSyntaxError( "Variables and attributes may " "not begin with underscores: '%s'" % var ) self.lookups = tuple(var.split(VARIABLE_ATTRIBUTE_SEPARATOR)) def resolve(self, context): """Resolve this variable against a given context.""" if self.lookups is not None: # We're dealing with a variable that needs to be resolved value = self._resolve_lookup(context) else: # We're dealing with a literal, so it's already been "resolved" value = self.literal if self.translate: is_safe = isinstance(value, SafeData) msgid = value.replace("%", "%%") msgid = mark_safe(msgid) if is_safe else msgid if self.message_context: return pgettext_lazy(self.message_context, msgid) else: return gettext_lazy(msgid) return value def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.var) def __str__(self): return self.var def _resolve_lookup(self, context): """ Perform resolution of a real variable (i.e. not a literal) against the given context. As indicated by the method's name, this method is an implementation detail and shouldn't be called by external code. Use Variable.resolve() instead. """ current = context try: # catch-all for silent variable failures for bit in self.lookups: try: # dictionary lookup current = current[bit] # ValueError/IndexError are for numpy.array lookup on # numpy < 1.9 and 1.9+ respectively except (TypeError, AttributeError, KeyError, ValueError, IndexError): try: # attribute lookup # Don't return class attributes if the class is the context: if isinstance(current, BaseContext) and getattr( type(current), bit ): raise AttributeError current = getattr(current, bit) except (TypeError, AttributeError): # Reraise if the exception was raised by a @property if not isinstance(current, BaseContext) and bit in dir(current): raise try: # list-index lookup current = current[int(bit)] except ( IndexError, # list index out of range ValueError, # invalid literal for int() KeyError, # current is a dict without `int(bit)` key TypeError, ): # unsubscriptable object raise VariableDoesNotExist( "Failed lookup for key [%s] in %r", (bit, current), ) # missing attribute if callable(current): if getattr(current, "do_not_call_in_templates", False): pass elif getattr(current, "alters_data", False): current = context.template.engine.string_if_invalid else: try: # method call (assuming no args required) current = current() except TypeError: try: signature = inspect.signature(current) except ValueError: # No signature found. current = context.template.engine.string_if_invalid else: try: signature.bind() except TypeError: # Arguments *were* required. # Invalid method call. current = context.template.engine.string_if_invalid else: raise except Exception as e: template_name = getattr(context, "template_name", None) or "unknown" logger.debug( "Exception while resolving variable '%s' in template '%s'.", bit, template_name, exc_info=True, ) if getattr(e, "silent_variable_failure", False): current = context.template.engine.string_if_invalid else: raise return current class Node: # Set this to True for nodes that must be first in the template (although # they can be preceded by text nodes. must_be_first = False child_nodelists = ("nodelist",) token = None def render(self, context): """ Return the node rendered as a string. """ pass def render_annotated(self, context): """ Render the node. If debug is True and an exception occurs during rendering, the exception is annotated with contextual line information where it occurred in the template. For internal usage this method is preferred over using the render method directly. """ try: return self.render(context) except Exception as e: if context.template.engine.debug: # Store the actual node that caused the exception. if not hasattr(e, "_culprit_node"): e._culprit_node = self if ( not hasattr(e, "template_debug") and context.render_context.template.origin == e._culprit_node.origin ): e.template_debug = ( context.render_context.template.get_exception_info( e, e._culprit_node.token, ) ) raise def get_nodes_by_type(self, nodetype): """ Return a list of all nodes (within this node and its nodelist) of the given type """ nodes = [] if isinstance(self, nodetype): nodes.append(self) for attr in self.child_nodelists: nodelist = getattr(self, attr, None) if nodelist: nodes.extend(nodelist.get_nodes_by_type(nodetype)) return nodes class NodeList(list): # Set to True the first time a non-TextNode is inserted by # extend_nodelist(). contains_nontext = False def render(self, context): return SafeString("".join([node.render_annotated(context) for node in self])) def get_nodes_by_type(self, nodetype): "Return a list of all nodes of the given type" nodes = [] for node in self: nodes.extend(node.get_nodes_by_type(nodetype)) return nodes class TextNode(Node): child_nodelists = () def __init__(self, s): self.s = s def __repr__(self): return "<%s: %r>" % (self.__class__.__name__, self.s[:25]) def render(self, context): return self.s def render_annotated(self, context): """ Return the given value. The default implementation of this method handles exceptions raised during rendering, which is not necessary for text nodes. """ return self.s def render_value_in_context(value, context): """ Convert any value to a string to become part of a rendered template. This means escaping, if required, and conversion to a string. If value is a string, it's expected to already be translated. """ value = template_localtime(value, use_tz=context.use_tz) value = localize(value, use_l10n=context.use_l10n) if context.autoescape: if not issubclass(type(value), str): value = str(value) return conditional_escape(value) else: return str(value) class VariableNode(Node): child_nodelists = () def __init__(self, filter_expression): self.filter_expression = filter_expression def __repr__(self): return "<Variable Node: %s>" % self.filter_expression def render(self, context): try: output = self.filter_expression.resolve(context) except UnicodeDecodeError: # Unicode conversion can fail sometimes for reasons out of our # control (e.g. exception rendering). In that case, we fail # quietly. return "" return render_value_in_context(output, context) # Regex for token keyword arguments kwarg_re = _lazy_re_compile(r"(?:(\w+)=)?(.+)") def token_kwargs(bits, parser, support_legacy=False): """ Parse token keyword arguments and return a dictionary of the arguments retrieved from the ``bits`` token list. `bits` is a list containing the remainder of the token (split by spaces) that is to be checked for arguments. Valid arguments are removed from this list. `support_legacy` - if True, the legacy format ``1 as foo`` is accepted. Otherwise, only the standard ``foo=1`` format is allowed. There is no requirement for all remaining token ``bits`` to be keyword arguments, so return the dictionary as soon as an invalid argument format is reached. """ if not bits: return {} match = kwarg_re.match(bits[0]) kwarg_format = match and match[1] if not kwarg_format: if not support_legacy: return {} if len(bits) < 3 or bits[1] != "as": return {} kwargs = {} while bits: if kwarg_format: match = kwarg_re.match(bits[0]) if not match or not match[1]: return kwargs key, value = match.groups() del bits[:1] else: if len(bits) < 3 or bits[1] != "as": return kwargs key, value = bits[2], bits[0] del bits[:3] kwargs[key] = parser.compile_filter(value) if bits and not kwarg_format: if bits[0] != "and": return kwargs del bits[:1] return kwargs
0413fd254ef6c2b4732074851eacd27e2df2f40d5cef484032ec92f859bdec1d
from functools import wraps from importlib import import_module from inspect import getfullargspec, unwrap from django.utils.html import conditional_escape from django.utils.itercompat import is_iterable from .base import Node, Template, token_kwargs from .exceptions import TemplateSyntaxError class InvalidTemplateLibrary(Exception): pass class Library: """ A class for registering template tags and filters. Compiled filter and template tag functions are stored in the filters and tags attributes. The filter, simple_tag, and inclusion_tag methods provide a convenient way to register callables as tags. """ def __init__(self): self.filters = {} self.tags = {} def tag(self, name=None, compile_function=None): if name is None and compile_function is None: # @register.tag() return self.tag_function elif name is not None and compile_function is None: if callable(name): # @register.tag return self.tag_function(name) else: # @register.tag('somename') or @register.tag(name='somename') def dec(func): return self.tag(name, func) return dec elif name is not None and compile_function is not None: # register.tag('somename', somefunc) self.tags[name] = compile_function return compile_function else: raise ValueError( "Unsupported arguments to Library.tag: (%r, %r)" % (name, compile_function), ) def tag_function(self, func): self.tags[func.__name__] = func return func def filter(self, name=None, filter_func=None, **flags): """ Register a callable as a template filter. Example: @register.filter def lower(value): return value.lower() """ if name is None and filter_func is None: # @register.filter() def dec(func): return self.filter_function(func, **flags) return dec elif name is not None and filter_func is None: if callable(name): # @register.filter return self.filter_function(name, **flags) else: # @register.filter('somename') or @register.filter(name='somename') def dec(func): return self.filter(name, func, **flags) return dec elif name is not None and filter_func is not None: # register.filter('somename', somefunc) self.filters[name] = filter_func for attr in ("expects_localtime", "is_safe", "needs_autoescape"): if attr in flags: value = flags[attr] # set the flag on the filter for FilterExpression.resolve setattr(filter_func, attr, value) # set the flag on the innermost decorated function # for decorators that need it, e.g. stringfilter setattr(unwrap(filter_func), attr, value) filter_func._filter_name = name return filter_func else: raise ValueError( "Unsupported arguments to Library.filter: (%r, %r)" % (name, filter_func), ) def filter_function(self, func, **flags): return self.filter(func.__name__, func, **flags) def simple_tag(self, func=None, takes_context=None, name=None): """ Register a callable as a compiled template tag. Example: @register.simple_tag def hello(*args, **kwargs): return 'world' """ def dec(func): ( params, varargs, varkw, defaults, kwonly, kwonly_defaults, _, ) = getfullargspec(unwrap(func)) function_name = name or func.__name__ @wraps(func) def compile_func(parser, token): bits = token.split_contents()[1:] target_var = None if len(bits) >= 2 and bits[-2] == "as": target_var = bits[-1] bits = bits[:-2] args, kwargs = parse_bits( parser, bits, params, varargs, varkw, defaults, kwonly, kwonly_defaults, takes_context, function_name, ) return SimpleNode(func, takes_context, args, kwargs, target_var) self.tag(function_name, compile_func) return func if func is None: # @register.simple_tag(...) return dec elif callable(func): # @register.simple_tag return dec(func) else: raise ValueError("Invalid arguments provided to simple_tag") def inclusion_tag(self, filename, func=None, takes_context=None, name=None): """ Register a callable as an inclusion tag: @register.inclusion_tag('results.html') def show_results(poll): choices = poll.choice_set.all() return {'choices': choices} """ def dec(func): ( params, varargs, varkw, defaults, kwonly, kwonly_defaults, _, ) = getfullargspec(unwrap(func)) function_name = name or func.__name__ @wraps(func) def compile_func(parser, token): bits = token.split_contents()[1:] args, kwargs = parse_bits( parser, bits, params, varargs, varkw, defaults, kwonly, kwonly_defaults, takes_context, function_name, ) return InclusionNode( func, takes_context, args, kwargs, filename, ) self.tag(function_name, compile_func) return func return dec class TagHelperNode(Node): """ Base class for tag helper nodes such as SimpleNode and InclusionNode. Manages the positional and keyword arguments to be passed to the decorated function. """ def __init__(self, func, takes_context, args, kwargs): self.func = func self.takes_context = takes_context self.args = args self.kwargs = kwargs def get_resolved_arguments(self, context): resolved_args = [var.resolve(context) for var in self.args] if self.takes_context: resolved_args = [context] + resolved_args resolved_kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()} return resolved_args, resolved_kwargs class SimpleNode(TagHelperNode): child_nodelists = () def __init__(self, func, takes_context, args, kwargs, target_var): super().__init__(func, takes_context, args, kwargs) self.target_var = target_var def render(self, context): resolved_args, resolved_kwargs = self.get_resolved_arguments(context) output = self.func(*resolved_args, **resolved_kwargs) if self.target_var is not None: context[self.target_var] = output return "" if context.autoescape: output = conditional_escape(output) return output class InclusionNode(TagHelperNode): def __init__(self, func, takes_context, args, kwargs, filename): super().__init__(func, takes_context, args, kwargs) self.filename = filename def render(self, context): """ Render the specified template and context. Cache the template object in render_context to avoid reparsing and loading when used in a for loop. """ resolved_args, resolved_kwargs = self.get_resolved_arguments(context) _dict = self.func(*resolved_args, **resolved_kwargs) t = context.render_context.get(self) if t is None: if isinstance(self.filename, Template): t = self.filename elif isinstance(getattr(self.filename, "template", None), Template): t = self.filename.template elif not isinstance(self.filename, str) and is_iterable(self.filename): t = context.template.engine.select_template(self.filename) else: t = context.template.engine.get_template(self.filename) context.render_context[self] = t new_context = context.new(_dict) # Copy across the CSRF token, if present, because inclusion tags are # often used for forms, and we need instructions for using CSRF # protection to be as simple as possible. csrf_token = context.get("csrf_token") if csrf_token is not None: new_context["csrf_token"] = csrf_token return t.render(new_context) def parse_bits( parser, bits, params, varargs, varkw, defaults, kwonly, kwonly_defaults, takes_context, name, ): """ Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments. """ if takes_context: if params and params[0] == "context": params = params[1:] else: raise TemplateSyntaxError( "'%s' is decorated with takes_context=True so it must " "have a first argument of 'context'" % name ) args = [] kwargs = {} unhandled_params = list(params) unhandled_kwargs = [ kwarg for kwarg in kwonly if not kwonly_defaults or kwarg not in kwonly_defaults ] for bit in bits: # First we try to extract a potential kwarg from the bit kwarg = token_kwargs([bit], parser) if kwarg: # The kwarg was successfully extracted param, value = kwarg.popitem() if param not in params and param not in kwonly and varkw is None: # An unexpected keyword argument was supplied raise TemplateSyntaxError( "'%s' received unexpected keyword argument '%s'" % (name, param) ) elif param in kwargs: # The keyword argument has already been supplied once raise TemplateSyntaxError( "'%s' received multiple values for keyword argument '%s'" % (name, param) ) else: # All good, record the keyword argument kwargs[str(param)] = value if param in unhandled_params: # If using the keyword syntax for a positional arg, then # consume it. unhandled_params.remove(param) elif param in unhandled_kwargs: # Same for keyword-only arguments unhandled_kwargs.remove(param) else: if kwargs: raise TemplateSyntaxError( "'%s' received some positional argument(s) after some " "keyword argument(s)" % name ) else: # Record the positional argument args.append(parser.compile_filter(bit)) try: # Consume from the list of expected positional arguments unhandled_params.pop(0) except IndexError: if varargs is None: raise TemplateSyntaxError( "'%s' received too many positional arguments" % name ) if defaults is not None: # Consider the last n params handled, where n is the # number of defaults. unhandled_params = unhandled_params[: -len(defaults)] if unhandled_params or unhandled_kwargs: # Some positional arguments were not supplied raise TemplateSyntaxError( "'%s' did not receive value(s) for the argument(s): %s" % (name, ", ".join("'%s'" % p for p in unhandled_params + unhandled_kwargs)) ) return args, kwargs def import_library(name): """ Load a Library object from a template tag module. """ try: module = import_module(name) except ImportError as e: raise InvalidTemplateLibrary( "Invalid template library specified. ImportError raised when " "trying to load '%s': %s" % (name, e) ) try: return module.register except AttributeError: raise InvalidTemplateLibrary( "Module %s does not have a variable named 'register'" % name, )
89a19432decfa5b24ecf2969a84bb6c7b9dac71ee94d323f0f21830ed9a2029e
""" This module converts requested URLs to callback view functions. URLResolver is the main class here. Its resolve() method takes a URL (as a string) and returns a ResolverMatch object which provides access to all attributes of the resolved URL match. """ import functools import inspect import re import string from importlib import import_module from pickle import PicklingError from urllib.parse import quote from asgiref.local import Local from django.conf import settings from django.core.checks import Error, Warning from django.core.checks.urls import check_resolver from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.utils.datastructures import MultiValueDict from django.utils.functional import cached_property from django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes from django.utils.regex_helper import _lazy_re_compile, normalize from django.utils.translation import get_language from .converters import get_converter from .exceptions import NoReverseMatch, Resolver404 from .utils import get_callable class ResolverMatch: def __init__( self, func, args, kwargs, url_name=None, app_names=None, namespaces=None, route=None, tried=None, captured_kwargs=None, extra_kwargs=None, ): self.func = func self.args = args self.kwargs = kwargs self.url_name = url_name self.route = route self.tried = tried self.captured_kwargs = captured_kwargs self.extra_kwargs = extra_kwargs # If a URLRegexResolver doesn't have a namespace or app_name, it passes # in an empty value. self.app_names = [x for x in app_names if x] if app_names else [] self.app_name = ":".join(self.app_names) self.namespaces = [x for x in namespaces if x] if namespaces else [] self.namespace = ":".join(self.namespaces) if hasattr(func, "view_class"): func = func.view_class if not hasattr(func, "__name__"): # A class-based view self._func_path = func.__class__.__module__ + "." + func.__class__.__name__ else: # A function-based view self._func_path = func.__module__ + "." + func.__name__ view_path = url_name or self._func_path self.view_name = ":".join(self.namespaces + [view_path]) def __getitem__(self, index): return (self.func, self.args, self.kwargs)[index] def __repr__(self): if isinstance(self.func, functools.partial): func = repr(self.func) else: func = self._func_path return ( "ResolverMatch(func=%s, args=%r, kwargs=%r, url_name=%r, " "app_names=%r, namespaces=%r, route=%r%s%s)" % ( func, self.args, self.kwargs, self.url_name, self.app_names, self.namespaces, self.route, f", captured_kwargs={self.captured_kwargs!r}" if self.captured_kwargs else "", f", extra_kwargs={self.extra_kwargs!r}" if self.extra_kwargs else "", ) ) def __reduce_ex__(self, protocol): raise PicklingError(f"Cannot pickle {self.__class__.__qualname__}.") def get_resolver(urlconf=None): if urlconf is None: urlconf = settings.ROOT_URLCONF return _get_cached_resolver(urlconf) @functools.lru_cache(maxsize=None) def _get_cached_resolver(urlconf=None): return URLResolver(RegexPattern(r"^/"), urlconf) @functools.lru_cache(maxsize=None) def get_ns_resolver(ns_pattern, resolver, converters): # Build a namespaced resolver for the given parent URLconf pattern. # This makes it possible to have captured parameters in the parent # URLconf pattern. pattern = RegexPattern(ns_pattern) pattern.converters = dict(converters) ns_resolver = URLResolver(pattern, resolver.url_patterns) return URLResolver(RegexPattern(r"^/"), [ns_resolver]) class LocaleRegexDescriptor: def __init__(self, attr): self.attr = attr def __get__(self, instance, cls=None): """ Return a compiled regular expression based on the active language. """ if instance is None: return self # As a performance optimization, if the given regex string is a regular # string (not a lazily-translated string proxy), compile it once and # avoid per-language compilation. pattern = getattr(instance, self.attr) if isinstance(pattern, str): instance.__dict__["regex"] = instance._compile(pattern) return instance.__dict__["regex"] language_code = get_language() if language_code not in instance._regex_dict: instance._regex_dict[language_code] = instance._compile(str(pattern)) return instance._regex_dict[language_code] class CheckURLMixin: def describe(self): """ Format the URL pattern for display in warning messages. """ description = "'{}'".format(self) if self.name: description += " [name='{}']".format(self.name) return description def _check_pattern_startswith_slash(self): """ Check that the pattern does not begin with a forward slash. """ regex_pattern = self.regex.pattern if not settings.APPEND_SLASH: # Skip check as it can be useful to start a URL pattern with a slash # when APPEND_SLASH=False. return [] if regex_pattern.startswith(("/", "^/", "^\\/")) and not regex_pattern.endswith( "/" ): warning = Warning( "Your URL pattern {} 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 '/'.".format( self.describe() ), id="urls.W002", ) return [warning] else: return [] class RegexPattern(CheckURLMixin): regex = LocaleRegexDescriptor("_regex") def __init__(self, regex, name=None, is_endpoint=False): self._regex = regex self._regex_dict = {} self._is_endpoint = is_endpoint self.name = name self.converters = {} def match(self, path): match = ( self.regex.fullmatch(path) if self._is_endpoint and self.regex.pattern.endswith("$") else self.regex.search(path) ) if match: # If there are any named groups, use those as kwargs, ignoring # non-named groups. Otherwise, pass all non-named arguments as # positional arguments. kwargs = match.groupdict() args = () if kwargs else match.groups() kwargs = {k: v for k, v in kwargs.items() if v is not None} return path[match.end() :], args, kwargs return None def check(self): warnings = [] warnings.extend(self._check_pattern_startswith_slash()) if not self._is_endpoint: warnings.extend(self._check_include_trailing_dollar()) return warnings def _check_include_trailing_dollar(self): regex_pattern = self.regex.pattern if regex_pattern.endswith("$") and not regex_pattern.endswith(r"\$"): return [ Warning( "Your URL pattern {} uses include with a route ending with a '$'. " "Remove the dollar from the route to avoid problems including " "URLs.".format(self.describe()), id="urls.W001", ) ] else: return [] def _compile(self, regex): """Compile and return the given regular expression.""" try: return re.compile(regex) except re.error as e: raise ImproperlyConfigured( '"%s" is not a valid regular expression: %s' % (regex, e) ) from e def __str__(self): return str(self._regex) _PATH_PARAMETER_COMPONENT_RE = _lazy_re_compile( r"<(?:(?P<converter>[^>:]+):)?(?P<parameter>[^>]+)>" ) def _route_to_regex(route, is_endpoint=False): """ Convert a path pattern into a regular expression. Return the regular expression and a dictionary mapping the capture names to the converters. For example, 'foo/<int:pk>' returns '^foo\\/(?P<pk>[0-9]+)' and {'pk': <django.urls.converters.IntConverter>}. """ original_route = route parts = ["^"] converters = {} while True: match = _PATH_PARAMETER_COMPONENT_RE.search(route) if not match: parts.append(re.escape(route)) break elif not set(match.group()).isdisjoint(string.whitespace): raise ImproperlyConfigured( "URL route '%s' cannot contain whitespace in angle brackets " "<…>." % original_route ) parts.append(re.escape(route[: match.start()])) route = route[match.end() :] parameter = match["parameter"] if not parameter.isidentifier(): raise ImproperlyConfigured( "URL route '%s' uses parameter name %r which isn't a valid " "Python identifier." % (original_route, parameter) ) raw_converter = match["converter"] if raw_converter is None: # If a converter isn't specified, the default is `str`. raw_converter = "str" try: converter = get_converter(raw_converter) except KeyError as e: raise ImproperlyConfigured( "URL route %r uses invalid converter %r." % (original_route, raw_converter) ) from e converters[parameter] = converter parts.append("(?P<" + parameter + ">" + converter.regex + ")") if is_endpoint: parts.append(r"\Z") return "".join(parts), converters class RoutePattern(CheckURLMixin): regex = LocaleRegexDescriptor("_route") def __init__(self, route, name=None, is_endpoint=False): self._route = route self._regex_dict = {} self._is_endpoint = is_endpoint self.name = name self.converters = _route_to_regex(str(route), is_endpoint)[1] def match(self, path): match = self.regex.search(path) if match: # RoutePattern doesn't allow non-named groups so args are ignored. kwargs = match.groupdict() for key, value in kwargs.items(): converter = self.converters[key] try: kwargs[key] = converter.to_python(value) except ValueError: return None return path[match.end() :], (), kwargs return None def check(self): warnings = self._check_pattern_startswith_slash() route = self._route if "(?P<" in route or route.startswith("^") or route.endswith("$"): warnings.append( Warning( "Your URL pattern {} has a route that contains '(?P<', begins " "with a '^', or ends with a '$'. This was likely an oversight " "when migrating to django.urls.path().".format(self.describe()), id="2_0.W001", ) ) return warnings def _compile(self, route): return re.compile(_route_to_regex(route, self._is_endpoint)[0]) def __str__(self): return str(self._route) class LocalePrefixPattern: def __init__(self, prefix_default_language=True): self.prefix_default_language = prefix_default_language self.converters = {} @property def regex(self): # This is only used by reverse() and cached in _reverse_dict. return re.compile(self.language_prefix) @property def language_prefix(self): language_code = get_language() or settings.LANGUAGE_CODE if language_code == settings.LANGUAGE_CODE and not self.prefix_default_language: return "" else: return "%s/" % language_code def match(self, path): language_prefix = self.language_prefix if path.startswith(language_prefix): return path[len(language_prefix) :], (), {} return None def check(self): return [] def describe(self): return "'{}'".format(self) def __str__(self): return self.language_prefix class URLPattern: def __init__(self, pattern, callback, default_args=None, name=None): self.pattern = pattern self.callback = callback # the view self.default_args = default_args or {} self.name = name def __repr__(self): return "<%s %s>" % (self.__class__.__name__, self.pattern.describe()) def check(self): warnings = self._check_pattern_name() warnings.extend(self.pattern.check()) warnings.extend(self._check_callback()) return warnings def _check_pattern_name(self): """ Check that the pattern name does not contain a colon. """ if self.pattern.name is not None and ":" in self.pattern.name: warning = Warning( "Your URL pattern {} has a name including a ':'. Remove the colon, to " "avoid ambiguous namespace references.".format(self.pattern.describe()), id="urls.W003", ) return [warning] else: return [] def _check_callback(self): from django.views import View view = self.callback if inspect.isclass(view) and issubclass(view, View): return [ Error( "Your URL pattern %s has an invalid view, pass %s.as_view() " "instead of %s." % ( self.pattern.describe(), view.__name__, view.__name__, ), id="urls.E009", ) ] return [] def resolve(self, path): match = self.pattern.match(path) if match: new_path, args, captured_kwargs = match # Pass any default args as **kwargs. kwargs = {**captured_kwargs, **self.default_args} return ResolverMatch( self.callback, args, kwargs, self.pattern.name, route=str(self.pattern), captured_kwargs=captured_kwargs, extra_kwargs=self.default_args, ) class URLResolver: def __init__( self, pattern, urlconf_name, default_kwargs=None, app_name=None, namespace=None ): self.pattern = pattern # urlconf_name is the dotted Python path to the module defining # urlpatterns. It may also be an object with an urlpatterns attribute # or urlpatterns itself. self.urlconf_name = urlconf_name self.callback = None self.default_kwargs = default_kwargs or {} self.namespace = namespace self.app_name = app_name self._reverse_dict = {} self._namespace_dict = {} self._app_dict = {} self._populated = False self._local = Local() def __repr__(self): if isinstance(self.urlconf_name, list) and self.urlconf_name: # Don't bother to output the whole list, it can be huge urlconf_repr = "<%s list>" % self.urlconf_name[0].__class__.__name__ else: urlconf_repr = repr(self.urlconf_name) return "<%s %s (%s:%s) %s>" % ( self.__class__.__name__, urlconf_repr, self.app_name, self.namespace, self.pattern.describe(), ) def check(self): messages = [] for pattern in self.url_patterns: messages.extend(check_resolver(pattern)) messages.extend(self._check_custom_error_handlers()) return messages or self.pattern.check() def _check_custom_error_handlers(self): messages = [] # All handlers take (request, exception) arguments except handler500 # which takes (request). for status_code, num_parameters in [(400, 2), (403, 2), (404, 2), (500, 1)]: try: handler = self.resolve_error_handler(status_code) except (ImportError, ViewDoesNotExist) as e: path = getattr(self.urlconf_module, "handler%s" % status_code) msg = ( "The custom handler{status_code} view '{path}' could not be " "imported." ).format(status_code=status_code, path=path) messages.append(Error(msg, hint=str(e), id="urls.E008")) continue signature = inspect.signature(handler) args = [None] * num_parameters try: signature.bind(*args) except TypeError: msg = ( "The custom handler{status_code} view '{path}' does not " "take the correct number of arguments ({args})." ).format( status_code=status_code, path=handler.__module__ + "." + handler.__qualname__, args="request, exception" if num_parameters == 2 else "request", ) messages.append(Error(msg, id="urls.E007")) return messages def _populate(self): # Short-circuit if called recursively in this thread to prevent # infinite recursion. Concurrent threads may call this at the same # time and will need to continue, so set 'populating' on a # thread-local variable. if getattr(self._local, "populating", False): return try: self._local.populating = True lookups = MultiValueDict() namespaces = {} apps = {} language_code = get_language() for url_pattern in reversed(self.url_patterns): p_pattern = url_pattern.pattern.regex.pattern if p_pattern.startswith("^"): p_pattern = p_pattern[1:] if isinstance(url_pattern, URLPattern): bits = normalize(url_pattern.pattern.regex.pattern) lookups.appendlist( url_pattern.callback, ( bits, p_pattern, url_pattern.default_args, url_pattern.pattern.converters, ), ) if url_pattern.name is not None: lookups.appendlist( url_pattern.name, ( bits, p_pattern, url_pattern.default_args, url_pattern.pattern.converters, ), ) else: # url_pattern is a URLResolver. url_pattern._populate() if url_pattern.app_name: apps.setdefault(url_pattern.app_name, []).append( url_pattern.namespace ) namespaces[url_pattern.namespace] = (p_pattern, url_pattern) else: for name in url_pattern.reverse_dict: for ( matches, pat, defaults, converters, ) in url_pattern.reverse_dict.getlist(name): new_matches = normalize(p_pattern + pat) lookups.appendlist( name, ( new_matches, p_pattern + pat, {**defaults, **url_pattern.default_kwargs}, { **self.pattern.converters, **url_pattern.pattern.converters, **converters, }, ), ) for namespace, ( prefix, sub_pattern, ) in url_pattern.namespace_dict.items(): current_converters = url_pattern.pattern.converters sub_pattern.pattern.converters.update(current_converters) namespaces[namespace] = (p_pattern + prefix, sub_pattern) for app_name, namespace_list in url_pattern.app_dict.items(): apps.setdefault(app_name, []).extend(namespace_list) self._namespace_dict[language_code] = namespaces self._app_dict[language_code] = apps self._reverse_dict[language_code] = lookups self._populated = True finally: self._local.populating = False @property def reverse_dict(self): language_code = get_language() if language_code not in self._reverse_dict: self._populate() return self._reverse_dict[language_code] @property def namespace_dict(self): language_code = get_language() if language_code not in self._namespace_dict: self._populate() return self._namespace_dict[language_code] @property def app_dict(self): language_code = get_language() if language_code not in self._app_dict: self._populate() return self._app_dict[language_code] @staticmethod def _extend_tried(tried, pattern, sub_tried=None): if sub_tried is None: tried.append([pattern]) else: tried.extend([pattern, *t] for t in sub_tried) @staticmethod def _join_route(route1, route2): """Join two routes, without the starting ^ in the second route.""" if not route1: return route2 if route2.startswith("^"): route2 = route2[1:] return route1 + route2 def resolve(self, path): path = str(path) # path may be a reverse_lazy object tried = [] match = self.pattern.match(path) if match: new_path, args, kwargs = match for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) except Resolver404 as e: self._extend_tried(tried, pattern, e.args[0].get("tried")) else: if sub_match: # Merge captured arguments in match with submatch sub_match_dict = {**kwargs, **self.default_kwargs} # Update the sub_match_dict with the kwargs from the sub_match. sub_match_dict.update(sub_match.kwargs) # If there are *any* named groups, ignore all non-named groups. # Otherwise, pass all non-named arguments as positional # arguments. sub_match_args = sub_match.args if not sub_match_dict: sub_match_args = args + sub_match.args current_route = ( "" if isinstance(pattern, URLPattern) else str(pattern.pattern) ) self._extend_tried(tried, pattern, sub_match.tried) return ResolverMatch( sub_match.func, sub_match_args, sub_match_dict, sub_match.url_name, [self.app_name] + sub_match.app_names, [self.namespace] + sub_match.namespaces, self._join_route(current_route, sub_match.route), tried, captured_kwargs=sub_match.captured_kwargs, extra_kwargs={ **self.default_kwargs, **sub_match.extra_kwargs, }, ) tried.append([pattern]) raise Resolver404({"tried": tried, "path": new_path}) raise Resolver404({"path": path}) @cached_property def urlconf_module(self): if isinstance(self.urlconf_name, str): return import_module(self.urlconf_name) else: return self.urlconf_name @cached_property def url_patterns(self): # urlconf_module might be a valid set of patterns, so we default to it patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) try: iter(patterns) except TypeError as e: msg = ( "The included URLconf '{name}' does not appear to have " "any patterns in it. If you see the 'urlpatterns' variable " "with valid patterns in the file then the issue is probably " "caused by a circular import." ) raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e return patterns def resolve_error_handler(self, view_type): callback = getattr(self.urlconf_module, "handler%s" % view_type, None) if not callback: # No handler specified in file; use lazy import, since # django.conf.urls imports this file. from django.conf import urls callback = getattr(urls, "handler%s" % view_type) return get_callable(callback) def reverse(self, lookup_view, *args, **kwargs): return self._reverse_with_prefix(lookup_view, "", *args, **kwargs) def _reverse_with_prefix(self, lookup_view, _prefix, *args, **kwargs): if args and kwargs: raise ValueError("Don't mix *args and **kwargs in call to reverse()!") if not self._populated: self._populate() possibilities = self.reverse_dict.getlist(lookup_view) for possibility, pattern, defaults, converters in possibilities: for result, params in possibility: if args: if len(args) != len(params): continue candidate_subs = dict(zip(params, args)) else: if set(kwargs).symmetric_difference(params).difference(defaults): continue matches = True for k, v in defaults.items(): if k in params: continue if kwargs.get(k, v) != v: matches = False break if not matches: continue candidate_subs = kwargs # Convert the candidate subs to text using Converter.to_url(). text_candidate_subs = {} match = True for k, v in candidate_subs.items(): if k in converters: try: text_candidate_subs[k] = converters[k].to_url(v) except ValueError: match = False break else: text_candidate_subs[k] = str(v) if not match: continue # WSGI provides decoded URLs, without %xx escapes, and the URL # resolver operates on such URLs. First substitute arguments # without quoting to build a decoded URL and look for a match. # Then, if we have a match, redo the substitution with quoted # arguments in order to return a properly encoded URL. candidate_pat = _prefix.replace("%", "%%") + result if re.search( "^%s%s" % (re.escape(_prefix), pattern), candidate_pat % text_candidate_subs, ): # safe characters from `pchar` definition of RFC 3986 url = quote( candidate_pat % text_candidate_subs, safe=RFC3986_SUBDELIMS + "/~:@", ) # Don't allow construction of scheme relative urls. return escape_leading_slashes(url) # lookup_view can be URL name or callable, but callables are not # friendly in error messages. m = getattr(lookup_view, "__module__", None) n = getattr(lookup_view, "__name__", None) if m is not None and n is not None: lookup_view_s = "%s.%s" % (m, n) else: lookup_view_s = lookup_view patterns = [pattern for (_, pattern, _, _) in possibilities] if patterns: if args: arg_msg = "arguments '%s'" % (args,) elif kwargs: arg_msg = "keyword arguments '%s'" % kwargs else: arg_msg = "no arguments" msg = "Reverse for '%s' with %s not found. %d pattern(s) tried: %s" % ( lookup_view_s, arg_msg, len(patterns), patterns, ) else: msg = ( "Reverse for '%(view)s' not found. '%(view)s' is not " "a valid view function or pattern name." % {"view": lookup_view_s} ) raise NoReverseMatch(msg)
704d181a1365980adda50e9b4bf3b115170f94a352900c0ad6941fc3aeb1deb8
import json import warnings from collections import UserList from django.conf import settings from django.core.exceptions import ValidationError from django.forms.renderers import get_default_renderer from django.utils import timezone from django.utils.deprecation import RemovedInDjango50Warning from django.utils.html import escape, format_html_join from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from django.utils.version import get_docs_version def pretty_name(name): """Convert 'first_name' to 'First name'.""" if not name: return "" return name.replace("_", " ").capitalize() def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. The result is passed through 'mark_safe' (by way of 'format_html_join'). """ key_value_attrs = [] boolean_attrs = [] for attr, value in attrs.items(): if isinstance(value, bool): if value: boolean_attrs.append((attr,)) elif value is not None: key_value_attrs.append((attr, value)) return format_html_join("", ' {}="{}"', sorted(key_value_attrs)) + format_html_join( "", " {}", sorted(boolean_attrs) ) DEFAULT_TEMPLATE_DEPRECATION_MSG = ( 'The "default.html" templates for forms and formsets will be removed. These were ' 'proxies to the equivalent "table.html" templates, but the new "div.html" ' "templates will be the default from Django 5.0. Transitional renderers are " "provided to allow you to opt-in to the new output style now. See " "https://docs.djangoproject.com/en/%s/releases/4.1/ for more details" % get_docs_version() ) class RenderableMixin: def get_context(self): raise NotImplementedError( "Subclasses of RenderableMixin must provide a get_context() method." ) def render(self, template_name=None, context=None, renderer=None): renderer = renderer or self.renderer template = template_name or self.template_name context = context or self.get_context() if ( template == "django/forms/default.html" or template == "django/forms/formsets/default.html" ): warnings.warn( DEFAULT_TEMPLATE_DEPRECATION_MSG, RemovedInDjango50Warning, stacklevel=2 ) return mark_safe(renderer.render(template, context)) __str__ = render __html__ = render class RenderableFormMixin(RenderableMixin): def as_p(self): """Render as <p> elements.""" return self.render(self.template_name_p) def as_table(self): """Render as <tr> elements excluding the surrounding <table> tag.""" return self.render(self.template_name_table) def as_ul(self): """Render as <li> elements excluding the surrounding <ul> tag.""" return self.render(self.template_name_ul) def as_div(self): """Render as <div> elements.""" return self.render(self.template_name_div) class RenderableErrorMixin(RenderableMixin): def as_json(self, escape_html=False): return json.dumps(self.get_json_data(escape_html)) def as_text(self): return self.render(self.template_name_text) def as_ul(self): return self.render(self.template_name_ul) class ErrorDict(dict, RenderableErrorMixin): """ A collection of errors that knows how to display itself in various formats. The dictionary keys are the field names, and the values are the errors. """ template_name = "django/forms/errors/dict/default.html" template_name_text = "django/forms/errors/dict/text.txt" template_name_ul = "django/forms/errors/dict/ul.html" def __init__(self, *args, renderer=None, **kwargs): super().__init__(*args, **kwargs) self.renderer = renderer or get_default_renderer() def as_data(self): return {f: e.as_data() for f, e in self.items()} def get_json_data(self, escape_html=False): return {f: e.get_json_data(escape_html) for f, e in self.items()} def get_context(self): return { "errors": self.items(), "error_class": "errorlist", } class ErrorList(UserList, list, RenderableErrorMixin): """ A collection of errors that knows how to display itself in various formats. """ template_name = "django/forms/errors/list/default.html" template_name_text = "django/forms/errors/list/text.txt" template_name_ul = "django/forms/errors/list/ul.html" def __init__(self, initlist=None, error_class=None, renderer=None): super().__init__(initlist) if error_class is None: self.error_class = "errorlist" else: self.error_class = "errorlist {}".format(error_class) self.renderer = renderer or get_default_renderer() def as_data(self): return ValidationError(self.data).error_list def copy(self): copy = super().copy() copy.error_class = self.error_class return copy def get_json_data(self, escape_html=False): errors = [] for error in self.as_data(): message = next(iter(error)) errors.append( { "message": escape(message) if escape_html else message, "code": error.code or "", } ) return errors def get_context(self): return { "errors": self, "error_class": self.error_class, } def __repr__(self): return repr(list(self)) def __contains__(self, item): return item in list(self) def __eq__(self, other): return list(self) == other def __getitem__(self, i): error = self.data[i] if isinstance(error, ValidationError): return next(iter(error)) return error def __reduce_ex__(self, *args, **kwargs): # The `list` reduce function returns an iterator as the fourth element # that is normally used for repopulating. Since we only inherit from # `list` for `isinstance` backward compatibility (Refs #17413) we # nullify this iterator as it would otherwise result in duplicate # entries. (Refs #23594) info = super(UserList, self).__reduce_ex__(*args, **kwargs) return info[:3] + (None, None) # Utilities for time zone support in DateTimeField et al. def from_current_timezone(value): """ When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes. """ if settings.USE_TZ and value is not None and timezone.is_naive(value): current_timezone = timezone.get_current_timezone() try: if not timezone._is_pytz_zone( current_timezone ) and timezone._datetime_ambiguous_or_imaginary(value, current_timezone): raise ValueError("Ambiguous or non-existent time.") return timezone.make_aware(value, current_timezone) except Exception as exc: raise ValidationError( _( "%(datetime)s couldn’t be interpreted " "in time zone %(current_timezone)s; it " "may be ambiguous or it may not exist." ), code="ambiguous_timezone", params={"datetime": value, "current_timezone": current_timezone}, ) from exc return value def to_current_timezone(value): """ When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display. """ if settings.USE_TZ and value is not None and timezone.is_aware(value): return timezone.make_naive(value) return value
ec6d4cc5391787e318a17720d7605a9bfb6e914771fcc65f91092bf855eaf1f2
import functools from pathlib import Path from django.conf import settings from django.template.backends.django import DjangoTemplates from django.template.loader import get_template from django.utils.functional import cached_property from django.utils.module_loading import import_string @functools.lru_cache def get_default_renderer(): renderer_class = import_string(settings.FORM_RENDERER) return renderer_class() class BaseRenderer: # RemovedInDjango50Warning: When the deprecation ends, replace with # form_template_name = "django/forms/div.html" # formset_template_name = "django/forms/formsets/div.html" form_template_name = "django/forms/default.html" formset_template_name = "django/forms/formsets/default.html" def get_template(self, template_name): raise NotImplementedError("subclasses must implement get_template()") def render(self, template_name, context, request=None): template = self.get_template(template_name) return template.render(context, request=request).strip() class EngineMixin: def get_template(self, template_name): return self.engine.get_template(template_name) @cached_property def engine(self): return self.backend( { "APP_DIRS": True, "DIRS": [Path(__file__).parent / self.backend.app_dirname], "NAME": "djangoforms", "OPTIONS": {}, } ) class DjangoTemplates(EngineMixin, BaseRenderer): """ Load Django templates from the built-in widget templates in django/forms/templates and from apps' 'templates' directory. """ backend = DjangoTemplates class Jinja2(EngineMixin, BaseRenderer): """ Load Jinja2 templates from the built-in widget templates in django/forms/jinja2 and from apps' 'jinja2' directory. """ @cached_property def backend(self): from django.template.backends.jinja2 import Jinja2 return Jinja2 class DjangoDivFormRenderer(DjangoTemplates): """ Load Django templates from django/forms/templates and from apps' 'templates' directory and use the 'div.html' template to render forms and formsets. """ # RemovedInDjango50Warning Deprecate this class in 5.0 and remove in 6.0. form_template_name = "django/forms/div.html" formset_template_name = "django/forms/formsets/div.html" class Jinja2DivFormRenderer(Jinja2): """ Load Jinja2 templates from the built-in widget templates in django/forms/jinja2 and from apps' 'jinja2' directory. """ # RemovedInDjango50Warning Deprecate this class in 5.0 and remove in 6.0. form_template_name = "django/forms/div.html" formset_template_name = "django/forms/formsets/div.html" class TemplatesSetting(BaseRenderer): """ Load templates using template.loader.get_template() which is configured based on settings.TEMPLATES. """ def get_template(self, template_name): return get_template(template_name)
f71f4fe3e7cabf57581298eae67eda4ad919da60859efd14dd3a219f2d34c833
from django.http.cookie import SimpleCookie, parse_cookie from django.http.request import ( HttpRequest, QueryDict, RawPostDataException, UnreadablePostError, ) from django.http.response import ( BadHeaderError, FileResponse, Http404, HttpResponse, HttpResponseBadRequest, HttpResponseBase, HttpResponseForbidden, HttpResponseGone, HttpResponseNotAllowed, HttpResponseNotFound, HttpResponseNotModified, HttpResponsePermanentRedirect, HttpResponseRedirect, HttpResponseServerError, JsonResponse, StreamingHttpResponse, ) __all__ = [ "SimpleCookie", "parse_cookie", "HttpRequest", "QueryDict", "RawPostDataException", "UnreadablePostError", "HttpResponse", "HttpResponseBase", "StreamingHttpResponse", "HttpResponseRedirect", "HttpResponsePermanentRedirect", "HttpResponseNotModified", "HttpResponseBadRequest", "HttpResponseForbidden", "HttpResponseNotFound", "HttpResponseNotAllowed", "HttpResponseGone", "HttpResponseServerError", "Http404", "BadHeaderError", "JsonResponse", "FileResponse", ]
b616f9559433332bdb52bc66746bdaaab8d9627047a6ebcbc973d9e11fdfc3ce
""" Multi-part parsing for file uploads. Exposes one class, ``MultiPartParser``, which feeds chunks of uploaded data to file upload handlers for processing. """ import base64 import binascii import collections import html from urllib.parse import unquote from django.conf import settings from django.core.exceptions import ( RequestDataTooBig, SuspiciousMultipartForm, TooManyFieldsSent, ) from django.core.files.uploadhandler import SkipFile, StopFutureHandlers, StopUpload from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str from django.utils.regex_helper import _lazy_re_compile __all__ = ("MultiPartParser", "MultiPartParserError", "InputStreamExhausted") class MultiPartParserError(Exception): pass class InputStreamExhausted(Exception): """ No more reads are allowed from this device. """ pass RAW = "raw" FILE = "file" FIELD = "field" class MultiPartParser: """ A rfc2388 multipart/form-data parser. ``MultiValueDict.parse()`` reads the input stream in ``chunk_size`` chunks and returns a tuple of ``(MultiValueDict(POST), MultiValueDict(FILES))``. """ boundary_re = _lazy_re_compile(rb"[ -~]{0,200}[!-~]") def __init__(self, META, input_data, upload_handlers, encoding=None): """ Initialize the MultiPartParser object. :META: The standard ``META`` dictionary in Django request objects. :input_data: The raw post data, as a file-like object. :upload_handlers: A list of UploadHandler instances that perform operations on the uploaded data. :encoding: The encoding with which to treat the incoming data. """ # Content-Type should contain multipart and the boundary information. content_type = META.get("CONTENT_TYPE", "") if not content_type.startswith("multipart/"): raise MultiPartParserError("Invalid Content-Type: %s" % content_type) # Parse the header to get the boundary to split the parts. try: ctypes, opts = parse_header(content_type.encode("ascii")) except UnicodeEncodeError: raise MultiPartParserError( "Invalid non-ASCII Content-Type in multipart: %s" % force_str(content_type) ) boundary = opts.get("boundary") if not boundary or not self.boundary_re.fullmatch(boundary): raise MultiPartParserError( "Invalid boundary in multipart: %s" % force_str(boundary) ) # Content-Length should contain the length of the body we are about # to receive. try: content_length = int(META.get("CONTENT_LENGTH", 0)) except (ValueError, TypeError): content_length = 0 if content_length < 0: # This means we shouldn't continue...raise an error. raise MultiPartParserError("Invalid content length: %r" % content_length) if isinstance(boundary, str): boundary = boundary.encode("ascii") self._boundary = boundary self._input_data = input_data # For compatibility with low-level network APIs (with 32-bit integers), # the chunk size should be < 2^31, but still divisible by 4. possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size] self._chunk_size = min([2**31 - 4] + possible_sizes) self._meta = META self._encoding = encoding or settings.DEFAULT_CHARSET self._content_length = content_length self._upload_handlers = upload_handlers def parse(self): """ Parse the POST data and break it into a FILES MultiValueDict and a POST MultiValueDict. Return a tuple containing the POST and FILES dictionary, respectively. """ from django.http import QueryDict encoding = self._encoding handlers = self._upload_handlers # HTTP spec says that Content-Length >= 0 is valid # handling content-length == 0 before continuing if self._content_length == 0: return QueryDict(encoding=self._encoding), MultiValueDict() # See if any of the handlers take care of the parsing. # This allows overriding everything if need be. for handler in handlers: result = handler.handle_raw_input( self._input_data, self._meta, self._content_length, self._boundary, encoding, ) # Check to see if it was handled if result is not None: return result[0], result[1] # Create the data structures to be used later. self._post = QueryDict(mutable=True) self._files = MultiValueDict() # Instantiate the parser and stream: stream = LazyStream(ChunkIter(self._input_data, self._chunk_size)) # Whether or not to signal a file-completion at the beginning of the loop. old_field_name = None counters = [0] * len(handlers) # Number of bytes that have been read. num_bytes_read = 0 # To count the number of keys in the request. num_post_keys = 0 # To limit the amount of data read from the request. read_size = None # Whether a file upload is finished. uploaded_file = True try: for item_type, meta_data, field_stream in Parser(stream, self._boundary): if old_field_name: # We run this at the beginning of the next loop # since we cannot be sure a file is complete until # we hit the next boundary/part of the multipart content. self.handle_file_complete(old_field_name, counters) old_field_name = None uploaded_file = True try: disposition = meta_data["content-disposition"][1] field_name = disposition["name"].strip() except (KeyError, IndexError, AttributeError): continue transfer_encoding = meta_data.get("content-transfer-encoding") if transfer_encoding is not None: transfer_encoding = transfer_encoding[0].strip() field_name = force_str(field_name, encoding, errors="replace") if item_type == FIELD: # Avoid storing more than DATA_UPLOAD_MAX_NUMBER_FIELDS. num_post_keys += 1 if ( settings.DATA_UPLOAD_MAX_NUMBER_FIELDS is not None and settings.DATA_UPLOAD_MAX_NUMBER_FIELDS < num_post_keys ): raise TooManyFieldsSent( "The number of GET/POST parameters exceeded " "settings.DATA_UPLOAD_MAX_NUMBER_FIELDS." ) # Avoid reading more than DATA_UPLOAD_MAX_MEMORY_SIZE. if settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None: read_size = ( settings.DATA_UPLOAD_MAX_MEMORY_SIZE - num_bytes_read ) # This is a post field, we can just set it in the post if transfer_encoding == "base64": raw_data = field_stream.read(size=read_size) num_bytes_read += len(raw_data) try: data = base64.b64decode(raw_data) except binascii.Error: data = raw_data else: data = field_stream.read(size=read_size) num_bytes_read += len(data) # Add two here to make the check consistent with the # x-www-form-urlencoded check that includes '&='. num_bytes_read += len(field_name) + 2 if ( settings.DATA_UPLOAD_MAX_MEMORY_SIZE is not None and num_bytes_read > settings.DATA_UPLOAD_MAX_MEMORY_SIZE ): raise RequestDataTooBig( "Request body exceeded " "settings.DATA_UPLOAD_MAX_MEMORY_SIZE." ) self._post.appendlist( field_name, force_str(data, encoding, errors="replace") ) elif item_type == FILE: # This is a file, use the handler... file_name = disposition.get("filename") if file_name: file_name = force_str(file_name, encoding, errors="replace") file_name = self.sanitize_file_name(file_name) if not file_name: continue content_type, content_type_extra = meta_data.get( "content-type", ("", {}) ) content_type = content_type.strip() charset = content_type_extra.get("charset") try: content_length = int(meta_data.get("content-length")[0]) except (IndexError, TypeError, ValueError): content_length = None counters = [0] * len(handlers) uploaded_file = False try: for handler in handlers: try: handler.new_file( field_name, file_name, content_type, content_length, charset, content_type_extra, ) except StopFutureHandlers: break for chunk in field_stream: if transfer_encoding == "base64": # We only special-case base64 transfer encoding # We should always decode base64 chunks by # multiple of 4, ignoring whitespace. stripped_chunk = b"".join(chunk.split()) remaining = len(stripped_chunk) % 4 while remaining != 0: over_chunk = field_stream.read(4 - remaining) if not over_chunk: break stripped_chunk += b"".join(over_chunk.split()) remaining = len(stripped_chunk) % 4 try: chunk = base64.b64decode(stripped_chunk) except Exception as exc: # Since this is only a chunk, any error is # an unfixable error. raise MultiPartParserError( "Could not decode base64 data." ) from exc for i, handler in enumerate(handlers): chunk_length = len(chunk) chunk = handler.receive_data_chunk(chunk, counters[i]) counters[i] += chunk_length if chunk is None: # Don't continue if the chunk received by # the handler is None. break except SkipFile: self._close_files() # Just use up the rest of this file... exhaust(field_stream) else: # Handle file upload completions on next iteration. old_field_name = field_name else: # If this is neither a FIELD or a FILE, just exhaust the stream. exhaust(stream) except StopUpload as e: self._close_files() if not e.connection_reset: exhaust(self._input_data) else: if not uploaded_file: for handler in handlers: handler.upload_interrupted() # Make sure that the request data is all fed exhaust(self._input_data) # Signal that the upload has completed. # any() shortcircuits if a handler's upload_complete() returns a value. any(handler.upload_complete() for handler in handlers) self._post._mutable = False return self._post, self._files def handle_file_complete(self, old_field_name, counters): """ Handle all the signaling that takes place when a file is complete. """ for i, handler in enumerate(self._upload_handlers): file_obj = handler.file_complete(counters[i]) if file_obj: # If it returns a file object, then set the files dict. self._files.appendlist( force_str(old_field_name, self._encoding, errors="replace"), file_obj, ) break def sanitize_file_name(self, file_name): """ Sanitize the filename of an upload. Remove all possible path separators, even though that might remove more than actually required by the target system. Filenames that could potentially cause problems (current/parent dir) are also discarded. It should be noted that this function could still return a "filepath" like "C:some_file.txt" which is handled later on by the storage layer. So while this function does sanitize filenames to some extent, the resulting filename should still be considered as untrusted user input. """ file_name = html.unescape(file_name) file_name = file_name.rsplit("/")[-1] file_name = file_name.rsplit("\\")[-1] # Remove non-printable characters. file_name = "".join([char for char in file_name if char.isprintable()]) if file_name in {"", ".", ".."}: return None return file_name IE_sanitize = sanitize_file_name def _close_files(self): # Free up all file handles. # FIXME: this currently assumes that upload handlers store the file as 'file' # We should document that... # (Maybe add handler.free_file to complement new_file) for handler in self._upload_handlers: if hasattr(handler, "file"): handler.file.close() class LazyStream: """ The LazyStream wrapper allows one to get and "unget" bytes from a stream. Given a producer object (an iterator that yields bytestrings), the LazyStream object will support iteration, reading, and keeping a "look-back" variable in case you need to "unget" some bytes. """ def __init__(self, producer, length=None): """ Every LazyStream must have a producer when instantiated. A producer is an iterable that returns a string each time it is called. """ self._producer = producer self._empty = False self._leftover = b"" self.length = length self.position = 0 self._remaining = length self._unget_history = [] def tell(self): return self.position def read(self, size=None): def parts(): remaining = self._remaining if size is None else size # do the whole thing in one shot if no limit was provided. if remaining is None: yield b"".join(self) return # otherwise do some bookkeeping to return exactly enough # of the stream and stashing any extra content we get from # the producer while remaining != 0: assert remaining > 0, "remaining bytes to read should never go negative" try: chunk = next(self) except StopIteration: return else: emitting = chunk[:remaining] self.unget(chunk[remaining:]) remaining -= len(emitting) yield emitting return b"".join(parts()) def __next__(self): """ Used when the exact number of bytes to read is unimportant. Return whatever chunk is conveniently returned from the iterator. Useful to avoid unnecessary bookkeeping if performance is an issue. """ if self._leftover: output = self._leftover self._leftover = b"" else: output = next(self._producer) self._unget_history = [] self.position += len(output) return output def close(self): """ Used to invalidate/disable this lazy stream. Replace the producer with an empty list. Any leftover bytes that have already been read will still be reported upon read() and/or next(). """ self._producer = [] def __iter__(self): return self def unget(self, bytes): """ Place bytes back onto the front of the lazy stream. Future calls to read() will return those bytes first. The stream position and thus tell() will be rewound. """ if not bytes: return self._update_unget_history(len(bytes)) self.position -= len(bytes) self._leftover = bytes + self._leftover def _update_unget_history(self, num_bytes): """ Update the unget history as a sanity check to see if we've pushed back the same number of bytes in one chunk. If we keep ungetting the same number of bytes many times (here, 50), we're mostly likely in an infinite loop of some sort. This is usually caused by a maliciously-malformed MIME request. """ self._unget_history = [num_bytes] + self._unget_history[:49] number_equal = len( [ current_number for current_number in self._unget_history if current_number == num_bytes ] ) if number_equal > 40: raise SuspiciousMultipartForm( "The multipart parser got stuck, which shouldn't happen with" " normal uploaded files. Check for malicious upload activity;" " if there is none, report this to the Django developers." ) class ChunkIter: """ An iterable that will yield chunks of data. Given a file-like object as the constructor, yield chunks of read operations from that object. """ def __init__(self, flo, chunk_size=64 * 1024): self.flo = flo self.chunk_size = chunk_size def __next__(self): try: data = self.flo.read(self.chunk_size) except InputStreamExhausted: raise StopIteration() if data: return data else: raise StopIteration() def __iter__(self): return self class InterBoundaryIter: """ A Producer that will iterate over boundaries. """ def __init__(self, stream, boundary): self._stream = stream self._boundary = boundary def __iter__(self): return self def __next__(self): try: return LazyStream(BoundaryIter(self._stream, self._boundary)) except InputStreamExhausted: raise StopIteration() class BoundaryIter: """ A Producer that is sensitive to boundaries. Will happily yield bytes until a boundary is found. Will yield the bytes before the boundary, throw away the boundary bytes themselves, and push the post-boundary bytes back on the stream. The future calls to next() after locating the boundary will raise a StopIteration exception. """ def __init__(self, stream, boundary): self._stream = stream self._boundary = boundary self._done = False # rollback an additional six bytes because the format is like # this: CRLF<boundary>[--CRLF] self._rollback = len(boundary) + 6 # Try to use mx fast string search if available. Otherwise # use Python find. Wrap the latter for consistency. unused_char = self._stream.read(1) if not unused_char: raise InputStreamExhausted() self._stream.unget(unused_char) def __iter__(self): return self def __next__(self): if self._done: raise StopIteration() stream = self._stream rollback = self._rollback bytes_read = 0 chunks = [] for bytes in stream: bytes_read += len(bytes) chunks.append(bytes) if bytes_read > rollback: break if not bytes: break else: self._done = True if not chunks: raise StopIteration() chunk = b"".join(chunks) boundary = self._find_boundary(chunk) if boundary: end, next = boundary stream.unget(chunk[next:]) self._done = True return chunk[:end] else: # make sure we don't treat a partial boundary (and # its separators) as data if not chunk[:-rollback]: # and len(chunk) >= (len(self._boundary) + 6): # There's nothing left, we should just return and mark as done. self._done = True return chunk else: stream.unget(chunk[-rollback:]) return chunk[:-rollback] def _find_boundary(self, data): """ Find a multipart boundary in data. Should no boundary exist in the data, return None. Otherwise, return a tuple containing the indices of the following: * the end of current encapsulation * the start of the next encapsulation """ index = data.find(self._boundary) if index < 0: return None else: end = index next = index + len(self._boundary) # backup over CRLF last = max(0, end - 1) if data[last : last + 1] == b"\n": end -= 1 last = max(0, end - 1) if data[last : last + 1] == b"\r": end -= 1 return end, next def exhaust(stream_or_iterable): """Exhaust an iterator or stream.""" try: iterator = iter(stream_or_iterable) except TypeError: iterator = ChunkIter(stream_or_iterable, 16384) collections.deque(iterator, maxlen=0) # consume iterator quickly. def parse_boundary_stream(stream, max_header_size): """ Parse one and exactly one stream that encapsulates a boundary. """ # Stream at beginning of header, look for end of header # and parse it if found. The header must fit within one # chunk. chunk = stream.read(max_header_size) # 'find' returns the top of these four bytes, so we'll # need to munch them later to prevent them from polluting # the payload. header_end = chunk.find(b"\r\n\r\n") def _parse_header(line): main_value_pair, params = parse_header(line) try: name, value = main_value_pair.split(":", 1) except ValueError: raise ValueError("Invalid header: %r" % line) return name, (value, params) if header_end == -1: # we find no header, so we just mark this fact and pass on # the stream verbatim stream.unget(chunk) return (RAW, {}, stream) header = chunk[:header_end] # here we place any excess chunk back onto the stream, as # well as throwing away the CRLFCRLF bytes from above. stream.unget(chunk[header_end + 4 :]) TYPE = RAW outdict = {} # Eliminate blank lines for line in header.split(b"\r\n"): # This terminology ("main value" and "dictionary of # parameters") is from the Python docs. try: name, (value, params) = _parse_header(line) except ValueError: continue if name == "content-disposition": TYPE = FIELD if params.get("filename"): TYPE = FILE outdict[name] = value, params if TYPE == RAW: stream.unget(chunk) return (TYPE, outdict, stream) class Parser: def __init__(self, stream, boundary): self._stream = stream self._separator = b"--" + boundary def __iter__(self): boundarystream = InterBoundaryIter(self._stream, self._separator) for sub_stream in boundarystream: # Iterate over each part yield parse_boundary_stream(sub_stream, 1024) def parse_header(line): """ Parse the header into a key-value. Input (line): bytes, output: str for key/name, bytes for values which will be decoded later. """ plist = _parse_header_params(b";" + line) key = plist.pop(0).lower().decode("ascii") pdict = {} for p in plist: i = p.find(b"=") if i >= 0: has_encoding = False name = p[:i].strip().lower().decode("ascii") if name.endswith("*"): # Lang/encoding embedded in the value (like "filename*=UTF-8''file.ext") # https://tools.ietf.org/html/rfc2231#section-4 name = name[:-1] if p.count(b"'") == 2: has_encoding = True value = p[i + 1 :].strip() if len(value) >= 2 and value[:1] == value[-1:] == b'"': value = value[1:-1] value = value.replace(b"\\\\", b"\\").replace(b'\\"', b'"') if has_encoding: encoding, lang, value = value.split(b"'") value = unquote(value.decode(), encoding=encoding.decode()) pdict[name] = value return key, pdict def _parse_header_params(s): plist = [] while s[:1] == b";": s = s[1:] end = s.find(b";") while end > 0 and (s.count(b'"', 0, end) - s.count(b'\\"', 0, end)) % 2: end = s.find(b";", end + 1) if end < 0: end = len(s) f = s[:end] plist.append(f.strip()) s = s[end:] return plist
0e97a875655dbf1f64922acbcfeb5b9f6e46952431cfb4f8312dce230909704b
from functools import wraps def no_append_slash(view_func): """ Mark a view function as excluded from CommonMiddleware's APPEND_SLASH redirection. """ # view_func.should_append_slash = False would also work, but decorators are # nicer if they don't have side effects, so return a new function. @wraps(view_func) def wrapper_view(*args, **kwargs): return view_func(*args, **kwargs) wrapper_view.should_append_slash = False return wrapper_view
247d3d5571a66793e66cbd272fb313a75ea1826ebe2d214beb679401a03ff884
from functools import wraps def xframe_options_deny(view_func): """ Modify a view function so its response has the X-Frame-Options HTTP header set to 'DENY' as long as the response doesn't already have that header set. Usage: @xframe_options_deny def some_view(request): ... """ @wraps(view_func) def wrapper_view(*args, **kwargs): resp = view_func(*args, **kwargs) if resp.get("X-Frame-Options") is None: resp["X-Frame-Options"] = "DENY" return resp return wrapper_view def xframe_options_sameorigin(view_func): """ Modify a view function so its response has the X-Frame-Options HTTP header set to 'SAMEORIGIN' as long as the response doesn't already have that header set. Usage: @xframe_options_sameorigin def some_view(request): ... """ @wraps(view_func) def wrapper_view(*args, **kwargs): resp = view_func(*args, **kwargs) if resp.get("X-Frame-Options") is None: resp["X-Frame-Options"] = "SAMEORIGIN" return resp return wrapper_view def xframe_options_exempt(view_func): """ Modify a view function by setting a response variable that instructs XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header. Usage: @xframe_options_exempt def some_view(request): ... """ @wraps(view_func) def wrapper_view(*args, **kwargs): resp = view_func(*args, **kwargs) resp.xframe_options_exempt = True return resp return wrapper_view
e082beb4b888754d6248f3e009d00efad7e1ddfe7918942de1fccc5108db086f
from functools import wraps from django.middleware.cache import CacheMiddleware from django.utils.cache import add_never_cache_headers, patch_cache_control from django.utils.decorators import decorator_from_middleware_with_args def cache_page(timeout, *, cache=None, key_prefix=None): """ Decorator for views that tries getting the page from the cache and populates the cache if the page isn't in the cache yet. The cache is keyed by the URL and some data from the headers. Additionally there is the key prefix that is used to distinguish different cache areas in a multi-site setup. You could use the get_current_site().domain, for example, as that is unique across a Django project. Additionally, all headers from the response's Vary header will be taken into account on caching -- just like the middleware does. """ return decorator_from_middleware_with_args(CacheMiddleware)( page_timeout=timeout, cache_alias=cache, key_prefix=key_prefix, ) def cache_control(**kwargs): def _cache_controller(viewfunc): @wraps(viewfunc) def _cache_controlled(request, *args, **kw): # Ensure argument looks like a request. if not hasattr(request, "META"): raise TypeError( "cache_control didn't receive an HttpRequest. If you are " "decorating a classmethod, be sure to use " "@method_decorator." ) response = viewfunc(request, *args, **kw) patch_cache_control(response, **kwargs) return response return _cache_controlled return _cache_controller def never_cache(view_func): """ Decorator that adds headers to a response so that it will never be cached. """ @wraps(view_func) def _wrapper_view_func(request, *args, **kwargs): # Ensure argument looks like a request. if not hasattr(request, "META"): raise TypeError( "never_cache didn't receive an HttpRequest. If you are " "decorating a classmethod, be sure to use @method_decorator." ) response = view_func(request, *args, **kwargs) add_never_cache_headers(response) return response return _wrapper_view_func
52f6978a2b8925a61d5f32b98ec8b48b731331e37b322ede31a1e6505c878f81
from functools import wraps from django.http import HttpRequest def sensitive_variables(*variables): """ Indicate which variables used in the decorated function are sensitive so that those variables can later be treated in a special way, for example by hiding them when logging unhandled exceptions. Accept two forms: * with specified variable names: @sensitive_variables('user', 'password', 'credit_card') def my_function(user): password = user.pass_word credit_card = user.credit_card_number ... * without any specified variable names, in which case consider all variables are sensitive: @sensitive_variables() def my_function() ... """ if len(variables) == 1 and callable(variables[0]): raise TypeError( "sensitive_variables() must be called to use it as a decorator, " "e.g., use @sensitive_variables(), not @sensitive_variables." ) def decorator(func): @wraps(func) def sensitive_variables_wrapper(*func_args, **func_kwargs): if variables: sensitive_variables_wrapper.sensitive_variables = variables else: sensitive_variables_wrapper.sensitive_variables = "__ALL__" return func(*func_args, **func_kwargs) return sensitive_variables_wrapper return decorator def sensitive_post_parameters(*parameters): """ Indicate which POST parameters used in the decorated view are sensitive, so that those parameters can later be treated in a special way, for example by hiding them when logging unhandled exceptions. Accept two forms: * with specified parameters: @sensitive_post_parameters('password', 'credit_card') def my_view(request): pw = request.POST['password'] cc = request.POST['credit_card'] ... * without any specified parameters, in which case consider all variables are sensitive: @sensitive_post_parameters() def my_view(request) ... """ if len(parameters) == 1 and callable(parameters[0]): raise TypeError( "sensitive_post_parameters() must be called to use it as a " "decorator, e.g., use @sensitive_post_parameters(), not " "@sensitive_post_parameters." ) def decorator(view): @wraps(view) def sensitive_post_parameters_wrapper(request, *args, **kwargs): if not isinstance(request, HttpRequest): raise TypeError( "sensitive_post_parameters didn't receive an HttpRequest " "object. If you are decorating a classmethod, make sure " "to use @method_decorator." ) if parameters: request.sensitive_post_parameters = parameters else: request.sensitive_post_parameters = "__ALL__" return view(request, *args, **kwargs) return sensitive_post_parameters_wrapper return decorator
62d6d5d1376d408e810e2e0283c64027566d6cba924f542fd97d6608385aa1d6
from functools import wraps from django.middleware.csrf import CsrfViewMiddleware, get_token from django.utils.decorators import decorator_from_middleware csrf_protect = decorator_from_middleware(CsrfViewMiddleware) csrf_protect.__name__ = "csrf_protect" csrf_protect.__doc__ = """ This decorator adds CSRF protection in exactly the same way as CsrfViewMiddleware, but it can be used on a per view basis. Using both, or using the decorator multiple times, is harmless and efficient. """ class _EnsureCsrfToken(CsrfViewMiddleware): # Behave like CsrfViewMiddleware but don't reject requests or log warnings. def _reject(self, request, reason): return None requires_csrf_token = decorator_from_middleware(_EnsureCsrfToken) requires_csrf_token.__name__ = "requires_csrf_token" requires_csrf_token.__doc__ = """ Use this decorator on views that need a correct csrf_token available to RequestContext, but without the CSRF protection that csrf_protect enforces. """ class _EnsureCsrfCookie(CsrfViewMiddleware): def _reject(self, request, reason): return None def process_view(self, request, callback, callback_args, callback_kwargs): retval = super().process_view(request, callback, callback_args, callback_kwargs) # Force process_response to send the cookie get_token(request) return retval ensure_csrf_cookie = decorator_from_middleware(_EnsureCsrfCookie) ensure_csrf_cookie.__name__ = "ensure_csrf_cookie" ensure_csrf_cookie.__doc__ = """ Use this decorator to ensure that a view sets a CSRF cookie, whether or not it uses the csrf_token template tag, or the CsrfViewMiddleware is used. """ def csrf_exempt(view_func): """Mark a view function as being exempt from the CSRF view protection.""" # view_func.csrf_exempt = True would also work, but decorators are nicer # if they don't have side effects, so return a new function. @wraps(view_func) def wrapper_view(*args, **kwargs): return view_func(*args, **kwargs) wrapper_view.csrf_exempt = True return wrapper_view
6d59a8eda11e7657ab631c08e8a7c5794fe7ae4c946f40c4b7c4b4e10f6e97f7
import functools import re from collections import defaultdict from itertools import chain from django.conf import settings from django.db import models from django.db.migrations import operations from django.db.migrations.migration import Migration from django.db.migrations.operations.models import AlterModelOptions from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.utils import ( COMPILED_REGEX_TYPE, RegexObject, resolve_relation, ) from django.utils.topological_sort import stable_topological_sort class MigrationAutodetector: """ Take a pair of ProjectStates and compare them to see what the first would need doing to make it match the second (the second usually being the project's current state). Note that this naturally operates on entire projects at a time, as it's likely that changes interact (for example, you can't add a ForeignKey without having a migration to add the table it depends on first). A user interface may offer single-app usage if it wishes, with the caveat that it may not always be possible. """ def __init__(self, from_state, to_state, questioner=None): self.from_state = from_state self.to_state = to_state self.questioner = questioner or MigrationQuestioner() self.existing_apps = {app for app, model in from_state.models} def changes(self, graph, trim_to_apps=None, convert_apps=None, migration_name=None): """ Main entry point to produce a list of applicable changes. Take a graph to base names on and an optional set of apps to try and restrict to (restriction is not guaranteed) """ changes = self._detect_changes(convert_apps, graph) changes = self.arrange_for_graph(changes, graph, migration_name) if trim_to_apps: changes = self._trim_to_apps(changes, trim_to_apps) return changes def deep_deconstruct(self, obj): """ Recursive deconstruction for a field and its arguments. Used for full comparison for rename/alter; sometimes a single-level deconstruction will not compare correctly. """ if isinstance(obj, list): return [self.deep_deconstruct(value) for value in obj] elif isinstance(obj, tuple): return tuple(self.deep_deconstruct(value) for value in obj) elif isinstance(obj, dict): return {key: self.deep_deconstruct(value) for key, value in obj.items()} elif isinstance(obj, functools.partial): return ( obj.func, self.deep_deconstruct(obj.args), self.deep_deconstruct(obj.keywords), ) elif isinstance(obj, COMPILED_REGEX_TYPE): return RegexObject(obj) elif isinstance(obj, type): # If this is a type that implements 'deconstruct' as an instance method, # avoid treating this as being deconstructible itself - see #22951 return obj elif hasattr(obj, "deconstruct"): deconstructed = obj.deconstruct() if isinstance(obj, models.Field): # we have a field which also returns a name deconstructed = deconstructed[1:] path, args, kwargs = deconstructed return ( path, [self.deep_deconstruct(value) for value in args], {key: self.deep_deconstruct(value) for key, value in kwargs.items()}, ) else: return obj def only_relation_agnostic_fields(self, fields): """ Return a definition of the fields that ignores field names and what related fields actually relate to. Used for detecting renames (as the related fields change during renames). """ fields_def = [] for name, field in sorted(fields.items()): deconstruction = self.deep_deconstruct(field) if field.remote_field and field.remote_field.model: deconstruction[2].pop("to", None) fields_def.append(deconstruction) return fields_def def _detect_changes(self, convert_apps=None, graph=None): """ Return a dict of migration plans which will achieve the change from from_state to to_state. The dict has app labels as keys and a list of migrations as values. The resulting migrations aren't specially named, but the names do matter for dependencies inside the set. convert_apps is the list of apps to convert to use migrations (i.e. to make initial migrations for, in the usual case) graph is an optional argument that, if provided, can help improve dependency generation and avoid potential circular dependencies. """ # The first phase is generating all the operations for each app # and gathering them into a big per-app list. # Then go through that list, order it, and split into migrations to # resolve dependencies caused by M2Ms and FKs. self.generated_operations = {} self.altered_indexes = {} self.altered_constraints = {} self.renamed_fields = {} # Prepare some old/new state and model lists, separating # proxy models and ignoring unmigrated apps. self.old_model_keys = set() self.old_proxy_keys = set() self.old_unmanaged_keys = set() self.new_model_keys = set() self.new_proxy_keys = set() self.new_unmanaged_keys = set() for (app_label, model_name), model_state in self.from_state.models.items(): if not model_state.options.get("managed", True): self.old_unmanaged_keys.add((app_label, model_name)) elif app_label not in self.from_state.real_apps: if model_state.options.get("proxy"): self.old_proxy_keys.add((app_label, model_name)) else: self.old_model_keys.add((app_label, model_name)) for (app_label, model_name), model_state in self.to_state.models.items(): if not model_state.options.get("managed", True): self.new_unmanaged_keys.add((app_label, model_name)) elif app_label not in self.from_state.real_apps or ( convert_apps and app_label in convert_apps ): if model_state.options.get("proxy"): self.new_proxy_keys.add((app_label, model_name)) else: self.new_model_keys.add((app_label, model_name)) self.from_state.resolve_fields_and_relations() self.to_state.resolve_fields_and_relations() # Renames have to come first self.generate_renamed_models() # Prepare lists of fields and generate through model map self._prepare_field_lists() self._generate_through_model_map() # Generate non-rename model operations self.generate_deleted_models() self.generate_created_models() self.generate_deleted_proxies() self.generate_created_proxies() self.generate_altered_options() self.generate_altered_managers() # Create the renamed fields and store them in self.renamed_fields. # They are used by create_altered_indexes(), generate_altered_fields(), # generate_removed_altered_index/unique_together(), and # generate_altered_index/unique_together(). self.create_renamed_fields() # Create the altered indexes and store them in self.altered_indexes. # This avoids the same computation in generate_removed_indexes() # and generate_added_indexes(). self.create_altered_indexes() self.create_altered_constraints() # Generate index removal operations before field is removed self.generate_removed_constraints() self.generate_removed_indexes() # Generate field renaming operations. self.generate_renamed_fields() self.generate_renamed_indexes() # Generate removal of foo together. self.generate_removed_altered_unique_together() self.generate_removed_altered_index_together() # Generate field operations. self.generate_removed_fields() self.generate_added_fields() self.generate_altered_fields() self.generate_altered_order_with_respect_to() self.generate_altered_unique_together() self.generate_altered_index_together() self.generate_added_indexes() self.generate_added_constraints() self.generate_altered_db_table() self._sort_migrations() self._build_migration_list(graph) self._optimize_migrations() return self.migrations def _prepare_field_lists(self): """ Prepare field lists and a list of the fields that used through models in the old state so dependencies can be made from the through model deletion to the field that uses it. """ self.kept_model_keys = self.old_model_keys & self.new_model_keys self.kept_proxy_keys = self.old_proxy_keys & self.new_proxy_keys self.kept_unmanaged_keys = self.old_unmanaged_keys & self.new_unmanaged_keys self.through_users = {} self.old_field_keys = { (app_label, model_name, field_name) for app_label, model_name in self.kept_model_keys for field_name in self.from_state.models[ app_label, self.renamed_models.get((app_label, model_name), model_name) ].fields } self.new_field_keys = { (app_label, model_name, field_name) for app_label, model_name in self.kept_model_keys for field_name in self.to_state.models[app_label, model_name].fields } def _generate_through_model_map(self): """Through model map generation.""" for app_label, model_name in sorted(self.old_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] for field_name, field in old_model_state.fields.items(): if hasattr(field, "remote_field") and getattr( field.remote_field, "through", None ): through_key = resolve_relation( field.remote_field.through, app_label, model_name ) self.through_users[through_key] = ( app_label, old_model_name, field_name, ) @staticmethod def _resolve_dependency(dependency): """ Return the resolved dependency and a boolean denoting whether or not it was swappable. """ if dependency[0] != "__setting__": return dependency, False resolved_app_label, resolved_object_name = getattr( settings, dependency[1] ).split(".") return (resolved_app_label, resolved_object_name.lower()) + dependency[2:], True def _build_migration_list(self, graph=None): """ Chop the lists of operations up into migrations with dependencies on each other. Do this by going through an app's list of operations until one is found that has an outgoing dependency that isn't in another app's migration yet (hasn't been chopped off its list). Then chop off the operations before it into a migration and move onto the next app. If the loops completes without doing anything, there's a circular dependency (which _should_ be impossible as the operations are all split at this point so they can't depend and be depended on). """ self.migrations = {} num_ops = sum(len(x) for x in self.generated_operations.values()) chop_mode = False while num_ops: # On every iteration, we step through all the apps and see if there # is a completed set of operations. # If we find that a subset of the operations are complete we can # try to chop it off from the rest and continue, but we only # do this if we've already been through the list once before # without any chopping and nothing has changed. for app_label in sorted(self.generated_operations): chopped = [] dependencies = set() for operation in list(self.generated_operations[app_label]): deps_satisfied = True operation_dependencies = set() for dep in operation._auto_deps: # Temporarily resolve the swappable dependency to # prevent circular references. While keeping the # dependency checks on the resolved model, add the # swappable dependencies. original_dep = dep dep, is_swappable_dep = self._resolve_dependency(dep) if dep[0] != app_label: # External app dependency. See if it's not yet # satisfied. for other_operation in self.generated_operations.get( dep[0], [] ): if self.check_dependency(other_operation, dep): deps_satisfied = False break if not deps_satisfied: break else: if is_swappable_dep: operation_dependencies.add( (original_dep[0], original_dep[1]) ) elif dep[0] in self.migrations: operation_dependencies.add( (dep[0], self.migrations[dep[0]][-1].name) ) else: # If we can't find the other app, we add a # first/last dependency, but only if we've # already been through once and checked # everything. if chop_mode: # If the app already exists, we add a # dependency on the last migration, as # we don't know which migration # contains the target field. If it's # not yet migrated or has no # migrations, we use __first__. if graph and graph.leaf_nodes(dep[0]): operation_dependencies.add( graph.leaf_nodes(dep[0])[0] ) else: operation_dependencies.add( (dep[0], "__first__") ) else: deps_satisfied = False if deps_satisfied: chopped.append(operation) dependencies.update(operation_dependencies) del self.generated_operations[app_label][0] else: break # Make a migration! Well, only if there's stuff to put in it if dependencies or chopped: if not self.generated_operations[app_label] or chop_mode: subclass = type( "Migration", (Migration,), {"operations": [], "dependencies": []}, ) instance = subclass( "auto_%i" % (len(self.migrations.get(app_label, [])) + 1), app_label, ) instance.dependencies = list(dependencies) instance.operations = chopped instance.initial = app_label not in self.existing_apps self.migrations.setdefault(app_label, []).append(instance) chop_mode = False else: self.generated_operations[app_label] = ( chopped + self.generated_operations[app_label] ) new_num_ops = sum(len(x) for x in self.generated_operations.values()) if new_num_ops == num_ops: if not chop_mode: chop_mode = True else: raise ValueError( "Cannot resolve operation dependencies: %r" % self.generated_operations ) num_ops = new_num_ops def _sort_migrations(self): """ Reorder to make things possible. Reordering may be needed so FKs work nicely inside the same app. """ for app_label, ops in sorted(self.generated_operations.items()): # construct a dependency graph for intra-app dependencies dependency_graph = {op: set() for op in ops} for op in ops: for dep in op._auto_deps: # Resolve intra-app dependencies to handle circular # references involving a swappable model. dep = self._resolve_dependency(dep)[0] if dep[0] == app_label: for op2 in ops: if self.check_dependency(op2, dep): dependency_graph[op].add(op2) # we use a stable sort for deterministic tests & general behavior self.generated_operations[app_label] = stable_topological_sort( ops, dependency_graph ) def _optimize_migrations(self): # Add in internal dependencies among the migrations for app_label, migrations in self.migrations.items(): for m1, m2 in zip(migrations, migrations[1:]): m2.dependencies.append((app_label, m1.name)) # De-dupe dependencies for migrations in self.migrations.values(): for migration in migrations: migration.dependencies = list(set(migration.dependencies)) # Optimize migrations for app_label, migrations in self.migrations.items(): for migration in migrations: migration.operations = MigrationOptimizer().optimize( migration.operations, app_label ) def check_dependency(self, operation, dependency): """ Return True if the given operation depends on the given dependency, False otherwise. """ # Created model if dependency[2] is None and dependency[3] is True: return ( isinstance(operation, operations.CreateModel) and operation.name_lower == dependency[1].lower() ) # Created field elif dependency[2] is not None and dependency[3] is True: return ( isinstance(operation, operations.CreateModel) and operation.name_lower == dependency[1].lower() and any(dependency[2] == x for x, y in operation.fields) ) or ( isinstance(operation, operations.AddField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # Removed field elif dependency[2] is not None and dependency[3] is False: return ( isinstance(operation, operations.RemoveField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # Removed model elif dependency[2] is None and dependency[3] is False: return ( isinstance(operation, operations.DeleteModel) and operation.name_lower == dependency[1].lower() ) # Field being altered elif dependency[2] is not None and dependency[3] == "alter": return ( isinstance(operation, operations.AlterField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # order_with_respect_to being unset for a field elif dependency[2] is not None and dependency[3] == "order_wrt_unset": return ( isinstance(operation, operations.AlterOrderWithRespectTo) and operation.name_lower == dependency[1].lower() and (operation.order_with_respect_to or "").lower() != dependency[2].lower() ) # Field is removed and part of an index/unique_together elif dependency[2] is not None and dependency[3] == "foo_together_change": return ( isinstance( operation, (operations.AlterUniqueTogether, operations.AlterIndexTogether), ) and operation.name_lower == dependency[1].lower() ) # Unknown dependency. Raise an error. else: raise ValueError("Can't handle dependency %r" % (dependency,)) def add_operation(self, app_label, operation, dependencies=None, beginning=False): # Dependencies are # (app_label, model_name, field_name, create/delete as True/False) operation._auto_deps = dependencies or [] if beginning: self.generated_operations.setdefault(app_label, []).insert(0, operation) else: self.generated_operations.setdefault(app_label, []).append(operation) def swappable_first_key(self, item): """ Place potential swappable models first in lists of created models (only real way to solve #22783). """ try: model_state = self.to_state.models[item] base_names = { base if isinstance(base, str) else base.__name__ for base in model_state.bases } string_version = "%s.%s" % (item[0], item[1]) if ( model_state.options.get("swappable") or "AbstractUser" in base_names or "AbstractBaseUser" in base_names or settings.AUTH_USER_MODEL.lower() == string_version.lower() ): return ("___" + item[0], "___" + item[1]) except LookupError: pass return item def generate_renamed_models(self): """ Find any renamed models, generate the operations for them, and remove the old entry from the model lists. Must be run before other model-level generation. """ self.renamed_models = {} self.renamed_models_rel = {} added_models = self.new_model_keys - self.old_model_keys for app_label, model_name in sorted(added_models): model_state = self.to_state.models[app_label, model_name] model_fields_def = self.only_relation_agnostic_fields(model_state.fields) removed_models = self.old_model_keys - self.new_model_keys for rem_app_label, rem_model_name in removed_models: if rem_app_label == app_label: rem_model_state = self.from_state.models[ rem_app_label, rem_model_name ] rem_model_fields_def = self.only_relation_agnostic_fields( rem_model_state.fields ) if model_fields_def == rem_model_fields_def: if self.questioner.ask_rename_model( rem_model_state, model_state ): dependencies = [] fields = list(model_state.fields.values()) + [ field.remote_field for relations in self.to_state.relations[ app_label, model_name ].values() for field in relations.values() ] for field in fields: if field.is_relation: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) self.add_operation( app_label, operations.RenameModel( old_name=rem_model_state.name, new_name=model_state.name, ), dependencies=dependencies, ) self.renamed_models[app_label, model_name] = rem_model_name renamed_models_rel_key = "%s.%s" % ( rem_model_state.app_label, rem_model_state.name_lower, ) self.renamed_models_rel[ renamed_models_rel_key ] = "%s.%s" % ( model_state.app_label, model_state.name_lower, ) self.old_model_keys.remove((rem_app_label, rem_model_name)) self.old_model_keys.add((app_label, model_name)) break def generate_created_models(self): """ Find all new models (both managed and unmanaged) and make create operations for them as well as separate operations to create any foreign key or M2M relationships (these are optimized later, if possible). Defer any model options that refer to collections of fields that might be deferred (e.g. unique_together, index_together). """ old_keys = self.old_model_keys | self.old_unmanaged_keys added_models = self.new_model_keys - old_keys added_unmanaged_models = self.new_unmanaged_keys - old_keys all_added_models = chain( sorted(added_models, key=self.swappable_first_key, reverse=True), sorted(added_unmanaged_models, key=self.swappable_first_key, reverse=True), ) for app_label, model_name in all_added_models: model_state = self.to_state.models[app_label, model_name] # Gather related fields related_fields = {} primary_key_rel = None for field_name, field in model_state.fields.items(): if field.remote_field: if field.remote_field.model: if field.primary_key: primary_key_rel = field.remote_field.model elif not field.remote_field.parent_link: related_fields[field_name] = field if getattr(field.remote_field, "through", None): related_fields[field_name] = field # Are there indexes/unique|index_together to defer? indexes = model_state.options.pop("indexes") constraints = model_state.options.pop("constraints") unique_together = model_state.options.pop("unique_together", None) index_together = model_state.options.pop("index_together", None) order_with_respect_to = model_state.options.pop( "order_with_respect_to", None ) # Depend on the deletion of any possible proxy version of us dependencies = [ (app_label, model_name, None, False), ] # Depend on all bases for base in model_state.bases: if isinstance(base, str) and "." in base: base_app_label, base_name = base.split(".", 1) dependencies.append((base_app_label, base_name, None, True)) # Depend on the removal of base fields if the new model has # a field with the same name. old_base_model_state = self.from_state.models.get( (base_app_label, base_name) ) new_base_model_state = self.to_state.models.get( (base_app_label, base_name) ) if old_base_model_state and new_base_model_state: removed_base_fields = ( set(old_base_model_state.fields) .difference( new_base_model_state.fields, ) .intersection(model_state.fields) ) for removed_base_field in removed_base_fields: dependencies.append( (base_app_label, base_name, removed_base_field, False) ) # Depend on the other end of the primary key if it's a relation if primary_key_rel: dependencies.append( resolve_relation( primary_key_rel, app_label, model_name, ) + (None, True) ) # Generate creation operation self.add_operation( app_label, operations.CreateModel( name=model_state.name, fields=[ d for d in model_state.fields.items() if d[0] not in related_fields ], options=model_state.options, bases=model_state.bases, managers=model_state.managers, ), dependencies=dependencies, beginning=True, ) # Don't add operations which modify the database for unmanaged models if not model_state.options.get("managed", True): continue # Generate operations for each related field for name, field in sorted(related_fields.items()): dependencies = self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) # Depend on our own model being created dependencies.append((app_label, model_name, None, True)) # Make operation self.add_operation( app_label, operations.AddField( model_name=model_name, name=name, field=field, ), dependencies=list(set(dependencies)), ) # Generate other opns if order_with_respect_to: self.add_operation( app_label, operations.AlterOrderWithRespectTo( name=model_name, order_with_respect_to=order_with_respect_to, ), dependencies=[ (app_label, model_name, order_with_respect_to, True), (app_label, model_name, None, True), ], ) related_dependencies = [ (app_label, model_name, name, True) for name in sorted(related_fields) ] related_dependencies.append((app_label, model_name, None, True)) for index in indexes: self.add_operation( app_label, operations.AddIndex( model_name=model_name, index=index, ), dependencies=related_dependencies, ) for constraint in constraints: self.add_operation( app_label, operations.AddConstraint( model_name=model_name, constraint=constraint, ), dependencies=related_dependencies, ) if unique_together: self.add_operation( app_label, operations.AlterUniqueTogether( name=model_name, unique_together=unique_together, ), dependencies=related_dependencies, ) if index_together: self.add_operation( app_label, operations.AlterIndexTogether( name=model_name, index_together=index_together, ), dependencies=related_dependencies, ) # Fix relationships if the model changed from a proxy model to a # concrete model. relations = self.to_state.relations if (app_label, model_name) in self.old_proxy_keys: for related_model_key, related_fields in relations[ app_label, model_name ].items(): related_model_state = self.to_state.models[related_model_key] for related_field_name, related_field in related_fields.items(): self.add_operation( related_model_state.app_label, operations.AlterField( model_name=related_model_state.name, name=related_field_name, field=related_field, ), dependencies=[(app_label, model_name, None, True)], ) def generate_created_proxies(self): """ Make CreateModel statements for proxy models. Use the same statements as that way there's less code duplication, but for proxy models it's safe to skip all the pointless field stuff and chuck out an operation. """ added = self.new_proxy_keys - self.old_proxy_keys for app_label, model_name in sorted(added): model_state = self.to_state.models[app_label, model_name] assert model_state.options.get("proxy") # Depend on the deletion of any possible non-proxy version of us dependencies = [ (app_label, model_name, None, False), ] # Depend on all bases for base in model_state.bases: if isinstance(base, str) and "." in base: base_app_label, base_name = base.split(".", 1) dependencies.append((base_app_label, base_name, None, True)) # Generate creation operation self.add_operation( app_label, operations.CreateModel( name=model_state.name, fields=[], options=model_state.options, bases=model_state.bases, managers=model_state.managers, ), # Depend on the deletion of any possible non-proxy version of us dependencies=dependencies, ) def generate_deleted_models(self): """ Find all deleted models (managed and unmanaged) and make delete operations for them as well as separate operations to delete any foreign key or M2M relationships (these are optimized later, if possible). Also bring forward removal of any model options that refer to collections of fields - the inverse of generate_created_models(). """ new_keys = self.new_model_keys | self.new_unmanaged_keys deleted_models = self.old_model_keys - new_keys deleted_unmanaged_models = self.old_unmanaged_keys - new_keys all_deleted_models = chain( sorted(deleted_models), sorted(deleted_unmanaged_models) ) for app_label, model_name in all_deleted_models: model_state = self.from_state.models[app_label, model_name] # Gather related fields related_fields = {} for field_name, field in model_state.fields.items(): if field.remote_field: if field.remote_field.model: related_fields[field_name] = field if getattr(field.remote_field, "through", None): related_fields[field_name] = field # Generate option removal first unique_together = model_state.options.pop("unique_together", None) index_together = model_state.options.pop("index_together", None) if unique_together: self.add_operation( app_label, operations.AlterUniqueTogether( name=model_name, unique_together=None, ), ) if index_together: self.add_operation( app_label, operations.AlterIndexTogether( name=model_name, index_together=None, ), ) # Then remove each related field for name in sorted(related_fields): self.add_operation( app_label, operations.RemoveField( model_name=model_name, name=name, ), ) # Finally, remove the model. # This depends on both the removal/alteration of all incoming fields # and the removal of all its own related fields, and if it's # a through model the field that references it. dependencies = [] relations = self.from_state.relations for ( related_object_app_label, object_name, ), relation_related_fields in relations[app_label, model_name].items(): for field_name, field in relation_related_fields.items(): dependencies.append( (related_object_app_label, object_name, field_name, False), ) if not field.many_to_many: dependencies.append( ( related_object_app_label, object_name, field_name, "alter", ), ) for name in sorted(related_fields): dependencies.append((app_label, model_name, name, False)) # We're referenced in another field's through= through_user = self.through_users.get((app_label, model_state.name_lower)) if through_user: dependencies.append( (through_user[0], through_user[1], through_user[2], False) ) # Finally, make the operation, deduping any dependencies self.add_operation( app_label, operations.DeleteModel( name=model_state.name, ), dependencies=list(set(dependencies)), ) def generate_deleted_proxies(self): """Make DeleteModel options for proxy models.""" deleted = self.old_proxy_keys - self.new_proxy_keys for app_label, model_name in sorted(deleted): model_state = self.from_state.models[app_label, model_name] assert model_state.options.get("proxy") self.add_operation( app_label, operations.DeleteModel( name=model_state.name, ), ) def create_renamed_fields(self): """Work out renamed fields.""" self.renamed_operations = [] old_field_keys = self.old_field_keys.copy() for app_label, model_name, field_name in sorted( self.new_field_keys - old_field_keys ): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] field = new_model_state.get_field(field_name) # Scan to see if this is actually a rename! field_dec = self.deep_deconstruct(field) for rem_app_label, rem_model_name, rem_field_name in sorted( old_field_keys - self.new_field_keys ): if rem_app_label == app_label and rem_model_name == model_name: old_field = old_model_state.get_field(rem_field_name) old_field_dec = self.deep_deconstruct(old_field) if ( field.remote_field and field.remote_field.model and "to" in old_field_dec[2] ): old_rel_to = old_field_dec[2]["to"] if old_rel_to in self.renamed_models_rel: old_field_dec[2]["to"] = self.renamed_models_rel[old_rel_to] old_field.set_attributes_from_name(rem_field_name) old_db_column = old_field.get_attname_column()[1] if old_field_dec == field_dec or ( # Was the field renamed and db_column equal to the # old field's column added? old_field_dec[0:2] == field_dec[0:2] and dict(old_field_dec[2], db_column=old_db_column) == field_dec[2] ): if self.questioner.ask_rename( model_name, rem_field_name, field_name, field ): self.renamed_operations.append( ( rem_app_label, rem_model_name, old_field.db_column, rem_field_name, app_label, model_name, field, field_name, ) ) old_field_keys.remove( (rem_app_label, rem_model_name, rem_field_name) ) old_field_keys.add((app_label, model_name, field_name)) self.renamed_fields[ app_label, model_name, field_name ] = rem_field_name break def generate_renamed_fields(self): """Generate RenameField operations.""" for ( rem_app_label, rem_model_name, rem_db_column, rem_field_name, app_label, model_name, field, field_name, ) in self.renamed_operations: # A db_column mismatch requires a prior noop AlterField for the # subsequent RenameField to be a noop on attempts at preserving the # old name. if rem_db_column != field.db_column: altered_field = field.clone() altered_field.name = rem_field_name self.add_operation( app_label, operations.AlterField( model_name=model_name, name=rem_field_name, field=altered_field, ), ) self.add_operation( app_label, operations.RenameField( model_name=model_name, old_name=rem_field_name, new_name=field_name, ), ) self.old_field_keys.remove((rem_app_label, rem_model_name, rem_field_name)) self.old_field_keys.add((app_label, model_name, field_name)) def generate_added_fields(self): """Make AddField operations.""" for app_label, model_name, field_name in sorted( self.new_field_keys - self.old_field_keys ): self._generate_added_field(app_label, model_name, field_name) def _generate_added_field(self, app_label, model_name, field_name): field = self.to_state.models[app_label, model_name].get_field(field_name) # Fields that are foreignkeys/m2ms depend on stuff dependencies = [] if field.remote_field and field.remote_field.model: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) # You can't just add NOT NULL fields with no default or fields # which don't allow empty strings as default. time_fields = (models.DateField, models.DateTimeField, models.TimeField) preserve_default = ( field.null or field.has_default() or field.many_to_many or (field.blank and field.empty_strings_allowed) or (isinstance(field, time_fields) and field.auto_now) ) if not preserve_default: field = field.clone() if isinstance(field, time_fields) and field.auto_now_add: field.default = self.questioner.ask_auto_now_add_addition( field_name, model_name ) else: field.default = self.questioner.ask_not_null_addition( field_name, model_name ) if ( field.unique and field.default is not models.NOT_PROVIDED and callable(field.default) ): self.questioner.ask_unique_callable_default_addition(field_name, model_name) self.add_operation( app_label, operations.AddField( model_name=model_name, name=field_name, field=field, preserve_default=preserve_default, ), dependencies=dependencies, ) def generate_removed_fields(self): """Make RemoveField operations.""" for app_label, model_name, field_name in sorted( self.old_field_keys - self.new_field_keys ): self._generate_removed_field(app_label, model_name, field_name) def _generate_removed_field(self, app_label, model_name, field_name): self.add_operation( app_label, operations.RemoveField( model_name=model_name, name=field_name, ), # We might need to depend on the removal of an # order_with_respect_to or index/unique_together operation; # this is safely ignored if there isn't one dependencies=[ (app_label, model_name, field_name, "order_wrt_unset"), (app_label, model_name, field_name, "foo_together_change"), ], ) def generate_altered_fields(self): """ Make AlterField operations, or possibly RemovedField/AddField if alter isn't possible. """ for app_label, model_name, field_name in sorted( self.old_field_keys & self.new_field_keys ): # Did the field change? old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_field_name = self.renamed_fields.get( (app_label, model_name, field_name), field_name ) old_field = self.from_state.models[app_label, old_model_name].get_field( old_field_name ) new_field = self.to_state.models[app_label, model_name].get_field( field_name ) dependencies = [] # Implement any model renames on relations; these are handled by RenameModel # so we need to exclude them from the comparison if hasattr(new_field, "remote_field") and getattr( new_field.remote_field, "model", None ): rename_key = resolve_relation( new_field.remote_field.model, app_label, model_name ) if rename_key in self.renamed_models: new_field.remote_field.model = old_field.remote_field.model # Handle ForeignKey which can only have a single to_field. remote_field_name = getattr(new_field.remote_field, "field_name", None) if remote_field_name: to_field_rename_key = rename_key + (remote_field_name,) if to_field_rename_key in self.renamed_fields: # Repoint both model and field name because to_field # inclusion in ForeignKey.deconstruct() is based on # both. new_field.remote_field.model = old_field.remote_field.model new_field.remote_field.field_name = ( old_field.remote_field.field_name ) # Handle ForeignObjects which can have multiple from_fields/to_fields. from_fields = getattr(new_field, "from_fields", None) if from_fields: from_rename_key = (app_label, model_name) new_field.from_fields = tuple( [ self.renamed_fields.get( from_rename_key + (from_field,), from_field ) for from_field in from_fields ] ) new_field.to_fields = tuple( [ self.renamed_fields.get(rename_key + (to_field,), to_field) for to_field in new_field.to_fields ] ) dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, new_field, self.to_state, ) ) if hasattr(new_field, "remote_field") and getattr( new_field.remote_field, "through", None ): rename_key = resolve_relation( new_field.remote_field.through, app_label, model_name ) if rename_key in self.renamed_models: new_field.remote_field.through = old_field.remote_field.through old_field_dec = self.deep_deconstruct(old_field) new_field_dec = self.deep_deconstruct(new_field) # If the field was confirmed to be renamed it means that only # db_column was allowed to change which generate_renamed_fields() # already accounts for by adding an AlterField operation. if old_field_dec != new_field_dec and old_field_name == field_name: both_m2m = old_field.many_to_many and new_field.many_to_many neither_m2m = not old_field.many_to_many and not new_field.many_to_many if both_m2m or neither_m2m: # Either both fields are m2m or neither is preserve_default = True if ( old_field.null and not new_field.null and not new_field.has_default() and not new_field.many_to_many ): field = new_field.clone() new_default = self.questioner.ask_not_null_alteration( field_name, model_name ) if new_default is not models.NOT_PROVIDED: field.default = new_default preserve_default = False else: field = new_field self.add_operation( app_label, operations.AlterField( model_name=model_name, name=field_name, field=field, preserve_default=preserve_default, ), dependencies=dependencies, ) else: # We cannot alter between m2m and concrete fields self._generate_removed_field(app_label, model_name, field_name) self._generate_added_field(app_label, model_name, field_name) def create_altered_indexes(self): option_name = operations.AddIndex.option_name self.renamed_index_together_values = defaultdict(list) for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_indexes = old_model_state.options[option_name] new_indexes = new_model_state.options[option_name] added_indexes = [idx for idx in new_indexes if idx not in old_indexes] removed_indexes = [idx for idx in old_indexes if idx not in new_indexes] renamed_indexes = [] # Find renamed indexes. remove_from_added = [] remove_from_removed = [] for new_index in added_indexes: new_index_dec = new_index.deconstruct() new_index_name = new_index_dec[2].pop("name") for old_index in removed_indexes: old_index_dec = old_index.deconstruct() old_index_name = old_index_dec[2].pop("name") # Indexes are the same except for the names. if ( new_index_dec == old_index_dec and new_index_name != old_index_name ): renamed_indexes.append((old_index_name, new_index_name, None)) remove_from_added.append(new_index) remove_from_removed.append(old_index) # Find index_together changed to indexes. for ( old_value, new_value, index_together_app_label, index_together_model_name, dependencies, ) in self._get_altered_foo_together_operations( operations.AlterIndexTogether.option_name ): if ( app_label != index_together_app_label or model_name != index_together_model_name ): continue removed_values = old_value.difference(new_value) for removed_index_together in removed_values: renamed_index_together_indexes = [] for new_index in added_indexes: _, args, kwargs = new_index.deconstruct() # Ensure only 'fields' are defined in the Index. if ( not args and new_index.fields == list(removed_index_together) and set(kwargs) == {"name", "fields"} ): renamed_index_together_indexes.append(new_index) if len(renamed_index_together_indexes) == 1: renamed_index = renamed_index_together_indexes[0] remove_from_added.append(renamed_index) renamed_indexes.append( (None, renamed_index.name, removed_index_together) ) self.renamed_index_together_values[ index_together_app_label, index_together_model_name ].append(removed_index_together) # Remove renamed indexes from the lists of added and removed # indexes. added_indexes = [ idx for idx in added_indexes if idx not in remove_from_added ] removed_indexes = [ idx for idx in removed_indexes if idx not in remove_from_removed ] self.altered_indexes.update( { (app_label, model_name): { "added_indexes": added_indexes, "removed_indexes": removed_indexes, "renamed_indexes": renamed_indexes, } } ) def generate_added_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for index in alt_indexes["added_indexes"]: self.add_operation( app_label, operations.AddIndex( model_name=model_name, index=index, ), ) def generate_removed_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for index in alt_indexes["removed_indexes"]: self.add_operation( app_label, operations.RemoveIndex( model_name=model_name, name=index.name, ), ) def generate_renamed_indexes(self): for (app_label, model_name), alt_indexes in self.altered_indexes.items(): for old_index_name, new_index_name, old_fields in alt_indexes[ "renamed_indexes" ]: self.add_operation( app_label, operations.RenameIndex( model_name=model_name, new_name=new_index_name, old_name=old_index_name, old_fields=old_fields, ), ) def create_altered_constraints(self): option_name = operations.AddConstraint.option_name for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_constraints = old_model_state.options[option_name] new_constraints = new_model_state.options[option_name] add_constraints = [c for c in new_constraints if c not in old_constraints] rem_constraints = [c for c in old_constraints if c not in new_constraints] self.altered_constraints.update( { (app_label, model_name): { "added_constraints": add_constraints, "removed_constraints": rem_constraints, } } ) def generate_added_constraints(self): for ( app_label, model_name, ), alt_constraints in self.altered_constraints.items(): for constraint in alt_constraints["added_constraints"]: self.add_operation( app_label, operations.AddConstraint( model_name=model_name, constraint=constraint, ), ) def generate_removed_constraints(self): for ( app_label, model_name, ), alt_constraints in self.altered_constraints.items(): for constraint in alt_constraints["removed_constraints"]: self.add_operation( app_label, operations.RemoveConstraint( model_name=model_name, name=constraint.name, ), ) @staticmethod def _get_dependencies_for_foreign_key(app_label, model_name, field, project_state): remote_field_model = None if hasattr(field.remote_field, "model"): remote_field_model = field.remote_field.model else: relations = project_state.relations[app_label, model_name] for (remote_app_label, remote_model_name), fields in relations.items(): if any( field == related_field.remote_field for related_field in fields.values() ): remote_field_model = f"{remote_app_label}.{remote_model_name}" break # Account for FKs to swappable models swappable_setting = getattr(field, "swappable_setting", None) if swappable_setting is not None: dep_app_label = "__setting__" dep_object_name = swappable_setting else: dep_app_label, dep_object_name = resolve_relation( remote_field_model, app_label, model_name, ) dependencies = [(dep_app_label, dep_object_name, None, True)] if getattr(field.remote_field, "through", None): through_app_label, through_object_name = resolve_relation( remote_field_model, app_label, model_name, ) dependencies.append((through_app_label, through_object_name, None, True)) return dependencies def _get_altered_foo_together_operations(self, option_name): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] # We run the old version through the field renames to account for those old_value = old_model_state.options.get(option_name) old_value = ( { tuple( self.renamed_fields.get((app_label, model_name, n), n) for n in unique ) for unique in old_value } if old_value else set() ) new_value = new_model_state.options.get(option_name) new_value = set(new_value) if new_value else set() if old_value != new_value: dependencies = [] for foo_togethers in new_value: for field_name in foo_togethers: field = new_model_state.get_field(field_name) if field.remote_field and field.remote_field.model: dependencies.extend( self._get_dependencies_for_foreign_key( app_label, model_name, field, self.to_state, ) ) yield ( old_value, new_value, app_label, model_name, dependencies, ) def _generate_removed_altered_foo_together(self, operation): for ( old_value, new_value, app_label, model_name, dependencies, ) in self._get_altered_foo_together_operations(operation.option_name): if operation == operations.AlterIndexTogether: old_value = { value for value in old_value if value not in self.renamed_index_together_values[app_label, model_name] } removal_value = new_value.intersection(old_value) if removal_value or old_value: self.add_operation( app_label, operation( name=model_name, **{operation.option_name: removal_value} ), dependencies=dependencies, ) def generate_removed_altered_unique_together(self): self._generate_removed_altered_foo_together(operations.AlterUniqueTogether) def generate_removed_altered_index_together(self): self._generate_removed_altered_foo_together(operations.AlterIndexTogether) def _generate_altered_foo_together(self, operation): for ( old_value, new_value, app_label, model_name, dependencies, ) in self._get_altered_foo_together_operations(operation.option_name): removal_value = new_value.intersection(old_value) if new_value != removal_value: self.add_operation( app_label, operation(name=model_name, **{operation.option_name: new_value}), dependencies=dependencies, ) def generate_altered_unique_together(self): self._generate_altered_foo_together(operations.AlterUniqueTogether) def generate_altered_index_together(self): self._generate_altered_foo_together(operations.AlterIndexTogether) def generate_altered_db_table(self): models_to_check = self.kept_model_keys.union( self.kept_proxy_keys, self.kept_unmanaged_keys ) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_db_table_name = old_model_state.options.get("db_table") new_db_table_name = new_model_state.options.get("db_table") if old_db_table_name != new_db_table_name: self.add_operation( app_label, operations.AlterModelTable( name=model_name, table=new_db_table_name, ), ) def generate_altered_options(self): """ Work out if any non-schema-affecting options have changed and make an operation to represent them in state changes (in case Python code in migrations needs them). """ models_to_check = self.kept_model_keys.union( self.kept_proxy_keys, self.kept_unmanaged_keys, # unmanaged converted to managed self.old_unmanaged_keys & self.new_model_keys, # managed converted to unmanaged self.old_model_keys & self.new_unmanaged_keys, ) for app_label, model_name in sorted(models_to_check): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] old_options = { key: value for key, value in old_model_state.options.items() if key in AlterModelOptions.ALTER_OPTION_KEYS } new_options = { key: value for key, value in new_model_state.options.items() if key in AlterModelOptions.ALTER_OPTION_KEYS } if old_options != new_options: self.add_operation( app_label, operations.AlterModelOptions( name=model_name, options=new_options, ), ) def generate_altered_order_with_respect_to(self): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] if old_model_state.options.get( "order_with_respect_to" ) != new_model_state.options.get("order_with_respect_to"): # Make sure it comes second if we're adding # (removal dependency is part of RemoveField) dependencies = [] if new_model_state.options.get("order_with_respect_to"): dependencies.append( ( app_label, model_name, new_model_state.options["order_with_respect_to"], True, ) ) # Actually generate the operation self.add_operation( app_label, operations.AlterOrderWithRespectTo( name=model_name, order_with_respect_to=new_model_state.options.get( "order_with_respect_to" ), ), dependencies=dependencies, ) def generate_altered_managers(self): for app_label, model_name in sorted(self.kept_model_keys): old_model_name = self.renamed_models.get( (app_label, model_name), model_name ) old_model_state = self.from_state.models[app_label, old_model_name] new_model_state = self.to_state.models[app_label, model_name] if old_model_state.managers != new_model_state.managers: self.add_operation( app_label, operations.AlterModelManagers( name=model_name, managers=new_model_state.managers, ), ) def arrange_for_graph(self, changes, graph, migration_name=None): """ Take a result from changes() and a MigrationGraph, and fix the names and dependencies of the changes so they extend the graph from the leaf nodes for each app. """ leaves = graph.leaf_nodes() name_map = {} for app_label, migrations in list(changes.items()): if not migrations: continue # Find the app label's current leaf node app_leaf = None for leaf in leaves: if leaf[0] == app_label: app_leaf = leaf break # Do they want an initial migration for this app? if app_leaf is None and not self.questioner.ask_initial(app_label): # They don't. for migration in migrations: name_map[(app_label, migration.name)] = (app_label, "__first__") del changes[app_label] continue # Work out the next number in the sequence if app_leaf is None: next_number = 1 else: next_number = (self.parse_number(app_leaf[1]) or 0) + 1 # Name each migration for i, migration in enumerate(migrations): if i == 0 and app_leaf: migration.dependencies.append(app_leaf) new_name_parts = ["%04i" % next_number] if migration_name: new_name_parts.append(migration_name) elif i == 0 and not app_leaf: new_name_parts.append("initial") else: new_name_parts.append(migration.suggest_name()[:100]) new_name = "_".join(new_name_parts) name_map[(app_label, migration.name)] = (app_label, new_name) next_number += 1 migration.name = new_name # Now fix dependencies for migrations in changes.values(): for migration in migrations: migration.dependencies = [ name_map.get(d, d) for d in migration.dependencies ] return changes def _trim_to_apps(self, changes, app_labels): """ Take changes from arrange_for_graph() and set of app labels, and return a modified set of changes which trims out as many migrations that are not in app_labels as possible. Note that some other migrations may still be present as they may be required dependencies. """ # Gather other app dependencies in a first pass app_dependencies = {} for app_label, migrations in changes.items(): for migration in migrations: for dep_app_label, name in migration.dependencies: app_dependencies.setdefault(app_label, set()).add(dep_app_label) required_apps = set(app_labels) # Keep resolving till there's no change old_required_apps = None while old_required_apps != required_apps: old_required_apps = set(required_apps) required_apps.update( *[app_dependencies.get(app_label, ()) for app_label in required_apps] ) # Remove all migrations that aren't needed for app_label in list(changes): if app_label not in required_apps: del changes[app_label] return changes @classmethod def parse_number(cls, name): """ Given a migration name, try to extract a number from the beginning of it. For a squashed migration such as '0001_squashed_0004…', return the second number. If no number is found, return None. """ if squashed_match := re.search(r".*_squashed_(\d+)", name): return int(squashed_match[1]) match = re.match(r"^\d+", name) if match: return int(match[0]) return None
9ca29d272a9dbae618a17ce1a60b025cdf8a45d4ba5e3270c64ad313ed68d28c
import copy import inspect import warnings from functools import partialmethod from itertools import chain import django from django.apps import apps from django.conf import settings from django.core import checks from django.core.exceptions import ( NON_FIELD_ERRORS, FieldDoesNotExist, FieldError, MultipleObjectsReturned, ObjectDoesNotExist, ValidationError, ) from django.db import ( DJANGO_VERSION_PICKLE_KEY, DatabaseError, connection, connections, router, transaction, ) from django.db.models import NOT_PROVIDED, ExpressionWrapper, IntegerField, Max, Value from django.db.models.constants import LOOKUP_SEP from django.db.models.constraints import CheckConstraint, UniqueConstraint from django.db.models.deletion import CASCADE, Collector from django.db.models.expressions import RawSQL from django.db.models.fields.related import ( ForeignObjectRel, OneToOneField, lazy_related_operation, resolve_relation, ) from django.db.models.functions import Coalesce from django.db.models.manager import Manager from django.db.models.options import Options from django.db.models.query import F, Q from django.db.models.signals import ( class_prepared, post_init, post_save, pre_init, pre_save, ) from django.db.models.utils import make_model_tuple from django.utils.encoding import force_str from django.utils.hashable import make_hashable from django.utils.text import capfirst, get_text_list from django.utils.translation import gettext_lazy as _ class Deferred: def __repr__(self): return "<Deferred field>" def __str__(self): return "<Deferred field>" DEFERRED = Deferred() def subclass_exception(name, bases, module, attached_to): """ Create exception subclass. Used by ModelBase below. The exception is created in a way that allows it to be pickled, assuming that the returned exception class will be added as an attribute to the 'attached_to' class. """ return type( name, bases, { "__module__": module, "__qualname__": "%s.%s" % (attached_to.__qualname__, name), }, ) def _has_contribute_to_class(value): # Only call contribute_to_class() if it's bound. return not inspect.isclass(value) and hasattr(value, "contribute_to_class") class ModelBase(type): """Metaclass for all models.""" def __new__(cls, name, bases, attrs, **kwargs): super_new = super().__new__ # Also ensure initialization is only performed for subclasses of Model # (excluding Model class itself). parents = [b for b in bases if isinstance(b, ModelBase)] if not parents: return super_new(cls, name, bases, attrs) # Create the class. module = attrs.pop("__module__") new_attrs = {"__module__": module} classcell = attrs.pop("__classcell__", None) if classcell is not None: new_attrs["__classcell__"] = classcell attr_meta = attrs.pop("Meta", None) # Pass all attrs without a (Django-specific) contribute_to_class() # method to type.__new__() so that they're properly initialized # (i.e. __set_name__()). contributable_attrs = {} for obj_name, obj in attrs.items(): if _has_contribute_to_class(obj): contributable_attrs[obj_name] = obj else: new_attrs[obj_name] = obj new_class = super_new(cls, name, bases, new_attrs, **kwargs) abstract = getattr(attr_meta, "abstract", False) meta = attr_meta or getattr(new_class, "Meta", None) base_meta = getattr(new_class, "_meta", None) app_label = None # Look for an application configuration to attach the model to. app_config = apps.get_containing_app_config(module) if getattr(meta, "app_label", None) is None: if app_config is None: if not abstract: raise RuntimeError( "Model class %s.%s doesn't declare an explicit " "app_label and isn't in an application in " "INSTALLED_APPS." % (module, name) ) else: app_label = app_config.label new_class.add_to_class("_meta", Options(meta, app_label)) if not abstract: new_class.add_to_class( "DoesNotExist", subclass_exception( "DoesNotExist", tuple( x.DoesNotExist for x in parents if hasattr(x, "_meta") and not x._meta.abstract ) or (ObjectDoesNotExist,), module, attached_to=new_class, ), ) new_class.add_to_class( "MultipleObjectsReturned", subclass_exception( "MultipleObjectsReturned", tuple( x.MultipleObjectsReturned for x in parents if hasattr(x, "_meta") and not x._meta.abstract ) or (MultipleObjectsReturned,), module, attached_to=new_class, ), ) if base_meta and not base_meta.abstract: # Non-abstract child classes inherit some attributes from their # non-abstract parent (unless an ABC comes before it in the # method resolution order). if not hasattr(meta, "ordering"): new_class._meta.ordering = base_meta.ordering if not hasattr(meta, "get_latest_by"): new_class._meta.get_latest_by = base_meta.get_latest_by is_proxy = new_class._meta.proxy # If the model is a proxy, ensure that the base class # hasn't been swapped out. if is_proxy and base_meta and base_meta.swapped: raise TypeError( "%s cannot proxy the swapped model '%s'." % (name, base_meta.swapped) ) # Add remaining attributes (those with a contribute_to_class() method) # to the class. for obj_name, obj in contributable_attrs.items(): new_class.add_to_class(obj_name, obj) # All the fields of any type declared on this model new_fields = chain( new_class._meta.local_fields, new_class._meta.local_many_to_many, new_class._meta.private_fields, ) field_names = {f.name for f in new_fields} # Basic setup for proxy models. if is_proxy: base = None for parent in [kls for kls in parents if hasattr(kls, "_meta")]: if parent._meta.abstract: if parent._meta.fields: raise TypeError( "Abstract base class containing model fields not " "permitted for proxy model '%s'." % name ) else: continue if base is None: base = parent elif parent._meta.concrete_model is not base._meta.concrete_model: raise TypeError( "Proxy model '%s' has more than one non-abstract model base " "class." % name ) if base is None: raise TypeError( "Proxy model '%s' has no non-abstract model base class." % name ) new_class._meta.setup_proxy(base) new_class._meta.concrete_model = base._meta.concrete_model else: new_class._meta.concrete_model = new_class # Collect the parent links for multi-table inheritance. parent_links = {} for base in reversed([new_class] + parents): # Conceptually equivalent to `if base is Model`. if not hasattr(base, "_meta"): continue # Skip concrete parent classes. if base != new_class and not base._meta.abstract: continue # Locate OneToOneField instances. for field in base._meta.local_fields: if isinstance(field, OneToOneField) and field.remote_field.parent_link: related = resolve_relation(new_class, field.remote_field.model) parent_links[make_model_tuple(related)] = field # Track fields inherited from base models. inherited_attributes = set() # Do the appropriate setup for any model parents. for base in new_class.mro(): if base not in parents or not hasattr(base, "_meta"): # Things without _meta aren't functional models, so they're # uninteresting parents. inherited_attributes.update(base.__dict__) continue parent_fields = base._meta.local_fields + base._meta.local_many_to_many if not base._meta.abstract: # Check for clashes between locally declared fields and those # on the base classes. for field in parent_fields: if field.name in field_names: raise FieldError( "Local field %r in class %r clashes with field of " "the same name from base class %r." % ( field.name, name, base.__name__, ) ) else: inherited_attributes.add(field.name) # Concrete classes... base = base._meta.concrete_model base_key = make_model_tuple(base) if base_key in parent_links: field = parent_links[base_key] elif not is_proxy: attr_name = "%s_ptr" % base._meta.model_name field = OneToOneField( base, on_delete=CASCADE, name=attr_name, auto_created=True, parent_link=True, ) if attr_name in field_names: raise FieldError( "Auto-generated field '%s' in class %r for " "parent_link to base class %r clashes with " "declared field of the same name." % ( attr_name, name, base.__name__, ) ) # Only add the ptr field if it's not already present; # e.g. migrations will already have it specified if not hasattr(new_class, attr_name): new_class.add_to_class(attr_name, field) else: field = None new_class._meta.parents[base] = field else: base_parents = base._meta.parents.copy() # Add fields from abstract base class if it wasn't overridden. for field in parent_fields: if ( field.name not in field_names and field.name not in new_class.__dict__ and field.name not in inherited_attributes ): new_field = copy.deepcopy(field) new_class.add_to_class(field.name, new_field) # Replace parent links defined on this base by the new # field. It will be appropriately resolved if required. if field.one_to_one: for parent, parent_link in base_parents.items(): if field == parent_link: base_parents[parent] = new_field # Pass any non-abstract parent classes onto child. new_class._meta.parents.update(base_parents) # Inherit private fields (like GenericForeignKey) from the parent # class for field in base._meta.private_fields: if field.name in field_names: if not base._meta.abstract: raise FieldError( "Local field %r in class %r clashes with field of " "the same name from base class %r." % ( field.name, name, base.__name__, ) ) else: field = copy.deepcopy(field) if not base._meta.abstract: field.mti_inherited = True new_class.add_to_class(field.name, field) # Copy indexes so that index names are unique when models extend an # abstract model. new_class._meta.indexes = [ copy.deepcopy(idx) for idx in new_class._meta.indexes ] if abstract: # Abstract base models can't be instantiated and don't appear in # the list of models for an app. We do the final setup for them a # little differently from normal models. attr_meta.abstract = False new_class.Meta = attr_meta return new_class new_class._prepare() new_class._meta.apps.register_model(new_class._meta.app_label, new_class) return new_class def add_to_class(cls, name, value): if _has_contribute_to_class(value): value.contribute_to_class(cls, name) else: setattr(cls, name, value) def _prepare(cls): """Create some methods once self._meta has been populated.""" opts = cls._meta opts._prepare(cls) if opts.order_with_respect_to: cls.get_next_in_order = partialmethod( cls._get_next_or_previous_in_order, is_next=True ) cls.get_previous_in_order = partialmethod( cls._get_next_or_previous_in_order, is_next=False ) # Defer creating accessors on the foreign class until it has been # created and registered. If remote_field is None, we're ordering # with respect to a GenericForeignKey and don't know what the # foreign class is - we'll add those accessors later in # contribute_to_class(). if opts.order_with_respect_to.remote_field: wrt = opts.order_with_respect_to remote = wrt.remote_field.model lazy_related_operation(make_foreign_order_accessors, cls, remote) # Give the class a docstring -- its definition. if cls.__doc__ is None: cls.__doc__ = "%s(%s)" % ( cls.__name__, ", ".join(f.name for f in opts.fields), ) get_absolute_url_override = settings.ABSOLUTE_URL_OVERRIDES.get( opts.label_lower ) if get_absolute_url_override: setattr(cls, "get_absolute_url", get_absolute_url_override) if not opts.managers: if any(f.name == "objects" for f in opts.fields): raise ValueError( "Model %s must specify a custom Manager, because it has a " "field named 'objects'." % cls.__name__ ) manager = Manager() manager.auto_created = True cls.add_to_class("objects", manager) # Set the name of _meta.indexes. This can't be done in # Options.contribute_to_class() because fields haven't been added to # the model at that point. for index in cls._meta.indexes: if not index.name: index.set_name_with_model(cls) class_prepared.send(sender=cls) @property def _base_manager(cls): return cls._meta.base_manager @property def _default_manager(cls): return cls._meta.default_manager class ModelStateCacheDescriptor: """ Upon first access, replace itself with an empty dictionary on the instance. """ def __set_name__(self, owner, name): self.attribute_name = name def __get__(self, instance, cls=None): if instance is None: return self res = instance.__dict__[self.attribute_name] = {} return res class ModelState: """Store model instance state.""" db = None # If true, uniqueness validation checks will consider this a new, unsaved # object. Necessary for correct validation of new instances of objects with # explicit (non-auto) PKs. This impacts validation only; it has no effect # on the actual save. adding = True fields_cache = ModelStateCacheDescriptor() related_managers_cache = ModelStateCacheDescriptor() def __getstate__(self): state = self.__dict__.copy() if "fields_cache" in state: state["fields_cache"] = self.fields_cache.copy() # Manager instances stored in related_managers_cache won't necessarily # be deserializable if they were dynamically created via an inner # scope, e.g. create_forward_many_to_many_manager() and # create_generic_related_manager(). if "related_managers_cache" in state: state["related_managers_cache"] = {} return state class Model(metaclass=ModelBase): def __init__(self, *args, **kwargs): # Alias some things as locals to avoid repeat global lookups cls = self.__class__ opts = self._meta _setattr = setattr _DEFERRED = DEFERRED if opts.abstract: raise TypeError("Abstract models cannot be instantiated.") pre_init.send(sender=cls, args=args, kwargs=kwargs) # Set up the storage for instance state self._state = ModelState() # There is a rather weird disparity here; if kwargs, it's set, then args # overrides it. It should be one or the other; don't duplicate the work # The reason for the kwargs check is that standard iterator passes in by # args, and instantiation for iteration is 33% faster. if len(args) > len(opts.concrete_fields): # Daft, but matches old exception sans the err msg. raise IndexError("Number of args exceeds number of fields") if not kwargs: fields_iter = iter(opts.concrete_fields) # The ordering of the zip calls matter - zip throws StopIteration # when an iter throws it. So if the first iter throws it, the second # is *not* consumed. We rely on this, so don't change the order # without changing the logic. for val, field in zip(args, fields_iter): if val is _DEFERRED: continue _setattr(self, field.attname, val) else: # Slower, kwargs-ready version. fields_iter = iter(opts.fields) for val, field in zip(args, fields_iter): if val is _DEFERRED: continue _setattr(self, field.attname, val) if kwargs.pop(field.name, NOT_PROVIDED) is not NOT_PROVIDED: raise TypeError( f"{cls.__qualname__}() got both positional and " f"keyword arguments for field '{field.name}'." ) # Now we're left with the unprocessed fields that *must* come from # keywords, or default. for field in fields_iter: is_related_object = False # Virtual field if field.attname not in kwargs and field.column is None: continue if kwargs: if isinstance(field.remote_field, ForeignObjectRel): try: # Assume object instance was passed in. rel_obj = kwargs.pop(field.name) is_related_object = True except KeyError: try: # Object instance wasn't passed in -- must be an ID. val = kwargs.pop(field.attname) except KeyError: val = field.get_default() else: try: val = kwargs.pop(field.attname) except KeyError: # This is done with an exception rather than the # default argument on pop because we don't want # get_default() to be evaluated, and then not used. # Refs #12057. val = field.get_default() else: val = field.get_default() if is_related_object: # If we are passed a related instance, set it using the # field.name instead of field.attname (e.g. "user" instead of # "user_id") so that the object gets properly cached (and type # checked) by the RelatedObjectDescriptor. if rel_obj is not _DEFERRED: _setattr(self, field.name, rel_obj) else: if val is not _DEFERRED: _setattr(self, field.attname, val) if kwargs: property_names = opts._property_names unexpected = () for prop, value in kwargs.items(): # Any remaining kwargs must correspond to properties or virtual # fields. if prop in property_names: if value is not _DEFERRED: _setattr(self, prop, value) else: try: opts.get_field(prop) except FieldDoesNotExist: unexpected += (prop,) else: if value is not _DEFERRED: _setattr(self, prop, value) if unexpected: unexpected_names = ", ".join(repr(n) for n in unexpected) raise TypeError( f"{cls.__name__}() got unexpected keyword arguments: " f"{unexpected_names}" ) super().__init__() post_init.send(sender=cls, instance=self) @classmethod def from_db(cls, db, field_names, values): if len(values) != len(cls._meta.concrete_fields): values_iter = iter(values) values = [ next(values_iter) if f.attname in field_names else DEFERRED for f in cls._meta.concrete_fields ] new = cls(*values) new._state.adding = False new._state.db = db return new def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def __str__(self): return "%s object (%s)" % (self.__class__.__name__, self.pk) def __eq__(self, other): if not isinstance(other, Model): return NotImplemented if self._meta.concrete_model != other._meta.concrete_model: return False my_pk = self.pk if my_pk is None: return self is other return my_pk == other.pk def __hash__(self): if self.pk is None: raise TypeError("Model instances without primary key value are unhashable") return hash(self.pk) def __reduce__(self): data = self.__getstate__() data[DJANGO_VERSION_PICKLE_KEY] = django.__version__ class_id = self._meta.app_label, self._meta.object_name return model_unpickle, (class_id,), data def __getstate__(self): """Hook to allow choosing the attributes to pickle.""" state = self.__dict__.copy() state["_state"] = copy.copy(state["_state"]) # memoryview cannot be pickled, so cast it to bytes and store # separately. _memoryview_attrs = [] for attr, value in state.items(): if isinstance(value, memoryview): _memoryview_attrs.append((attr, bytes(value))) if _memoryview_attrs: state["_memoryview_attrs"] = _memoryview_attrs for attr, value in _memoryview_attrs: state.pop(attr) return state def __setstate__(self, state): pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY) if pickled_version: if pickled_version != django.__version__: warnings.warn( "Pickled model instance's Django version %s does not " "match the current version %s." % (pickled_version, django.__version__), RuntimeWarning, stacklevel=2, ) else: warnings.warn( "Pickled model instance's Django version is not specified.", RuntimeWarning, stacklevel=2, ) if "_memoryview_attrs" in state: for attr, value in state.pop("_memoryview_attrs"): state[attr] = memoryview(value) self.__dict__.update(state) def _get_pk_val(self, meta=None): meta = meta or self._meta return getattr(self, meta.pk.attname) def _set_pk_val(self, value): for parent_link in self._meta.parents.values(): if parent_link and parent_link != self._meta.pk: setattr(self, parent_link.target_field.attname, value) return setattr(self, self._meta.pk.attname, value) pk = property(_get_pk_val, _set_pk_val) def get_deferred_fields(self): """ Return a set containing names of deferred fields for this instance. """ return { f.attname for f in self._meta.concrete_fields if f.attname not in self.__dict__ } def refresh_from_db(self, using=None, fields=None): """ Reload field values from the database. By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn't loaded from any database. The using parameter will override the default. Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded. When accessing deferred fields of an instance, the deferred loading of the field will call this method. """ if fields is None: self._prefetched_objects_cache = {} else: prefetched_objects_cache = getattr(self, "_prefetched_objects_cache", ()) for field in fields: if field in prefetched_objects_cache: del prefetched_objects_cache[field] fields.remove(field) if not fields: return if any(LOOKUP_SEP in f for f in fields): raise ValueError( 'Found "%s" in fields argument. Relations and transforms ' "are not allowed in fields." % LOOKUP_SEP ) hints = {"instance": self} db_instance_qs = self.__class__._base_manager.db_manager( using, hints=hints ).filter(pk=self.pk) # Use provided fields, if not set then reload all non-deferred fields. deferred_fields = self.get_deferred_fields() if fields is not None: fields = list(fields) db_instance_qs = db_instance_qs.only(*fields) elif deferred_fields: fields = [ f.attname for f in self._meta.concrete_fields if f.attname not in deferred_fields ] db_instance_qs = db_instance_qs.only(*fields) db_instance = db_instance_qs.get() non_loaded_fields = db_instance.get_deferred_fields() for field in self._meta.concrete_fields: if field.attname in non_loaded_fields: # This field wasn't refreshed - skip ahead. continue setattr(self, field.attname, getattr(db_instance, field.attname)) # Clear cached foreign keys. if field.is_relation and field.is_cached(self): field.delete_cached_value(self) # Clear cached relations. for field in self._meta.related_objects: if field.is_cached(self): field.delete_cached_value(self) self._state.db = db_instance._state.db def serializable_value(self, field_name): """ Return the value of the field name for this instance. If the field is a foreign key, return the id value instead of the object. If there's no Field object with this name on the model, return the model attribute's value. Used to serialize a field's value (in the serializer, or form output, for example). Normally, you would just access the attribute directly and not use this method. """ try: field = self._meta.get_field(field_name) except FieldDoesNotExist: return getattr(self, field_name) return getattr(self, field.attname) def save( self, force_insert=False, force_update=False, using=None, update_fields=None ): """ Save the current instance. Override this in a subclass if you want to control the saving process. The 'force_insert' and 'force_update' parameters can be used to insist that the "save" must be an SQL insert or update (or equivalent for non-SQL backends), respectively. Normally, they should not be set. """ self._prepare_related_fields_for_save(operation_name="save") using = using or router.db_for_write(self.__class__, instance=self) if force_insert and (force_update or update_fields): raise ValueError("Cannot force both insert and updating in model saving.") deferred_fields = self.get_deferred_fields() if update_fields is not None: # If update_fields is empty, skip the save. We do also check for # no-op saves later on for inheritance cases. This bailout is # still needed for skipping signal sending. if not update_fields: return update_fields = frozenset(update_fields) field_names = set() for field in self._meta.concrete_fields: if not field.primary_key: field_names.add(field.name) if field.name != field.attname: field_names.add(field.attname) non_model_fields = update_fields.difference(field_names) if non_model_fields: raise ValueError( "The following fields do not exist in this model, are m2m " "fields, or are non-concrete fields: %s" % ", ".join(non_model_fields) ) # If saving to the same database, and this model is deferred, then # automatically do an "update_fields" save on the loaded fields. elif not force_insert and deferred_fields and using == self._state.db: field_names = set() for field in self._meta.concrete_fields: if not field.primary_key and not hasattr(field, "through"): field_names.add(field.attname) loaded_fields = field_names.difference(deferred_fields) if loaded_fields: update_fields = frozenset(loaded_fields) self.save_base( using=using, force_insert=force_insert, force_update=force_update, update_fields=update_fields, ) save.alters_data = True def save_base( self, raw=False, force_insert=False, force_update=False, using=None, update_fields=None, ): """ Handle the parts of saving which should be done only once per save, yet need to be done in raw saves, too. This includes some sanity checks and signal sending. The 'raw' argument is telling save_base not to save any parent models and not to do any changes to the values before save. This is used by fixture loading. """ using = using or router.db_for_write(self.__class__, instance=self) assert not (force_insert and (force_update or update_fields)) assert update_fields is None or update_fields cls = origin = self.__class__ # Skip proxies, but keep the origin as the proxy model. if cls._meta.proxy: cls = cls._meta.concrete_model meta = cls._meta if not meta.auto_created: pre_save.send( sender=origin, instance=self, raw=raw, using=using, update_fields=update_fields, ) # A transaction isn't needed if one query is issued. if meta.parents: context_manager = transaction.atomic(using=using, savepoint=False) else: context_manager = transaction.mark_for_rollback_on_error(using=using) with context_manager: parent_inserted = False if not raw: parent_inserted = self._save_parents(cls, using, update_fields) updated = self._save_table( raw, cls, force_insert or parent_inserted, force_update, using, update_fields, ) # Store the database on which the object was saved self._state.db = using # Once saved, this is no longer a to-be-added instance. self._state.adding = False # Signal that the save is complete if not meta.auto_created: post_save.send( sender=origin, instance=self, created=(not updated), update_fields=update_fields, raw=raw, using=using, ) save_base.alters_data = True def _save_parents(self, cls, using, update_fields): """Save all the parents of cls using values from self.""" meta = cls._meta inserted = False for parent, field in meta.parents.items(): # Make sure the link fields are synced between parent and self. if ( field and getattr(self, parent._meta.pk.attname) is None and getattr(self, field.attname) is not None ): setattr(self, parent._meta.pk.attname, getattr(self, field.attname)) parent_inserted = self._save_parents( cls=parent, using=using, update_fields=update_fields ) updated = self._save_table( cls=parent, using=using, update_fields=update_fields, force_insert=parent_inserted, ) if not updated: inserted = True # Set the parent's PK value to self. if field: setattr(self, field.attname, self._get_pk_val(parent._meta)) # Since we didn't have an instance of the parent handy set # attname directly, bypassing the descriptor. Invalidate # the related object cache, in case it's been accidentally # populated. A fresh instance will be re-built from the # database if necessary. if field.is_cached(self): field.delete_cached_value(self) return inserted def _save_table( self, raw=False, cls=None, force_insert=False, force_update=False, using=None, update_fields=None, ): """ Do the heavy-lifting involved in saving. Update or insert the data for a single table. """ meta = cls._meta non_pks = [f for f in meta.local_concrete_fields if not f.primary_key] if update_fields: non_pks = [ f for f in non_pks if f.name in update_fields or f.attname in update_fields ] pk_val = self._get_pk_val(meta) if pk_val is None: pk_val = meta.pk.get_pk_value_on_save(self) setattr(self, meta.pk.attname, pk_val) pk_set = pk_val is not None if not pk_set and (force_update or update_fields): raise ValueError("Cannot force an update in save() with no primary key.") updated = False # Skip an UPDATE when adding an instance and primary key has a default. if ( not raw and not force_insert and self._state.adding and meta.pk.default and meta.pk.default is not NOT_PROVIDED ): force_insert = True # If possible, try an UPDATE. If that doesn't update anything, do an INSERT. if pk_set and not force_insert: base_qs = cls._base_manager.using(using) values = [ ( f, None, (getattr(self, f.attname) if raw else f.pre_save(self, False)), ) for f in non_pks ] forced_update = update_fields or force_update updated = self._do_update( base_qs, using, pk_val, values, update_fields, forced_update ) if force_update and not updated: raise DatabaseError("Forced update did not affect any rows.") if update_fields and not updated: raise DatabaseError("Save with update_fields did not affect any rows.") if not updated: if meta.order_with_respect_to: # If this is a model with an order_with_respect_to # autopopulate the _order field field = meta.order_with_respect_to filter_args = field.get_filter_kwargs_for_object(self) self._order = ( cls._base_manager.using(using) .filter(**filter_args) .aggregate( _order__max=Coalesce( ExpressionWrapper( Max("_order") + Value(1), output_field=IntegerField() ), Value(0), ), )["_order__max"] ) fields = meta.local_concrete_fields if not pk_set: fields = [f for f in fields if f is not meta.auto_field] returning_fields = meta.db_returning_fields results = self._do_insert( cls._base_manager, using, fields, returning_fields, raw ) if results: for value, field in zip(results[0], returning_fields): setattr(self, field.attname, value) return updated def _do_update(self, base_qs, using, pk_val, values, update_fields, forced_update): """ Try to update the model. Return True if the model was updated (if an update query was done and a matching row was found in the DB). """ filtered = base_qs.filter(pk=pk_val) if not values: # We can end up here when saving a model in inheritance chain where # update_fields doesn't target any field in current model. In that # case we just say the update succeeded. Another case ending up here # is a model with just PK - in that case check that the PK still # exists. return update_fields is not None or filtered.exists() if self._meta.select_on_save and not forced_update: return ( filtered.exists() and # It may happen that the object is deleted from the DB right after # this check, causing the subsequent UPDATE to return zero matching # rows. The same result can occur in some rare cases when the # database returns zero despite the UPDATE being executed # successfully (a row is matched and updated). In order to # distinguish these two cases, the object's existence in the # database is again checked for if the UPDATE query returns 0. (filtered._update(values) > 0 or filtered.exists()) ) return filtered._update(values) > 0 def _do_insert(self, manager, using, fields, returning_fields, raw): """ Do an INSERT. If returning_fields is defined then this method should return the newly created data for the model. """ return manager._insert( [self], fields=fields, returning_fields=returning_fields, using=using, raw=raw, ) def _prepare_related_fields_for_save(self, operation_name, fields=None): # Ensure that a model instance without a PK hasn't been assigned to # a ForeignKey, GenericForeignKey or OneToOneField on this model. If # the field is nullable, allowing the save would result in silent data # loss. for field in self._meta.concrete_fields: if fields and field not in fields: continue # If the related field isn't cached, then an instance hasn't been # assigned and there's no need to worry about this check. if field.is_relation and field.is_cached(self): obj = getattr(self, field.name, None) if not obj: continue # A pk may have been assigned manually to a model instance not # saved to the database (or auto-generated in a case like # UUIDField), but we allow the save to proceed and rely on the # database to raise an IntegrityError if applicable. If # constraints aren't supported by the database, there's the # unavoidable risk of data corruption. if obj.pk is None: # Remove the object from a related instance cache. if not field.remote_field.multiple: field.remote_field.delete_cached_value(obj) raise ValueError( "%s() prohibited to prevent data loss due to unsaved " "related object '%s'." % (operation_name, field.name) ) elif getattr(self, field.attname) in field.empty_values: # Set related object if it has been saved after an # assignment. setattr(self, field.name, obj) # If the relationship's pk/to_field was changed, clear the # cached relationship. if getattr(obj, field.target_field.attname) != getattr( self, field.attname ): field.delete_cached_value(self) # GenericForeignKeys are private. for field in self._meta.private_fields: if fields and field not in fields: continue if ( field.is_relation and field.is_cached(self) and hasattr(field, "fk_field") ): obj = field.get_cached_value(self, default=None) if obj and obj.pk is None: raise ValueError( f"{operation_name}() prohibited to prevent data loss due to " f"unsaved related object '{field.name}'." ) def delete(self, using=None, keep_parents=False): if self.pk is None: raise ValueError( "%s object can't be deleted because its %s attribute is set " "to None." % (self._meta.object_name, self._meta.pk.attname) ) using = using or router.db_for_write(self.__class__, instance=self) collector = Collector(using=using, origin=self) collector.collect([self], keep_parents=keep_parents) return collector.delete() delete.alters_data = True def _get_FIELD_display(self, field): value = getattr(self, field.attname) choices_dict = dict(make_hashable(field.flatchoices)) # force_str() to coerce lazy strings. return force_str( choices_dict.get(make_hashable(value), value), strings_only=True ) def _get_next_or_previous_by_FIELD(self, field, is_next, **kwargs): if not self.pk: raise ValueError("get_next/get_previous cannot be used on unsaved objects.") op = "gt" if is_next else "lt" order = "" if is_next else "-" param = getattr(self, field.attname) q = Q((field.name, param), (f"pk__{op}", self.pk), _connector=Q.AND) q = Q(q, (f"{field.name}__{op}", param), _connector=Q.OR) qs = ( self.__class__._default_manager.using(self._state.db) .filter(**kwargs) .filter(q) .order_by("%s%s" % (order, field.name), "%spk" % order) ) try: return qs[0] except IndexError: raise self.DoesNotExist( "%s matching query does not exist." % self.__class__._meta.object_name ) def _get_next_or_previous_in_order(self, is_next): cachename = "__%s_order_cache" % is_next if not hasattr(self, cachename): op = "gt" if is_next else "lt" order = "_order" if is_next else "-_order" order_field = self._meta.order_with_respect_to filter_args = order_field.get_filter_kwargs_for_object(self) obj = ( self.__class__._default_manager.filter(**filter_args) .filter( **{ "_order__%s" % op: self.__class__._default_manager.values("_order").filter( **{self._meta.pk.name: self.pk} ) } ) .order_by(order)[:1] .get() ) setattr(self, cachename, obj) return getattr(self, cachename) def _get_field_value_map(self, meta, exclude=None): if exclude is None: exclude = set() meta = meta or self._meta return { field.name: Value(getattr(self, field.attname), field) for field in meta.local_concrete_fields if field.name not in exclude } def prepare_database_save(self, field): if self.pk is None: raise ValueError( "Unsaved model instance %r cannot be used in an ORM query." % self ) return getattr(self, field.remote_field.get_related_field().attname) def clean(self): """ Hook for doing any extra model-wide validation after clean() has been called on every field by self.clean_fields. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS. """ pass def validate_unique(self, exclude=None): """ Check unique constraints on the model and raise ValidationError if any failed. """ unique_checks, date_checks = self._get_unique_checks(exclude=exclude) errors = self._perform_unique_checks(unique_checks) date_errors = self._perform_date_checks(date_checks) for k, v in date_errors.items(): errors.setdefault(k, []).extend(v) if errors: raise ValidationError(errors) def _get_unique_checks(self, exclude=None, include_meta_constraints=False): """ Return a list of checks to perform. Since validate_unique() could be called from a ModelForm, some fields may have been excluded; we can't perform a unique check on a model that is missing fields involved in that check. Fields that did not validate should also be excluded, but they need to be passed in via the exclude argument. """ if exclude is None: exclude = set() unique_checks = [] unique_togethers = [(self.__class__, self._meta.unique_together)] constraints = [] if include_meta_constraints: constraints = [(self.__class__, self._meta.total_unique_constraints)] for parent_class in self._meta.get_parent_list(): if parent_class._meta.unique_together: unique_togethers.append( (parent_class, parent_class._meta.unique_together) ) if include_meta_constraints and parent_class._meta.total_unique_constraints: constraints.append( (parent_class, parent_class._meta.total_unique_constraints) ) for model_class, unique_together in unique_togethers: for check in unique_together: if not any(name in exclude for name in check): # Add the check if the field isn't excluded. unique_checks.append((model_class, tuple(check))) if include_meta_constraints: for model_class, model_constraints in constraints: for constraint in model_constraints: if not any(name in exclude for name in constraint.fields): unique_checks.append((model_class, constraint.fields)) # These are checks for the unique_for_<date/year/month>. date_checks = [] # Gather a list of checks for fields declared as unique and add them to # the list of checks. fields_with_class = [(self.__class__, self._meta.local_fields)] for parent_class in self._meta.get_parent_list(): fields_with_class.append((parent_class, parent_class._meta.local_fields)) for model_class, fields in fields_with_class: for f in fields: name = f.name if name in exclude: continue if f.unique: unique_checks.append((model_class, (name,))) if f.unique_for_date and f.unique_for_date not in exclude: date_checks.append((model_class, "date", name, f.unique_for_date)) if f.unique_for_year and f.unique_for_year not in exclude: date_checks.append((model_class, "year", name, f.unique_for_year)) if f.unique_for_month and f.unique_for_month not in exclude: date_checks.append((model_class, "month", name, f.unique_for_month)) return unique_checks, date_checks def _perform_unique_checks(self, unique_checks): errors = {} for model_class, unique_check in unique_checks: # Try to look up an existing object with the same values as this # object's values for all the unique field. lookup_kwargs = {} for field_name in unique_check: f = self._meta.get_field(field_name) lookup_value = getattr(self, f.attname) # TODO: Handle multiple backends with different feature flags. if lookup_value is None or ( lookup_value == "" and connection.features.interprets_empty_strings_as_nulls ): # no value, skip the lookup continue if f.primary_key and not self._state.adding: # no need to check for unique primary key when editing continue lookup_kwargs[str(field_name)] = lookup_value # some fields were skipped, no reason to do the check if len(unique_check) != len(lookup_kwargs): continue qs = model_class._default_manager.filter(**lookup_kwargs) # Exclude the current object from the query if we are editing an # instance (as opposed to creating a new one) # Note that we need to use the pk as defined by model_class, not # self.pk. These can be different fields because model inheritance # allows single model to have effectively multiple primary keys. # Refs #17615. model_class_pk = self._get_pk_val(model_class._meta) if not self._state.adding and model_class_pk is not None: qs = qs.exclude(pk=model_class_pk) if qs.exists(): if len(unique_check) == 1: key = unique_check[0] else: key = NON_FIELD_ERRORS errors.setdefault(key, []).append( self.unique_error_message(model_class, unique_check) ) return errors def _perform_date_checks(self, date_checks): errors = {} for model_class, lookup_type, field, unique_for in date_checks: lookup_kwargs = {} # there's a ticket to add a date lookup, we can remove this special # case if that makes it's way in date = getattr(self, unique_for) if date is None: continue if lookup_type == "date": lookup_kwargs["%s__day" % unique_for] = date.day lookup_kwargs["%s__month" % unique_for] = date.month lookup_kwargs["%s__year" % unique_for] = date.year else: lookup_kwargs["%s__%s" % (unique_for, lookup_type)] = getattr( date, lookup_type ) lookup_kwargs[field] = getattr(self, field) qs = model_class._default_manager.filter(**lookup_kwargs) # Exclude the current object from the query if we are editing an # instance (as opposed to creating a new one) if not self._state.adding and self.pk is not None: qs = qs.exclude(pk=self.pk) if qs.exists(): errors.setdefault(field, []).append( self.date_error_message(lookup_type, field, unique_for) ) return errors def date_error_message(self, lookup_type, field_name, unique_for): opts = self._meta field = opts.get_field(field_name) return ValidationError( message=field.error_messages["unique_for_date"], code="unique_for_date", params={ "model": self, "model_name": capfirst(opts.verbose_name), "lookup_type": lookup_type, "field": field_name, "field_label": capfirst(field.verbose_name), "date_field": unique_for, "date_field_label": capfirst(opts.get_field(unique_for).verbose_name), }, ) def unique_error_message(self, model_class, unique_check): opts = model_class._meta params = { "model": self, "model_class": model_class, "model_name": capfirst(opts.verbose_name), "unique_check": unique_check, } # A unique field if len(unique_check) == 1: field = opts.get_field(unique_check[0]) params["field_label"] = capfirst(field.verbose_name) return ValidationError( message=field.error_messages["unique"], code="unique", params=params, ) # unique_together else: field_labels = [ capfirst(opts.get_field(f).verbose_name) for f in unique_check ] params["field_labels"] = get_text_list(field_labels, _("and")) return ValidationError( message=_("%(model_name)s with this %(field_labels)s already exists."), code="unique_together", params=params, ) def get_constraints(self): constraints = [(self.__class__, self._meta.constraints)] for parent_class in self._meta.get_parent_list(): if parent_class._meta.constraints: constraints.append((parent_class, parent_class._meta.constraints)) return constraints def validate_constraints(self, exclude=None): constraints = self.get_constraints() using = router.db_for_write(self.__class__, instance=self) errors = {} for model_class, model_constraints in constraints: for constraint in model_constraints: try: constraint.validate(model_class, self, exclude=exclude, using=using) except ValidationError as e: if e.code == "unique" and len(constraint.fields) == 1: errors.setdefault(constraint.fields[0], []).append(e) else: errors = e.update_error_dict(errors) if errors: raise ValidationError(errors) def full_clean(self, exclude=None, validate_unique=True, validate_constraints=True): """ Call clean_fields(), clean(), validate_unique(), and validate_constraints() on the model. Raise a ValidationError for any errors that occur. """ errors = {} if exclude is None: exclude = set() else: exclude = set(exclude) try: self.clean_fields(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) # Form.clean() is run even if other validation fails, so do the # same with Model.clean() for consistency. try: self.clean() except ValidationError as e: errors = e.update_error_dict(errors) # Run unique checks, but only for fields that passed validation. if validate_unique: for name in errors: if name != NON_FIELD_ERRORS and name not in exclude: exclude.add(name) try: self.validate_unique(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) # Run constraints checks, but only for fields that passed validation. if validate_constraints: for name in errors: if name != NON_FIELD_ERRORS and name not in exclude: exclude.add(name) try: self.validate_constraints(exclude=exclude) except ValidationError as e: errors = e.update_error_dict(errors) if errors: raise ValidationError(errors) def clean_fields(self, exclude=None): """ Clean all fields and raise a ValidationError containing a dict of all validation errors if any occur. """ if exclude is None: exclude = set() errors = {} for f in self._meta.fields: if f.name in exclude: continue # Skip validation for empty fields with blank=True. The developer # is responsible for making sure they have a valid value. raw_value = getattr(self, f.attname) if f.blank and raw_value in f.empty_values: continue try: setattr(self, f.attname, f.clean(raw_value, self)) except ValidationError as e: errors[f.name] = e.error_list if errors: raise ValidationError(errors) @classmethod def check(cls, **kwargs): errors = [ *cls._check_swappable(), *cls._check_model(), *cls._check_managers(**kwargs), ] if not cls._meta.swapped: databases = kwargs.get("databases") or [] errors += [ *cls._check_fields(**kwargs), *cls._check_m2m_through_same_relationship(), *cls._check_long_column_names(databases), ] clash_errors = ( *cls._check_id_field(), *cls._check_field_name_clashes(), *cls._check_model_name_db_lookup_clashes(), *cls._check_property_name_related_field_accessor_clashes(), *cls._check_single_primary_key(), ) errors.extend(clash_errors) # If there are field name clashes, hide consequent column name # clashes. if not clash_errors: errors.extend(cls._check_column_name_clashes()) errors += [ *cls._check_index_together(), *cls._check_unique_together(), *cls._check_indexes(databases), *cls._check_ordering(), *cls._check_constraints(databases), *cls._check_default_pk(), ] return errors @classmethod def _check_default_pk(cls): if ( not cls._meta.abstract and cls._meta.pk.auto_created and # Inherited PKs are checked in parents models. not ( isinstance(cls._meta.pk, OneToOneField) and cls._meta.pk.remote_field.parent_link ) and not settings.is_overridden("DEFAULT_AUTO_FIELD") and cls._meta.app_config and not cls._meta.app_config._is_default_auto_field_overridden ): return [ checks.Warning( f"Auto-created primary key used when not defining a " f"primary key type, by default " f"'{settings.DEFAULT_AUTO_FIELD}'.", hint=( f"Configure the DEFAULT_AUTO_FIELD setting or the " f"{cls._meta.app_config.__class__.__qualname__}." f"default_auto_field attribute to point to a subclass " f"of AutoField, e.g. 'django.db.models.BigAutoField'." ), obj=cls, id="models.W042", ), ] return [] @classmethod def _check_swappable(cls): """Check if the swapped model exists.""" errors = [] if cls._meta.swapped: try: apps.get_model(cls._meta.swapped) except ValueError: errors.append( checks.Error( "'%s' is not of the form 'app_label.app_name'." % cls._meta.swappable, id="models.E001", ) ) except LookupError: app_label, model_name = cls._meta.swapped.split(".") errors.append( checks.Error( "'%s' references '%s.%s', which has not been " "installed, or is abstract." % (cls._meta.swappable, app_label, model_name), id="models.E002", ) ) return errors @classmethod def _check_model(cls): errors = [] if cls._meta.proxy: if cls._meta.local_fields or cls._meta.local_many_to_many: errors.append( checks.Error( "Proxy model '%s' contains model fields." % cls.__name__, id="models.E017", ) ) return errors @classmethod def _check_managers(cls, **kwargs): """Perform all manager checks.""" errors = [] for manager in cls._meta.managers: errors.extend(manager.check(**kwargs)) return errors @classmethod def _check_fields(cls, **kwargs): """Perform all field checks.""" errors = [] for field in cls._meta.local_fields: errors.extend(field.check(**kwargs)) for field in cls._meta.local_many_to_many: errors.extend(field.check(from_model=cls, **kwargs)) return errors @classmethod def _check_m2m_through_same_relationship(cls): """Check if no relationship model is used by more than one m2m field.""" errors = [] seen_intermediary_signatures = [] fields = cls._meta.local_many_to_many # Skip when the target model wasn't found. fields = (f for f in fields if isinstance(f.remote_field.model, ModelBase)) # Skip when the relationship model wasn't found. fields = (f for f in fields if isinstance(f.remote_field.through, ModelBase)) for f in fields: signature = ( f.remote_field.model, cls, f.remote_field.through, f.remote_field.through_fields, ) if signature in seen_intermediary_signatures: errors.append( checks.Error( "The model has two identical many-to-many relations " "through the intermediate model '%s'." % f.remote_field.through._meta.label, obj=cls, id="models.E003", ) ) else: seen_intermediary_signatures.append(signature) return errors @classmethod def _check_id_field(cls): """Check if `id` field is a primary key.""" fields = [ f for f in cls._meta.local_fields if f.name == "id" and f != cls._meta.pk ] # fields is empty or consists of the invalid "id" field if fields and not fields[0].primary_key and cls._meta.pk.name == "id": return [ checks.Error( "'id' can only be used as a field name if the field also " "sets 'primary_key=True'.", obj=cls, id="models.E004", ) ] else: return [] @classmethod def _check_field_name_clashes(cls): """Forbid field shadowing in multi-table inheritance.""" errors = [] used_fields = {} # name or attname -> field # Check that multi-inheritance doesn't cause field name shadowing. for parent in cls._meta.get_parent_list(): for f in parent._meta.local_fields: clash = used_fields.get(f.name) or used_fields.get(f.attname) or None if clash: errors.append( checks.Error( "The field '%s' from parent model " "'%s' clashes with the field '%s' " "from parent model '%s'." % (clash.name, clash.model._meta, f.name, f.model._meta), obj=cls, id="models.E005", ) ) used_fields[f.name] = f used_fields[f.attname] = f # Check that fields defined in the model don't clash with fields from # parents, including auto-generated fields like multi-table inheritance # child accessors. for parent in cls._meta.get_parent_list(): for f in parent._meta.get_fields(): if f not in used_fields: used_fields[f.name] = f for f in cls._meta.local_fields: clash = used_fields.get(f.name) or used_fields.get(f.attname) or None # Note that we may detect clash between user-defined non-unique # field "id" and automatically added unique field "id", both # defined at the same model. This special case is considered in # _check_id_field and here we ignore it. id_conflict = ( f.name == "id" and clash and clash.name == "id" and clash.model == cls ) if clash and not id_conflict: errors.append( checks.Error( "The field '%s' clashes with the field '%s' " "from model '%s'." % (f.name, clash.name, clash.model._meta), obj=f, id="models.E006", ) ) used_fields[f.name] = f used_fields[f.attname] = f return errors @classmethod def _check_column_name_clashes(cls): # Store a list of column names which have already been used by other fields. used_column_names = [] errors = [] for f in cls._meta.local_fields: _, column_name = f.get_attname_column() # Ensure the column name is not already in use. if column_name and column_name in used_column_names: errors.append( checks.Error( "Field '%s' has column name '%s' that is used by " "another field." % (f.name, column_name), hint="Specify a 'db_column' for the field.", obj=cls, id="models.E007", ) ) else: used_column_names.append(column_name) return errors @classmethod def _check_model_name_db_lookup_clashes(cls): errors = [] model_name = cls.__name__ if model_name.startswith("_") or model_name.endswith("_"): errors.append( checks.Error( "The model name '%s' cannot start or end with an underscore " "as it collides with the query lookup syntax." % model_name, obj=cls, id="models.E023", ) ) elif LOOKUP_SEP in model_name: errors.append( checks.Error( "The model name '%s' cannot contain double underscores as " "it collides with the query lookup syntax." % model_name, obj=cls, id="models.E024", ) ) return errors @classmethod def _check_property_name_related_field_accessor_clashes(cls): errors = [] property_names = cls._meta._property_names related_field_accessors = ( f.get_attname() for f in cls._meta._get_fields(reverse=False) if f.is_relation and f.related_model is not None ) for accessor in related_field_accessors: if accessor in property_names: errors.append( checks.Error( "The property '%s' clashes with a related field " "accessor." % accessor, obj=cls, id="models.E025", ) ) return errors @classmethod def _check_single_primary_key(cls): errors = [] if sum(1 for f in cls._meta.local_fields if f.primary_key) > 1: errors.append( checks.Error( "The model cannot have more than one field with " "'primary_key=True'.", obj=cls, id="models.E026", ) ) return errors @classmethod def _check_index_together(cls): """Check the value of "index_together" option.""" if not isinstance(cls._meta.index_together, (tuple, list)): return [ checks.Error( "'index_together' must be a list or tuple.", obj=cls, id="models.E008", ) ] elif any( not isinstance(fields, (tuple, list)) for fields in cls._meta.index_together ): return [ checks.Error( "All 'index_together' elements must be lists or tuples.", obj=cls, id="models.E009", ) ] else: errors = [] for fields in cls._meta.index_together: errors.extend(cls._check_local_fields(fields, "index_together")) return errors @classmethod def _check_unique_together(cls): """Check the value of "unique_together" option.""" if not isinstance(cls._meta.unique_together, (tuple, list)): return [ checks.Error( "'unique_together' must be a list or tuple.", obj=cls, id="models.E010", ) ] elif any( not isinstance(fields, (tuple, list)) for fields in cls._meta.unique_together ): return [ checks.Error( "All 'unique_together' elements must be lists or tuples.", obj=cls, id="models.E011", ) ] else: errors = [] for fields in cls._meta.unique_together: errors.extend(cls._check_local_fields(fields, "unique_together")) return errors @classmethod def _check_indexes(cls, databases): """Check fields, names, and conditions of indexes.""" errors = [] references = set() for index in cls._meta.indexes: # Index name can't start with an underscore or a number, restricted # for cross-database compatibility with Oracle. if index.name[0] == "_" or index.name[0].isdigit(): errors.append( checks.Error( "The index name '%s' cannot start with an underscore " "or a number." % index.name, obj=cls, id="models.E033", ), ) if len(index.name) > index.max_name_length: errors.append( checks.Error( "The index name '%s' cannot be longer than %d " "characters." % (index.name, index.max_name_length), obj=cls, id="models.E034", ), ) if index.contains_expressions: for expression in index.expressions: references.update( ref[0] for ref in cls._get_expr_references(expression) ) for db in databases: if not router.allow_migrate_model(db, cls): continue connection = connections[db] if not ( connection.features.supports_partial_indexes or "supports_partial_indexes" in cls._meta.required_db_features ) and any(index.condition is not None for index in cls._meta.indexes): errors.append( checks.Warning( "%s does not support indexes with conditions." % connection.display_name, hint=( "Conditions will be ignored. Silence this warning " "if you don't care about it." ), obj=cls, id="models.W037", ) ) if not ( connection.features.supports_covering_indexes or "supports_covering_indexes" in cls._meta.required_db_features ) and any(index.include for index in cls._meta.indexes): errors.append( checks.Warning( "%s does not support indexes with non-key columns." % connection.display_name, hint=( "Non-key columns will be ignored. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W040", ) ) if not ( connection.features.supports_expression_indexes or "supports_expression_indexes" in cls._meta.required_db_features ) and any(index.contains_expressions for index in cls._meta.indexes): errors.append( checks.Warning( "%s does not support indexes on expressions." % connection.display_name, hint=( "An index won't be created. Silence this warning " "if you don't care about it." ), obj=cls, id="models.W043", ) ) fields = [ field for index in cls._meta.indexes for field, _ in index.fields_orders ] fields += [include for index in cls._meta.indexes for include in index.include] fields += references errors.extend(cls._check_local_fields(fields, "indexes")) return errors @classmethod def _check_local_fields(cls, fields, option): from django.db import models # In order to avoid hitting the relation tree prematurely, we use our # own fields_map instead of using get_field() forward_fields_map = {} for field in cls._meta._get_fields(reverse=False): forward_fields_map[field.name] = field if hasattr(field, "attname"): forward_fields_map[field.attname] = field errors = [] for field_name in fields: try: field = forward_fields_map[field_name] except KeyError: errors.append( checks.Error( "'%s' refers to the nonexistent field '%s'." % ( option, field_name, ), obj=cls, id="models.E012", ) ) else: if isinstance(field.remote_field, models.ManyToManyRel): errors.append( checks.Error( "'%s' refers to a ManyToManyField '%s', but " "ManyToManyFields are not permitted in '%s'." % ( option, field_name, option, ), obj=cls, id="models.E013", ) ) elif field not in cls._meta.local_fields: errors.append( checks.Error( "'%s' refers to field '%s' which is not local to model " "'%s'." % (option, field_name, cls._meta.object_name), hint="This issue may be caused by multi-table inheritance.", obj=cls, id="models.E016", ) ) return errors @classmethod def _check_ordering(cls): """ Check "ordering" option -- is it a list of strings and do all fields exist? """ if cls._meta._ordering_clash: return [ checks.Error( "'ordering' and 'order_with_respect_to' cannot be used together.", obj=cls, id="models.E021", ), ] if cls._meta.order_with_respect_to or not cls._meta.ordering: return [] if not isinstance(cls._meta.ordering, (list, tuple)): return [ checks.Error( "'ordering' must be a tuple or list (even if you want to order by " "only one field).", obj=cls, id="models.E014", ) ] errors = [] fields = cls._meta.ordering # Skip expressions and '?' fields. fields = (f for f in fields if isinstance(f, str) and f != "?") # Convert "-field" to "field". fields = ((f[1:] if f.startswith("-") else f) for f in fields) # Separate related fields and non-related fields. _fields = [] related_fields = [] for f in fields: if LOOKUP_SEP in f: related_fields.append(f) else: _fields.append(f) fields = _fields # Check related fields. for field in related_fields: _cls = cls fld = None for part in field.split(LOOKUP_SEP): try: # pk is an alias that won't be found by opts.get_field. if part == "pk": fld = _cls._meta.pk else: fld = _cls._meta.get_field(part) if fld.is_relation: _cls = fld.path_infos[-1].to_opts.model else: _cls = None except (FieldDoesNotExist, AttributeError): if fld is None or ( fld.get_transform(part) is None and fld.get_lookup(part) is None ): errors.append( checks.Error( "'ordering' refers to the nonexistent field, " "related field, or lookup '%s'." % field, obj=cls, id="models.E015", ) ) # Skip ordering on pk. This is always a valid order_by field # but is an alias and therefore won't be found by opts.get_field. fields = {f for f in fields if f != "pk"} # Check for invalid or nonexistent fields in ordering. invalid_fields = [] # Any field name that is not present in field_names does not exist. # Also, ordering by m2m fields is not allowed. opts = cls._meta valid_fields = set( chain.from_iterable( (f.name, f.attname) if not (f.auto_created and not f.concrete) else (f.field.related_query_name(),) for f in chain(opts.fields, opts.related_objects) ) ) invalid_fields.extend(fields - valid_fields) for invalid_field in invalid_fields: errors.append( checks.Error( "'ordering' refers to the nonexistent field, related " "field, or lookup '%s'." % invalid_field, obj=cls, id="models.E015", ) ) return errors @classmethod def _check_long_column_names(cls, databases): """ Check that any auto-generated column names are shorter than the limits for each database in which the model will be created. """ if not databases: return [] errors = [] allowed_len = None db_alias = None # Find the minimum max allowed length among all specified db_aliases. for db in databases: # skip databases where the model won't be created if not router.allow_migrate_model(db, cls): continue connection = connections[db] max_name_length = connection.ops.max_name_length() if max_name_length is None or connection.features.truncates_names: continue else: if allowed_len is None: allowed_len = max_name_length db_alias = db elif max_name_length < allowed_len: allowed_len = max_name_length db_alias = db if allowed_len is None: return errors for f in cls._meta.local_fields: _, column_name = f.get_attname_column() # Check if auto-generated name for the field is too long # for the database. if ( f.db_column is None and column_name is not None and len(column_name) > allowed_len ): errors.append( checks.Error( 'Autogenerated column name too long for field "%s". ' 'Maximum length is "%s" for database "%s".' % (column_name, allowed_len, db_alias), hint="Set the column name manually using 'db_column'.", obj=cls, id="models.E018", ) ) for f in cls._meta.local_many_to_many: # Skip nonexistent models. if isinstance(f.remote_field.through, str): continue # Check if auto-generated name for the M2M field is too long # for the database. for m2m in f.remote_field.through._meta.local_fields: _, rel_name = m2m.get_attname_column() if ( m2m.db_column is None and rel_name is not None and len(rel_name) > allowed_len ): errors.append( checks.Error( "Autogenerated column name too long for M2M field " '"%s". Maximum length is "%s" for database "%s".' % (rel_name, allowed_len, db_alias), hint=( "Use 'through' to create a separate model for " "M2M and then set column_name using 'db_column'." ), obj=cls, id="models.E019", ) ) return errors @classmethod def _get_expr_references(cls, expr): if isinstance(expr, Q): for child in expr.children: if isinstance(child, tuple): lookup, value = child yield tuple(lookup.split(LOOKUP_SEP)) yield from cls._get_expr_references(value) else: yield from cls._get_expr_references(child) elif isinstance(expr, F): yield tuple(expr.name.split(LOOKUP_SEP)) elif hasattr(expr, "get_source_expressions"): for src_expr in expr.get_source_expressions(): yield from cls._get_expr_references(src_expr) @classmethod def _check_constraints(cls, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, cls): continue connection = connections[db] if not ( connection.features.supports_table_check_constraints or "supports_table_check_constraints" in cls._meta.required_db_features ) and any( isinstance(constraint, CheckConstraint) for constraint in cls._meta.constraints ): errors.append( checks.Warning( "%s does not support check constraints." % connection.display_name, hint=( "A constraint won't be created. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W027", ) ) if not ( connection.features.supports_partial_indexes or "supports_partial_indexes" in cls._meta.required_db_features ) and any( isinstance(constraint, UniqueConstraint) and constraint.condition is not None for constraint in cls._meta.constraints ): errors.append( checks.Warning( "%s does not support unique constraints with " "conditions." % connection.display_name, hint=( "A constraint won't be created. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W036", ) ) if not ( connection.features.supports_deferrable_unique_constraints or "supports_deferrable_unique_constraints" in cls._meta.required_db_features ) and any( isinstance(constraint, UniqueConstraint) and constraint.deferrable is not None for constraint in cls._meta.constraints ): errors.append( checks.Warning( "%s does not support deferrable unique constraints." % connection.display_name, hint=( "A constraint won't be created. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W038", ) ) if not ( connection.features.supports_covering_indexes or "supports_covering_indexes" in cls._meta.required_db_features ) and any( isinstance(constraint, UniqueConstraint) and constraint.include for constraint in cls._meta.constraints ): errors.append( checks.Warning( "%s does not support unique constraints with non-key " "columns." % connection.display_name, hint=( "A constraint won't be created. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W039", ) ) if not ( connection.features.supports_expression_indexes or "supports_expression_indexes" in cls._meta.required_db_features ) and any( isinstance(constraint, UniqueConstraint) and constraint.contains_expressions for constraint in cls._meta.constraints ): errors.append( checks.Warning( "%s does not support unique constraints on " "expressions." % connection.display_name, hint=( "A constraint won't be created. Silence this " "warning if you don't care about it." ), obj=cls, id="models.W044", ) ) fields = set( chain.from_iterable( (*constraint.fields, *constraint.include) for constraint in cls._meta.constraints if isinstance(constraint, UniqueConstraint) ) ) references = set() for constraint in cls._meta.constraints: if isinstance(constraint, UniqueConstraint): if ( connection.features.supports_partial_indexes or "supports_partial_indexes" not in cls._meta.required_db_features ) and isinstance(constraint.condition, Q): references.update( cls._get_expr_references(constraint.condition) ) if ( connection.features.supports_expression_indexes or "supports_expression_indexes" not in cls._meta.required_db_features ) and constraint.contains_expressions: for expression in constraint.expressions: references.update(cls._get_expr_references(expression)) elif isinstance(constraint, CheckConstraint): if ( connection.features.supports_table_check_constraints or "supports_table_check_constraints" not in cls._meta.required_db_features ): if isinstance(constraint.check, Q): references.update( cls._get_expr_references(constraint.check) ) if any( isinstance(expr, RawSQL) for expr in constraint.check.flatten() ): errors.append( checks.Warning( f"Check constraint {constraint.name!r} contains " f"RawSQL() expression and won't be validated " f"during the model full_clean().", hint=( "Silence this warning if you don't care about " "it." ), obj=cls, id="models.W045", ), ) for field_name, *lookups in references: # pk is an alias that won't be found by opts.get_field. if field_name != "pk": fields.add(field_name) if not lookups: # If it has no lookups it cannot result in a JOIN. continue try: if field_name == "pk": field = cls._meta.pk else: field = cls._meta.get_field(field_name) if not field.is_relation or field.many_to_many or field.one_to_many: continue except FieldDoesNotExist: continue # JOIN must happen at the first lookup. first_lookup = lookups[0] if ( hasattr(field, "get_transform") and hasattr(field, "get_lookup") and field.get_transform(first_lookup) is None and field.get_lookup(first_lookup) is None ): errors.append( checks.Error( "'constraints' refers to the joined field '%s'." % LOOKUP_SEP.join([field_name] + lookups), obj=cls, id="models.E041", ) ) errors.extend(cls._check_local_fields(fields, "constraints")) return errors ############################################ # HELPER FUNCTIONS (CURRIED MODEL METHODS) # ############################################ # ORDERING METHODS ######################### def method_set_order(self, ordered_obj, id_list, using=None): order_wrt = ordered_obj._meta.order_with_respect_to filter_args = order_wrt.get_forward_related_filter(self) ordered_obj.objects.db_manager(using).filter(**filter_args).bulk_update( [ordered_obj(pk=pk, _order=order) for order, pk in enumerate(id_list)], ["_order"], ) def method_get_order(self, ordered_obj): order_wrt = ordered_obj._meta.order_with_respect_to filter_args = order_wrt.get_forward_related_filter(self) pk_name = ordered_obj._meta.pk.name return ordered_obj.objects.filter(**filter_args).values_list(pk_name, flat=True) def make_foreign_order_accessors(model, related_model): setattr( related_model, "get_%s_order" % model.__name__.lower(), partialmethod(method_get_order, model), ) setattr( related_model, "set_%s_order" % model.__name__.lower(), partialmethod(method_set_order, model), ) ######## # MISC # ######## def model_unpickle(model_id): """Used to unpickle Model subclasses with deferred fields.""" if isinstance(model_id, tuple): model = apps.get_model(*model_id) else: # Backwards compat - the model was cached directly in earlier versions. model = model_id return model.__new__(model) model_unpickle.__safe_for_unpickle__ = True
6a3f3835abe27564d6e50d4594ea2c081f7545bd851772830b1113f3ab99cc3f
import itertools import math from django.core.exceptions import EmptyResultSet from django.db.models.expressions import Case, Expression, Func, Value, When from django.db.models.fields import ( BooleanField, CharField, DateTimeField, Field, IntegerField, UUIDField, ) from django.db.models.query_utils import RegisterLookupMixin from django.utils.datastructures import OrderedSet from django.utils.functional import cached_property from django.utils.hashable import make_hashable class Lookup(Expression): lookup_name = None prepare_rhs = True can_use_none_as_rhs = False def __init__(self, lhs, rhs): self.lhs, self.rhs = lhs, rhs self.rhs = self.get_prep_lookup() self.lhs = self.get_prep_lhs() if hasattr(self.lhs, "get_bilateral_transforms"): bilateral_transforms = self.lhs.get_bilateral_transforms() else: bilateral_transforms = [] if bilateral_transforms: # Warn the user as soon as possible if they are trying to apply # a bilateral transformation on a nested QuerySet: that won't work. from django.db.models.sql.query import Query # avoid circular import if isinstance(rhs, Query): raise NotImplementedError( "Bilateral transformations on nested querysets are not implemented." ) self.bilateral_transforms = bilateral_transforms def apply_bilateral_transforms(self, value): for transform in self.bilateral_transforms: value = transform(value) return value def __repr__(self): return f"{self.__class__.__name__}({self.lhs!r}, {self.rhs!r})" def batch_process_rhs(self, compiler, connection, rhs=None): if rhs is None: rhs = self.rhs if self.bilateral_transforms: sqls, sqls_params = [], [] for p in rhs: value = Value(p, output_field=self.lhs.output_field) value = self.apply_bilateral_transforms(value) value = value.resolve_expression(compiler.query) sql, sql_params = compiler.compile(value) sqls.append(sql) sqls_params.extend(sql_params) else: _, params = self.get_db_prep_lookup(rhs, connection) sqls, sqls_params = ["%s"] * len(params), params return sqls, sqls_params def get_source_expressions(self): if self.rhs_is_direct_value(): return [self.lhs] return [self.lhs, self.rhs] def set_source_expressions(self, new_exprs): if len(new_exprs) == 1: self.lhs = new_exprs[0] else: self.lhs, self.rhs = new_exprs def get_prep_lookup(self): if not self.prepare_rhs or hasattr(self.rhs, "resolve_expression"): return self.rhs if hasattr(self.lhs, "output_field"): if hasattr(self.lhs.output_field, "get_prep_value"): return self.lhs.output_field.get_prep_value(self.rhs) elif self.rhs_is_direct_value(): return Value(self.rhs) return self.rhs def get_prep_lhs(self): if hasattr(self.lhs, "resolve_expression"): return self.lhs return Value(self.lhs) def get_db_prep_lookup(self, value, connection): return ("%s", [value]) def process_lhs(self, compiler, connection, lhs=None): lhs = lhs or self.lhs if hasattr(lhs, "resolve_expression"): lhs = lhs.resolve_expression(compiler.query) sql, params = compiler.compile(lhs) if isinstance(lhs, Lookup): # Wrapped in parentheses to respect operator precedence. sql = f"({sql})" return sql, params def process_rhs(self, compiler, connection): value = self.rhs if self.bilateral_transforms: if self.rhs_is_direct_value(): # Do not call get_db_prep_lookup here as the value will be # transformed before being used for lookup value = Value(value, output_field=self.lhs.output_field) value = self.apply_bilateral_transforms(value) value = value.resolve_expression(compiler.query) if hasattr(value, "as_sql"): sql, params = compiler.compile(value) # Ensure expression is wrapped in parentheses to respect operator # precedence but avoid double wrapping as it can be misinterpreted # on some backends (e.g. subqueries on SQLite). if sql and sql[0] != "(": sql = "(%s)" % sql return sql, params else: return self.get_db_prep_lookup(value, connection) def rhs_is_direct_value(self): return not hasattr(self.rhs, "as_sql") def get_group_by_cols(self, alias=None): cols = [] for source in self.get_source_expressions(): cols.extend(source.get_group_by_cols()) return cols def as_oracle(self, compiler, connection): # Oracle doesn't allow EXISTS() and filters to be compared to another # expression unless they're wrapped in a CASE WHEN. wrapped = False exprs = [] for expr in (self.lhs, self.rhs): if connection.ops.conditional_expression_supported_in_where_clause(expr): expr = Case(When(expr, then=True), default=False) wrapped = True exprs.append(expr) lookup = type(self)(*exprs) if wrapped else self return lookup.as_sql(compiler, connection) @cached_property def output_field(self): return BooleanField() @property def identity(self): return self.__class__, self.lhs, self.rhs def __eq__(self, other): if not isinstance(other, Lookup): return NotImplemented return self.identity == other.identity def __hash__(self): return hash(make_hashable(self.identity)) def resolve_expression( self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False ): c = self.copy() c.is_summary = summarize c.lhs = self.lhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) if hasattr(self.rhs, "resolve_expression"): c.rhs = self.rhs.resolve_expression( query, allow_joins, reuse, summarize, for_save ) return c def select_format(self, compiler, sql, params): # Wrap filters with a CASE WHEN expression if a database backend # (e.g. Oracle) doesn't support boolean expression in SELECT or GROUP # BY list. if not compiler.connection.features.supports_boolean_expr_in_select_clause: sql = f"CASE WHEN {sql} THEN 1 ELSE 0 END" return sql, params class Transform(RegisterLookupMixin, Func): """ RegisterLookupMixin() is first so that get_lookup() and get_transform() first examine self and then check output_field. """ bilateral = False arity = 1 @property def lhs(self): return self.get_source_expressions()[0] def get_bilateral_transforms(self): if hasattr(self.lhs, "get_bilateral_transforms"): bilateral_transforms = self.lhs.get_bilateral_transforms() else: bilateral_transforms = [] if self.bilateral: bilateral_transforms.append(self.__class__) return bilateral_transforms class BuiltinLookup(Lookup): def process_lhs(self, compiler, connection, lhs=None): lhs_sql, params = super().process_lhs(compiler, connection, lhs) field_internal_type = self.lhs.output_field.get_internal_type() db_type = self.lhs.output_field.db_type(connection=connection) lhs_sql = connection.ops.field_cast_sql(db_type, field_internal_type) % lhs_sql lhs_sql = ( connection.ops.lookup_cast(self.lookup_name, field_internal_type) % lhs_sql ) return lhs_sql, list(params) def as_sql(self, compiler, connection): lhs_sql, params = self.process_lhs(compiler, connection) rhs_sql, rhs_params = self.process_rhs(compiler, connection) params.extend(rhs_params) rhs_sql = self.get_rhs_op(connection, rhs_sql) return "%s %s" % (lhs_sql, rhs_sql), params def get_rhs_op(self, connection, rhs): return connection.operators[self.lookup_name] % rhs class FieldGetDbPrepValueMixin: """ Some lookups require Field.get_db_prep_value() to be called on their inputs. """ get_db_prep_lookup_value_is_iterable = False def get_db_prep_lookup(self, value, connection): # For relational fields, use the 'target_field' attribute of the # output_field. field = getattr(self.lhs.output_field, "target_field", None) get_db_prep_value = ( getattr(field, "get_db_prep_value", None) or self.lhs.output_field.get_db_prep_value ) return ( "%s", [get_db_prep_value(v, connection, prepared=True) for v in value] if self.get_db_prep_lookup_value_is_iterable else [get_db_prep_value(value, connection, prepared=True)], ) class FieldGetDbPrepValueIterableMixin(FieldGetDbPrepValueMixin): """ Some lookups require Field.get_db_prep_value() to be called on each value in an iterable. """ get_db_prep_lookup_value_is_iterable = True def get_prep_lookup(self): if hasattr(self.rhs, "resolve_expression"): return self.rhs prepared_values = [] for rhs_value in self.rhs: if hasattr(rhs_value, "resolve_expression"): # An expression will be handled by the database but can coexist # alongside real values. pass elif self.prepare_rhs and hasattr(self.lhs.output_field, "get_prep_value"): rhs_value = self.lhs.output_field.get_prep_value(rhs_value) prepared_values.append(rhs_value) return prepared_values def process_rhs(self, compiler, connection): if self.rhs_is_direct_value(): # rhs should be an iterable of values. Use batch_process_rhs() # to prepare/transform those values. return self.batch_process_rhs(compiler, connection) else: return super().process_rhs(compiler, connection) def resolve_expression_parameter(self, compiler, connection, sql, param): params = [param] if hasattr(param, "resolve_expression"): param = param.resolve_expression(compiler.query) if hasattr(param, "as_sql"): sql, params = compiler.compile(param) return sql, params def batch_process_rhs(self, compiler, connection, rhs=None): pre_processed = super().batch_process_rhs(compiler, connection, rhs) # The params list may contain expressions which compile to a # sql/param pair. Zip them to get sql and param pairs that refer to the # same argument and attempt to replace them with the result of # compiling the param step. sql, params = zip( *( self.resolve_expression_parameter(compiler, connection, sql, param) for sql, param in zip(*pre_processed) ) ) params = itertools.chain.from_iterable(params) return sql, tuple(params) class PostgresOperatorLookup(FieldGetDbPrepValueMixin, Lookup): """Lookup defined by operators on PostgreSQL.""" postgres_operator = None def as_postgresql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = tuple(lhs_params) + tuple(rhs_params) return "%s %s %s" % (lhs, self.postgres_operator, rhs), params @Field.register_lookup class Exact(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "exact" def get_prep_lookup(self): from django.db.models.sql.query import Query # avoid circular import if isinstance(self.rhs, Query): if self.rhs.has_limit_one(): if not self.rhs.has_select_fields: self.rhs.clear_select_clause() self.rhs.add_fields(["pk"]) else: raise ValueError( "The QuerySet value for an exact lookup must be limited to " "one result using slicing." ) return super().get_prep_lookup() def as_sql(self, compiler, connection): # Avoid comparison against direct rhs if lhs is a boolean value. That # turns "boolfield__exact=True" into "WHERE boolean_field" instead of # "WHERE boolean_field = True" when allowed. if ( isinstance(self.rhs, bool) and getattr(self.lhs, "conditional", False) and connection.ops.conditional_expression_supported_in_where_clause( self.lhs ) ): lhs_sql, params = self.process_lhs(compiler, connection) template = "%s" if self.rhs else "NOT %s" return template % lhs_sql, params return super().as_sql(compiler, connection) @Field.register_lookup class IExact(BuiltinLookup): lookup_name = "iexact" prepare_rhs = False def process_rhs(self, qn, connection): rhs, params = super().process_rhs(qn, connection) if params: params[0] = connection.ops.prep_for_iexact_query(params[0]) return rhs, params @Field.register_lookup class GreaterThan(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "gt" @Field.register_lookup class GreaterThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "gte" @Field.register_lookup class LessThan(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "lt" @Field.register_lookup class LessThanOrEqual(FieldGetDbPrepValueMixin, BuiltinLookup): lookup_name = "lte" class IntegerFieldFloatRounding: """ Allow floats to work as query values for IntegerField. Without this, the decimal portion of the float would always be discarded. """ def get_prep_lookup(self): if isinstance(self.rhs, float): self.rhs = math.ceil(self.rhs) return super().get_prep_lookup() @IntegerField.register_lookup class IntegerGreaterThanOrEqual(IntegerFieldFloatRounding, GreaterThanOrEqual): pass @IntegerField.register_lookup class IntegerLessThan(IntegerFieldFloatRounding, LessThan): pass @Field.register_lookup class In(FieldGetDbPrepValueIterableMixin, BuiltinLookup): lookup_name = "in" def get_prep_lookup(self): from django.db.models.sql.query import Query # avoid circular import if isinstance(self.rhs, Query): self.rhs.clear_ordering(clear_default=True) if not self.rhs.has_select_fields: self.rhs.clear_select_clause() self.rhs.add_fields(["pk"]) return super().get_prep_lookup() def process_rhs(self, compiler, connection): db_rhs = getattr(self.rhs, "_db", None) if db_rhs is not None and db_rhs != connection.alias: raise ValueError( "Subqueries aren't allowed across different databases. Force " "the inner query to be evaluated using `list(inner_query)`." ) if self.rhs_is_direct_value(): # Remove None from the list as NULL is never equal to anything. try: rhs = OrderedSet(self.rhs) rhs.discard(None) except TypeError: # Unhashable items in self.rhs rhs = [r for r in self.rhs if r is not None] if not rhs: raise EmptyResultSet # rhs should be an iterable; use batch_process_rhs() to # prepare/transform those values. sqls, sqls_params = self.batch_process_rhs(compiler, connection, rhs) placeholder = "(" + ", ".join(sqls) + ")" return (placeholder, sqls_params) return super().process_rhs(compiler, connection) def get_rhs_op(self, connection, rhs): return "IN %s" % rhs def as_sql(self, compiler, connection): max_in_list_size = connection.ops.max_in_list_size() if ( self.rhs_is_direct_value() and max_in_list_size and len(self.rhs) > max_in_list_size ): return self.split_parameter_list_as_sql(compiler, connection) return super().as_sql(compiler, connection) def split_parameter_list_as_sql(self, compiler, connection): # This is a special case for databases which limit the number of # elements which can appear in an 'IN' clause. max_in_list_size = connection.ops.max_in_list_size() lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.batch_process_rhs(compiler, connection) in_clause_elements = ["("] params = [] for offset in range(0, len(rhs_params), max_in_list_size): if offset > 0: in_clause_elements.append(" OR ") in_clause_elements.append("%s IN (" % lhs) params.extend(lhs_params) sqls = rhs[offset : offset + max_in_list_size] sqls_params = rhs_params[offset : offset + max_in_list_size] param_group = ", ".join(sqls) in_clause_elements.append(param_group) in_clause_elements.append(")") params.extend(sqls_params) in_clause_elements.append(")") return "".join(in_clause_elements), params class PatternLookup(BuiltinLookup): param_pattern = "%%%s%%" prepare_rhs = False def get_rhs_op(self, connection, rhs): # Assume we are in startswith. We need to produce SQL like: # col LIKE %s, ['thevalue%'] # For python values we can (and should) do that directly in Python, # but if the value is for example reference to other column, then # we need to add the % pattern match to the lookup by something like # col LIKE othercol || '%%' # So, for Python values we don't need any special pattern, but for # SQL reference values or SQL transformations we need the correct # pattern added. if hasattr(self.rhs, "as_sql") or self.bilateral_transforms: pattern = connection.pattern_ops[self.lookup_name].format( connection.pattern_esc ) return pattern.format(rhs) else: return super().get_rhs_op(connection, rhs) def process_rhs(self, qn, connection): rhs, params = super().process_rhs(qn, connection) if self.rhs_is_direct_value() and params and not self.bilateral_transforms: params[0] = self.param_pattern % connection.ops.prep_for_like_query( params[0] ) return rhs, params @Field.register_lookup class Contains(PatternLookup): lookup_name = "contains" @Field.register_lookup class IContains(Contains): lookup_name = "icontains" @Field.register_lookup class StartsWith(PatternLookup): lookup_name = "startswith" param_pattern = "%s%%" @Field.register_lookup class IStartsWith(StartsWith): lookup_name = "istartswith" @Field.register_lookup class EndsWith(PatternLookup): lookup_name = "endswith" param_pattern = "%%%s" @Field.register_lookup class IEndsWith(EndsWith): lookup_name = "iendswith" @Field.register_lookup class Range(FieldGetDbPrepValueIterableMixin, BuiltinLookup): lookup_name = "range" def get_rhs_op(self, connection, rhs): return "BETWEEN %s AND %s" % (rhs[0], rhs[1]) @Field.register_lookup class IsNull(BuiltinLookup): lookup_name = "isnull" prepare_rhs = False def as_sql(self, compiler, connection): if not isinstance(self.rhs, bool): raise ValueError( "The QuerySet value for an isnull lookup must be True or False." ) sql, params = compiler.compile(self.lhs) if self.rhs: return "%s IS NULL" % sql, params else: return "%s IS NOT NULL" % sql, params @Field.register_lookup class Regex(BuiltinLookup): lookup_name = "regex" prepare_rhs = False def as_sql(self, compiler, connection): if self.lookup_name in connection.operators: return super().as_sql(compiler, connection) else: lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) sql_template = connection.ops.regex_lookup(self.lookup_name) return sql_template % (lhs, rhs), lhs_params + rhs_params @Field.register_lookup class IRegex(Regex): lookup_name = "iregex" class YearLookup(Lookup): def year_lookup_bounds(self, connection, year): from django.db.models.functions import ExtractIsoYear iso_year = isinstance(self.lhs, ExtractIsoYear) output_field = self.lhs.lhs.output_field if isinstance(output_field, DateTimeField): bounds = connection.ops.year_lookup_bounds_for_datetime_field( year, iso_year=iso_year, ) else: bounds = connection.ops.year_lookup_bounds_for_date_field( year, iso_year=iso_year, ) return bounds def as_sql(self, compiler, connection): # Avoid the extract operation if the rhs is a direct value to allow # indexes to be used. if self.rhs_is_direct_value(): # Skip the extract part by directly using the originating field, # that is self.lhs.lhs. lhs_sql, params = self.process_lhs(compiler, connection, self.lhs.lhs) rhs_sql, _ = self.process_rhs(compiler, connection) rhs_sql = self.get_direct_rhs_sql(connection, rhs_sql) start, finish = self.year_lookup_bounds(connection, self.rhs) params.extend(self.get_bound_params(start, finish)) return "%s %s" % (lhs_sql, rhs_sql), params return super().as_sql(compiler, connection) def get_direct_rhs_sql(self, connection, rhs): return connection.operators[self.lookup_name] % rhs def get_bound_params(self, start, finish): raise NotImplementedError( "subclasses of YearLookup must provide a get_bound_params() method" ) class YearExact(YearLookup, Exact): def get_direct_rhs_sql(self, connection, rhs): return "BETWEEN %s AND %s" def get_bound_params(self, start, finish): return (start, finish) class YearGt(YearLookup, GreaterThan): def get_bound_params(self, start, finish): return (finish,) class YearGte(YearLookup, GreaterThanOrEqual): def get_bound_params(self, start, finish): return (start,) class YearLt(YearLookup, LessThan): def get_bound_params(self, start, finish): return (start,) class YearLte(YearLookup, LessThanOrEqual): def get_bound_params(self, start, finish): return (finish,) class UUIDTextMixin: """ Strip hyphens from a value when filtering a UUIDField on backends without a native datatype for UUID. """ def process_rhs(self, qn, connection): if not connection.features.has_native_uuid_field: from django.db.models.functions import Replace if self.rhs_is_direct_value(): self.rhs = Value(self.rhs) self.rhs = Replace( self.rhs, Value("-"), Value(""), output_field=CharField() ) rhs, params = super().process_rhs(qn, connection) return rhs, params @UUIDField.register_lookup class UUIDIExact(UUIDTextMixin, IExact): pass @UUIDField.register_lookup class UUIDContains(UUIDTextMixin, Contains): pass @UUIDField.register_lookup class UUIDIContains(UUIDTextMixin, IContains): pass @UUIDField.register_lookup class UUIDStartsWith(UUIDTextMixin, StartsWith): pass @UUIDField.register_lookup class UUIDIStartsWith(UUIDTextMixin, IStartsWith): pass @UUIDField.register_lookup class UUIDEndsWith(UUIDTextMixin, EndsWith): pass @UUIDField.register_lookup class UUIDIEndsWith(UUIDTextMixin, IEndsWith): pass
c88636f1228846681b9223026d27d37a3cab43ff5fbe514cda2ecdca9f793d97
from django.db import models from django.db.migrations.operations.base import Operation from django.db.migrations.state import ModelState from django.db.migrations.utils import field_references, resolve_relation from django.db.models.options import normalize_together from django.utils.functional import cached_property from .fields import AddField, AlterField, FieldOperation, RemoveField, RenameField def _check_for_duplicates(arg_name, objs): used_vals = set() for val in objs: if val in used_vals: raise ValueError( "Found duplicate value %s in CreateModel %s argument." % (val, arg_name) ) used_vals.add(val) class ModelOperation(Operation): def __init__(self, name): self.name = name @cached_property def name_lower(self): return self.name.lower() def references_model(self, name, app_label): return name.lower() == self.name_lower def reduce(self, operation, app_label): return super().reduce(operation, app_label) or self.can_reduce_through( operation, app_label ) def can_reduce_through(self, operation, app_label): return not operation.references_model(self.name, app_label) class CreateModel(ModelOperation): """Create a model's table.""" serialization_expand_args = ["fields", "options", "managers"] def __init__(self, name, fields, options=None, bases=None, managers=None): self.fields = fields self.options = options or {} self.bases = bases or (models.Model,) self.managers = managers or [] super().__init__(name) # Sanity-check that there are no duplicated field names, bases, or # manager names _check_for_duplicates("fields", (name for name, _ in self.fields)) _check_for_duplicates( "bases", ( base._meta.label_lower if hasattr(base, "_meta") else base.lower() if isinstance(base, str) else base for base in self.bases ), ) _check_for_duplicates("managers", (name for name, _ in self.managers)) def deconstruct(self): kwargs = { "name": self.name, "fields": self.fields, } if self.options: kwargs["options"] = self.options if self.bases and self.bases != (models.Model,): kwargs["bases"] = self.bases if self.managers and self.managers != [("objects", models.Manager())]: kwargs["managers"] = self.managers return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.add_model( ModelState( app_label, self.name, list(self.fields), dict(self.options), tuple(self.bases), list(self.managers), ) ) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.create_model(model) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.delete_model(model) def describe(self): return "Create %smodel %s" % ( "proxy " if self.options.get("proxy", False) else "", self.name, ) @property def migration_name_fragment(self): return self.name_lower def references_model(self, name, app_label): name_lower = name.lower() if name_lower == self.name_lower: return True # Check we didn't inherit from the model reference_model_tuple = (app_label, name_lower) for base in self.bases: if ( base is not models.Model and isinstance(base, (models.base.ModelBase, str)) and resolve_relation(base, app_label) == reference_model_tuple ): return True # Check we have no FKs/M2Ms with it for _name, field in self.fields: if field_references( (app_label, self.name_lower), field, reference_model_tuple ): return True return False def reduce(self, operation, app_label): if ( isinstance(operation, DeleteModel) and self.name_lower == operation.name_lower and not self.options.get("proxy", False) ): return [] elif ( isinstance(operation, RenameModel) and self.name_lower == operation.old_name_lower ): return [ CreateModel( operation.new_name, fields=self.fields, options=self.options, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterModelOptions) and self.name_lower == operation.name_lower ): options = {**self.options, **operation.options} for key in operation.ALTER_OPTION_KEYS: if key not in operation.options: options.pop(key, None) return [ CreateModel( self.name, fields=self.fields, options=options, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterModelManagers) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options=self.options, bases=self.bases, managers=operation.managers, ), ] elif ( isinstance(operation, AlterTogetherOptionOperation) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options={ **self.options, **{operation.option_name: operation.option_value}, }, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, AlterOrderWithRespectTo) and self.name_lower == operation.name_lower ): return [ CreateModel( self.name, fields=self.fields, options={ **self.options, "order_with_respect_to": operation.order_with_respect_to, }, bases=self.bases, managers=self.managers, ), ] elif ( isinstance(operation, FieldOperation) and self.name_lower == operation.model_name_lower ): if isinstance(operation, AddField): return [ CreateModel( self.name, fields=self.fields + [(operation.name, operation.field)], options=self.options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, AlterField): return [ CreateModel( self.name, fields=[ (n, operation.field if n == operation.name else v) for n, v in self.fields ], options=self.options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RemoveField): options = self.options.copy() for option_name in ("unique_together", "index_together"): option = options.pop(option_name, None) if option: option = set( filter( bool, ( tuple( f for f in fields if f != operation.name_lower ) for fields in option ), ) ) if option: options[option_name] = option order_with_respect_to = options.get("order_with_respect_to") if order_with_respect_to == operation.name_lower: del options["order_with_respect_to"] return [ CreateModel( self.name, fields=[ (n, v) for n, v in self.fields if n.lower() != operation.name_lower ], options=options, bases=self.bases, managers=self.managers, ), ] elif isinstance(operation, RenameField): options = self.options.copy() for option_name in ("unique_together", "index_together"): option = options.get(option_name) if option: options[option_name] = { tuple( operation.new_name if f == operation.old_name else f for f in fields ) for fields in option } order_with_respect_to = options.get("order_with_respect_to") if order_with_respect_to == operation.old_name: options["order_with_respect_to"] = operation.new_name return [ CreateModel( self.name, fields=[ (operation.new_name if n == operation.old_name else n, v) for n, v in self.fields ], options=options, bases=self.bases, managers=self.managers, ), ] return super().reduce(operation, app_label) class DeleteModel(ModelOperation): """Drop a model's table.""" def deconstruct(self): kwargs = { "name": self.name, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.remove_model(app_label, self.name_lower) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.delete_model(model) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.create_model(model) def references_model(self, name, app_label): # The deleted model could be referencing the specified model through # related fields. return True def describe(self): return "Delete model %s" % self.name @property def migration_name_fragment(self): return "delete_%s" % self.name_lower class RenameModel(ModelOperation): """Rename a model.""" def __init__(self, old_name, new_name): self.old_name = old_name self.new_name = new_name super().__init__(old_name) @cached_property def old_name_lower(self): return self.old_name.lower() @cached_property def new_name_lower(self): return self.new_name.lower() def deconstruct(self): kwargs = { "old_name": self.old_name, "new_name": self.new_name, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.rename_model(app_label, self.old_name, self.new_name) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.new_name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.old_name) old_db_table = old_model._meta.db_table new_db_table = new_model._meta.db_table # Don't alter when a table name is not changed. if old_db_table == new_db_table: return # Move the main table schema_editor.alter_db_table(new_model, old_db_table, new_db_table) # Alter the fields pointing to us for related_object in old_model._meta.related_objects: if related_object.related_model == old_model: model = new_model related_key = (app_label, self.new_name_lower) else: model = related_object.related_model related_key = ( related_object.related_model._meta.app_label, related_object.related_model._meta.model_name, ) to_field = to_state.apps.get_model(*related_key)._meta.get_field( related_object.field.name ) schema_editor.alter_field( model, related_object.field, to_field, ) # Rename M2M fields whose name is based on this model's name. fields = zip( old_model._meta.local_many_to_many, new_model._meta.local_many_to_many ) for (old_field, new_field) in fields: # Skip self-referential fields as these are renamed above. if ( new_field.model == new_field.related_model or not new_field.remote_field.through._meta.auto_created ): continue # Rename the M2M table that's based on this model's name. old_m2m_model = old_field.remote_field.through new_m2m_model = new_field.remote_field.through schema_editor.alter_db_table( new_m2m_model, old_m2m_model._meta.db_table, new_m2m_model._meta.db_table, ) # Rename the column in the M2M table that's based on this # model's name. schema_editor.alter_field( new_m2m_model, old_m2m_model._meta.get_field(old_model._meta.model_name), new_m2m_model._meta.get_field(new_model._meta.model_name), ) def database_backwards(self, app_label, schema_editor, from_state, to_state): self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name self.database_forwards(app_label, schema_editor, from_state, to_state) self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name def references_model(self, name, app_label): return ( name.lower() == self.old_name_lower or name.lower() == self.new_name_lower ) def describe(self): return "Rename model %s to %s" % (self.old_name, self.new_name) @property def migration_name_fragment(self): return "rename_%s_%s" % (self.old_name_lower, self.new_name_lower) def reduce(self, operation, app_label): if ( isinstance(operation, RenameModel) and self.new_name_lower == operation.old_name_lower ): return [ RenameModel( self.old_name, operation.new_name, ), ] # Skip `ModelOperation.reduce` as we want to run `references_model` # against self.new_name. return super(ModelOperation, self).reduce( operation, app_label ) or not operation.references_model(self.new_name, app_label) class ModelOptionOperation(ModelOperation): def reduce(self, operation, app_label): if ( isinstance(operation, (self.__class__, DeleteModel)) and self.name_lower == operation.name_lower ): return [operation] return super().reduce(operation, app_label) class AlterModelTable(ModelOptionOperation): """Rename a model's table.""" def __init__(self, name, table): self.table = table super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "table": self.table, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options(app_label, self.name_lower, {"db_table": self.table}) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) schema_editor.alter_db_table( new_model, old_model._meta.db_table, new_model._meta.db_table, ) # Rename M2M fields whose name is based on this model's db_table for (old_field, new_field) in zip( old_model._meta.local_many_to_many, new_model._meta.local_many_to_many ): if new_field.remote_field.through._meta.auto_created: schema_editor.alter_db_table( new_field.remote_field.through, old_field.remote_field.through._meta.db_table, new_field.remote_field.through._meta.db_table, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def describe(self): return "Rename table for %s to %s" % ( self.name, self.table if self.table is not None else "(default)", ) @property def migration_name_fragment(self): return "alter_%s_table" % self.name_lower class AlterTogetherOptionOperation(ModelOptionOperation): option_name = None def __init__(self, name, option_value): if option_value: option_value = set(normalize_together(option_value)) setattr(self, self.option_name, option_value) super().__init__(name) @cached_property def option_value(self): return getattr(self, self.option_name) def deconstruct(self): kwargs = { "name": self.name, self.option_name: self.option_value, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, {self.option_name: self.option_value}, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): new_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, new_model): old_model = from_state.apps.get_model(app_label, self.name) alter_together = getattr(schema_editor, "alter_%s" % self.option_name) alter_together( new_model, getattr(old_model._meta, self.option_name, set()), getattr(new_model._meta, self.option_name, set()), ) def database_backwards(self, app_label, schema_editor, from_state, to_state): return self.database_forwards(app_label, schema_editor, from_state, to_state) def references_field(self, model_name, name, app_label): return self.references_model(model_name, app_label) and ( not self.option_value or any((name in fields) for fields in self.option_value) ) def describe(self): return "Alter %s for %s (%s constraint(s))" % ( self.option_name, self.name, len(self.option_value or ""), ) @property def migration_name_fragment(self): return "alter_%s_%s" % (self.name_lower, self.option_name) def can_reduce_through(self, operation, app_label): return super().can_reduce_through(operation, app_label) or ( isinstance(operation, AlterTogetherOptionOperation) and type(operation) is not type(self) ) class AlterUniqueTogether(AlterTogetherOptionOperation): """ Change the value of unique_together to the target one. Input value of unique_together must be a set of tuples. """ option_name = "unique_together" def __init__(self, name, unique_together): super().__init__(name, unique_together) class AlterIndexTogether(AlterTogetherOptionOperation): """ Change the value of index_together to the target one. Input value of index_together must be a set of tuples. """ option_name = "index_together" def __init__(self, name, index_together): super().__init__(name, index_together) class AlterOrderWithRespectTo(ModelOptionOperation): """Represent a change with the order_with_respect_to option.""" option_name = "order_with_respect_to" def __init__(self, name, order_with_respect_to): self.order_with_respect_to = order_with_respect_to super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "order_with_respect_to": self.order_with_respect_to, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, {self.option_name: self.order_with_respect_to}, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): to_model = to_state.apps.get_model(app_label, self.name) if self.allow_migrate_model(schema_editor.connection.alias, to_model): from_model = from_state.apps.get_model(app_label, self.name) # Remove a field if we need to if ( from_model._meta.order_with_respect_to and not to_model._meta.order_with_respect_to ): schema_editor.remove_field( from_model, from_model._meta.get_field("_order") ) # Add a field if we need to (altering the column is untouched as # it's likely a rename) elif ( to_model._meta.order_with_respect_to and not from_model._meta.order_with_respect_to ): field = to_model._meta.get_field("_order") if not field.has_default(): field.default = 0 schema_editor.add_field( from_model, field, ) def database_backwards(self, app_label, schema_editor, from_state, to_state): self.database_forwards(app_label, schema_editor, from_state, to_state) def references_field(self, model_name, name, app_label): return self.references_model(model_name, app_label) and ( self.order_with_respect_to is None or name == self.order_with_respect_to ) def describe(self): return "Set order_with_respect_to on %s to %s" % ( self.name, self.order_with_respect_to, ) @property def migration_name_fragment(self): return "alter_%s_order_with_respect_to" % self.name_lower class AlterModelOptions(ModelOptionOperation): """ Set new model options that don't directly affect the database schema (like verbose_name, permissions, ordering). Python code in migrations may still need them. """ # Model options we want to compare and preserve in an AlterModelOptions op ALTER_OPTION_KEYS = [ "base_manager_name", "default_manager_name", "default_related_name", "get_latest_by", "managed", "ordering", "permissions", "default_permissions", "select_on_save", "verbose_name", "verbose_name_plural", ] def __init__(self, name, options): self.options = options super().__init__(name) def deconstruct(self): kwargs = { "name": self.name, "options": self.options, } return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): state.alter_model_options( app_label, self.name_lower, self.options, self.ALTER_OPTION_KEYS, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass def describe(self): return "Change Meta options on %s" % self.name @property def migration_name_fragment(self): return "alter_%s_options" % self.name_lower class AlterModelManagers(ModelOptionOperation): """Alter the model's managers.""" serialization_expand_args = ["managers"] def __init__(self, name, managers): self.managers = managers super().__init__(name) def deconstruct(self): return (self.__class__.__qualname__, [self.name, self.managers], {}) def state_forwards(self, app_label, state): state.alter_model_managers(app_label, self.name_lower, self.managers) def database_forwards(self, app_label, schema_editor, from_state, to_state): pass def database_backwards(self, app_label, schema_editor, from_state, to_state): pass def describe(self): return "Change managers on %s" % self.name @property def migration_name_fragment(self): return "alter_%s_managers" % self.name_lower class IndexOperation(Operation): option_name = "indexes" @cached_property def model_name_lower(self): return self.model_name.lower() class AddIndex(IndexOperation): """Add an index on a model.""" def __init__(self, model_name, index): self.model_name = model_name if not index.name: raise ValueError( "Indexes passed to AddIndex operations require a name " "argument. %r doesn't have one." % index ) self.index = index def state_forwards(self, app_label, state): state.add_index(app_label, self.model_name_lower, self.index) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.add_index(model, self.index) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.remove_index(model, self.index) def deconstruct(self): kwargs = { "model_name": self.model_name, "index": self.index, } return ( self.__class__.__qualname__, [], kwargs, ) def describe(self): if self.index.expressions: return "Create index %s on %s on model %s" % ( self.index.name, ", ".join([str(expression) for expression in self.index.expressions]), self.model_name, ) return "Create index %s on field(s) %s of model %s" % ( self.index.name, ", ".join(self.index.fields), self.model_name, ) @property def migration_name_fragment(self): return "%s_%s" % (self.model_name_lower, self.index.name.lower()) class RemoveIndex(IndexOperation): """Remove an index from a model.""" def __init__(self, model_name, name): self.model_name = model_name self.name = name def state_forwards(self, app_label, state): state.remove_index(app_label, self.model_name_lower, self.name) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): from_model_state = from_state.models[app_label, self.model_name_lower] index = from_model_state.get_index_by_name(self.name) schema_editor.remove_index(model, index) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): to_model_state = to_state.models[app_label, self.model_name_lower] index = to_model_state.get_index_by_name(self.name) schema_editor.add_index(model, index) def deconstruct(self): kwargs = { "model_name": self.model_name, "name": self.name, } return ( self.__class__.__qualname__, [], kwargs, ) def describe(self): return "Remove index %s from %s" % (self.name, self.model_name) @property def migration_name_fragment(self): return "remove_%s_%s" % (self.model_name_lower, self.name.lower()) class RenameIndex(IndexOperation): """Rename an index.""" def __init__(self, model_name, new_name, old_name=None, old_fields=None): if not old_name and not old_fields: raise ValueError( "RenameIndex requires one of old_name and old_fields arguments to be " "set." ) if old_name and old_fields: raise ValueError( "RenameIndex.old_name and old_fields are mutually exclusive." ) self.model_name = model_name self.new_name = new_name self.old_name = old_name self.old_fields = old_fields @cached_property def old_name_lower(self): return self.old_name.lower() @cached_property def new_name_lower(self): return self.new_name.lower() def deconstruct(self): kwargs = { "model_name": self.model_name, "new_name": self.new_name, } if self.old_name: kwargs["old_name"] = self.old_name if self.old_fields: kwargs["old_fields"] = self.old_fields return (self.__class__.__qualname__, [], kwargs) def state_forwards(self, app_label, state): if self.old_fields: state.add_index( app_label, self.model_name_lower, models.Index(fields=self.old_fields, name=self.new_name), ) state.remove_model_options( app_label, self.model_name_lower, AlterIndexTogether.option_name, self.old_fields, ) else: state.rename_index( app_label, self.model_name_lower, self.old_name, self.new_name ) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if not self.allow_migrate_model(schema_editor.connection.alias, model): return if self.old_fields: from_model = from_state.apps.get_model(app_label, self.model_name) columns = [ from_model._meta.get_field(field).column for field in self.old_fields ] matching_index_name = schema_editor._constraint_names( from_model, column_names=columns, index=True ) if len(matching_index_name) != 1: raise ValueError( "Found wrong number (%s) of indexes for %s(%s)." % ( len(matching_index_name), from_model._meta.db_table, ", ".join(columns), ) ) old_index = models.Index( fields=self.old_fields, name=matching_index_name[0], ) else: from_model_state = from_state.models[app_label, self.model_name_lower] old_index = from_model_state.get_index_by_name(self.old_name) # Don't alter when the index name is not changed. if old_index.name == self.new_name: return to_model_state = to_state.models[app_label, self.model_name_lower] new_index = to_model_state.get_index_by_name(self.new_name) schema_editor.rename_index(model, old_index, new_index) def database_backwards(self, app_label, schema_editor, from_state, to_state): if self.old_fields: # Backward operation with unnamed index is a no-op. return self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name self.database_forwards(app_label, schema_editor, from_state, to_state) self.new_name_lower, self.old_name_lower = ( self.old_name_lower, self.new_name_lower, ) self.new_name, self.old_name = self.old_name, self.new_name def describe(self): if self.old_name: return ( f"Rename index {self.old_name} on {self.model_name} to {self.new_name}" ) return ( f"Rename unnamed index for {self.old_fields} on {self.model_name} to " f"{self.new_name}" ) @property def migration_name_fragment(self): if self.old_name: return "rename_%s_%s" % (self.old_name_lower, self.new_name_lower) return "rename_%s_%s_%s" % ( self.model_name_lower, "_".join(self.old_fields), self.new_name_lower, ) def reduce(self, operation, app_label): if ( isinstance(operation, RenameIndex) and self.model_name_lower == operation.model_name_lower and operation.old_name and self.new_name_lower == operation.old_name_lower ): return [ RenameIndex( self.model_name, new_name=operation.new_name, old_name=self.old_name, old_fields=self.old_fields, ) ] return super().reduce(operation, app_label) class AddConstraint(IndexOperation): option_name = "constraints" def __init__(self, model_name, constraint): self.model_name = model_name self.constraint = constraint def state_forwards(self, app_label, state): state.add_constraint(app_label, self.model_name_lower, self.constraint) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.add_constraint(model, self.constraint) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.remove_constraint(model, self.constraint) def deconstruct(self): return ( self.__class__.__name__, [], { "model_name": self.model_name, "constraint": self.constraint, }, ) def describe(self): return "Create constraint %s on model %s" % ( self.constraint.name, self.model_name, ) @property def migration_name_fragment(self): return "%s_%s" % (self.model_name_lower, self.constraint.name.lower()) class RemoveConstraint(IndexOperation): option_name = "constraints" def __init__(self, model_name, name): self.model_name = model_name self.name = name def state_forwards(self, app_label, state): state.remove_constraint(app_label, self.model_name_lower, self.name) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): from_model_state = from_state.models[app_label, self.model_name_lower] constraint = from_model_state.get_constraint_by_name(self.name) schema_editor.remove_constraint(model, constraint) def database_backwards(self, app_label, schema_editor, from_state, to_state): model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): to_model_state = to_state.models[app_label, self.model_name_lower] constraint = to_model_state.get_constraint_by_name(self.name) schema_editor.add_constraint(model, constraint) def deconstruct(self): return ( self.__class__.__name__, [], { "model_name": self.model_name, "name": self.name, }, ) def describe(self): return "Remove constraint %s from model %s" % (self.name, self.model_name) @property def migration_name_fragment(self): return "remove_%s_%s" % (self.model_name_lower, self.name.lower())
35da2e1e1f744b09fb6bfed7d6f197b8bd256ca5061c38fc49f9c8177950e614
import collections.abc import copy import datetime import decimal import math import operator import uuid import warnings from base64 import b64decode, b64encode from functools import partialmethod, total_ordering from django import forms from django.apps import apps from django.conf import settings from django.core import checks, exceptions, validators from django.db import connection, connections, router from django.db.models.constants import LOOKUP_SEP from django.db.models.query_utils import DeferredAttribute, RegisterLookupMixin from django.utils import timezone from django.utils.datastructures import DictWrapper from django.utils.dateparse import ( parse_date, parse_datetime, parse_duration, parse_time, ) from django.utils.duration import duration_microseconds, duration_string from django.utils.functional import Promise, cached_property from django.utils.ipv6 import clean_ipv6_address from django.utils.itercompat import is_iterable from django.utils.text import capfirst from django.utils.translation import gettext_lazy as _ __all__ = [ "AutoField", "BLANK_CHOICE_DASH", "BigAutoField", "BigIntegerField", "BinaryField", "BooleanField", "CharField", "CommaSeparatedIntegerField", "DateField", "DateTimeField", "DecimalField", "DurationField", "EmailField", "Empty", "Field", "FilePathField", "FloatField", "GenericIPAddressField", "IPAddressField", "IntegerField", "NOT_PROVIDED", "NullBooleanField", "PositiveBigIntegerField", "PositiveIntegerField", "PositiveSmallIntegerField", "SlugField", "SmallAutoField", "SmallIntegerField", "TextField", "TimeField", "URLField", "UUIDField", ] class Empty: pass class NOT_PROVIDED: pass # The values to use for "blank" in SelectFields. Will be appended to the start # of most "choices" lists. BLANK_CHOICE_DASH = [("", "---------")] def _load_field(app_label, model_name, field_name): return apps.get_model(app_label, model_name)._meta.get_field(field_name) # A guide to Field parameters: # # * name: The name of the field specified in the model. # * attname: The attribute to use on the model object. This is the same as # "name", except in the case of ForeignKeys, where "_id" is # appended. # * db_column: The db_column specified in the model (or None). # * column: The database column for this field. This is the same as # "attname", except if db_column is specified. # # Code that introspects values, or does other dynamic things, should use # attname. For example, this gets the primary key value of object "obj": # # getattr(obj, opts.pk.attname) def _empty(of_cls): new = Empty() new.__class__ = of_cls return new def return_None(): return None @total_ordering class Field(RegisterLookupMixin): """Base class for all field types""" # Designates whether empty strings fundamentally are allowed at the # database level. empty_strings_allowed = True empty_values = list(validators.EMPTY_VALUES) # These track each time a Field instance is created. Used to retain order. # The auto_creation_counter is used for fields that Django implicitly # creates, creation_counter is used for all user-specified fields. creation_counter = 0 auto_creation_counter = -1 default_validators = [] # Default set of validators default_error_messages = { "invalid_choice": _("Value %(value)r is not a valid choice."), "null": _("This field cannot be null."), "blank": _("This field cannot be blank."), "unique": _("%(model_name)s with this %(field_label)s already exists."), "unique_for_date": _( # Translators: The 'lookup_type' is one of 'date', 'year' or # 'month'. Eg: "Title must be unique for pub_date year" "%(field_label)s must be unique for " "%(date_field_label)s %(lookup_type)s." ), } system_check_deprecated_details = None system_check_removed_details = None # Attributes that don't affect a column definition. # These attributes are ignored when altering the field. non_db_attrs = ( "blank", "choices", "db_column", "editable", "error_messages", "help_text", "limit_choices_to", # Database-level options are not supported, see #21961. "on_delete", "related_name", "related_query_name", "validators", "verbose_name", ) # Field flags hidden = False many_to_many = None many_to_one = None one_to_many = None one_to_one = None related_model = None descriptor_class = DeferredAttribute # Generic field type description, usually overridden by subclasses def _description(self): return _("Field of type: %(field_type)s") % { "field_type": self.__class__.__name__ } description = property(_description) def __init__( self, verbose_name=None, name=None, primary_key=False, max_length=None, unique=False, blank=False, null=False, db_index=False, rel=None, default=NOT_PROVIDED, editable=True, serialize=True, unique_for_date=None, unique_for_month=None, unique_for_year=None, choices=None, help_text="", db_column=None, db_tablespace=None, auto_created=False, validators=(), error_messages=None, ): self.name = name self.verbose_name = verbose_name # May be set by set_attributes_from_name self._verbose_name = verbose_name # Store original for deconstruction self.primary_key = primary_key self.max_length, self._unique = max_length, unique self.blank, self.null = blank, null self.remote_field = rel self.is_relation = self.remote_field is not None self.default = default self.editable = editable self.serialize = serialize self.unique_for_date = unique_for_date self.unique_for_month = unique_for_month self.unique_for_year = unique_for_year if isinstance(choices, collections.abc.Iterator): choices = list(choices) self.choices = choices self.help_text = help_text self.db_index = db_index self.db_column = db_column self._db_tablespace = db_tablespace self.auto_created = auto_created # Adjust the appropriate creation counter, and save our local copy. if auto_created: self.creation_counter = Field.auto_creation_counter Field.auto_creation_counter -= 1 else: self.creation_counter = Field.creation_counter Field.creation_counter += 1 self._validators = list(validators) # Store for deconstruction later self._error_messages = error_messages # Store for deconstruction later def __str__(self): """ Return "app_label.model_label.field_name" for fields attached to models. """ if not hasattr(self, "model"): return super().__str__() model = self.model return "%s.%s" % (model._meta.label, self.name) def __repr__(self): """Display the module, class, and name of the field.""" path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) name = getattr(self, "name", None) if name is not None: return "<%s: %s>" % (path, name) return "<%s>" % path def check(self, **kwargs): return [ *self._check_field_name(), *self._check_choices(), *self._check_db_index(), *self._check_null_allowed_for_primary_keys(), *self._check_backend_specific_checks(**kwargs), *self._check_validators(), *self._check_deprecation_details(), ] def _check_field_name(self): """ Check if field name is valid, i.e. 1) does not end with an underscore, 2) does not contain "__" and 3) is not "pk". """ if self.name.endswith("_"): return [ checks.Error( "Field names must not end with an underscore.", obj=self, id="fields.E001", ) ] elif LOOKUP_SEP in self.name: return [ checks.Error( 'Field names must not contain "%s".' % LOOKUP_SEP, obj=self, id="fields.E002", ) ] elif self.name == "pk": return [ checks.Error( "'pk' is a reserved word that cannot be used as a field name.", obj=self, id="fields.E003", ) ] else: return [] @classmethod def _choices_is_value(cls, value): return isinstance(value, (str, Promise)) or not is_iterable(value) def _check_choices(self): if not self.choices: return [] if not is_iterable(self.choices) or isinstance(self.choices, str): return [ checks.Error( "'choices' must be an iterable (e.g., a list or tuple).", obj=self, id="fields.E004", ) ] choice_max_length = 0 # Expect [group_name, [value, display]] for choices_group in self.choices: try: group_name, group_choices = choices_group except (TypeError, ValueError): # Containing non-pairs break try: if not all( self._choices_is_value(value) and self._choices_is_value(human_name) for value, human_name in group_choices ): break if self.max_length is not None and group_choices: choice_max_length = max( [ choice_max_length, *( len(value) for value, _ in group_choices if isinstance(value, str) ), ] ) except (TypeError, ValueError): # No groups, choices in the form [value, display] value, human_name = group_name, group_choices if not self._choices_is_value(value) or not self._choices_is_value( human_name ): break if self.max_length is not None and isinstance(value, str): choice_max_length = max(choice_max_length, len(value)) # Special case: choices=['ab'] if isinstance(choices_group, str): break else: if self.max_length is not None and choice_max_length > self.max_length: return [ checks.Error( "'max_length' is too small to fit the longest value " "in 'choices' (%d characters)." % choice_max_length, obj=self, id="fields.E009", ), ] return [] return [ checks.Error( "'choices' must be an iterable containing " "(actual value, human readable name) tuples.", obj=self, id="fields.E005", ) ] def _check_db_index(self): if self.db_index not in (None, True, False): return [ checks.Error( "'db_index' must be None, True or False.", obj=self, id="fields.E006", ) ] else: return [] def _check_null_allowed_for_primary_keys(self): if ( self.primary_key and self.null and not connection.features.interprets_empty_strings_as_nulls ): # We cannot reliably check this for backends like Oracle which # consider NULL and '' to be equal (and thus set up # character-based fields a little differently). return [ checks.Error( "Primary keys must not have null=True.", hint=( "Set null=False on the field, or " "remove primary_key=True argument." ), obj=self, id="fields.E007", ) ] else: return [] def _check_backend_specific_checks(self, databases=None, **kwargs): if databases is None: return [] app_label = self.model._meta.app_label errors = [] for alias in databases: if router.allow_migrate( alias, app_label, model_name=self.model._meta.model_name ): errors.extend(connections[alias].validation.check_field(self, **kwargs)) return errors def _check_validators(self): errors = [] for i, validator in enumerate(self.validators): if not callable(validator): errors.append( checks.Error( "All 'validators' must be callable.", hint=( "validators[{i}] ({repr}) isn't a function or " "instance of a validator class.".format( i=i, repr=repr(validator), ) ), obj=self, id="fields.E008", ) ) return errors def _check_deprecation_details(self): if self.system_check_removed_details is not None: return [ checks.Error( self.system_check_removed_details.get( "msg", "%s has been removed except for support in historical " "migrations." % self.__class__.__name__, ), hint=self.system_check_removed_details.get("hint"), obj=self, id=self.system_check_removed_details.get("id", "fields.EXXX"), ) ] elif self.system_check_deprecated_details is not None: return [ checks.Warning( self.system_check_deprecated_details.get( "msg", "%s has been deprecated." % self.__class__.__name__ ), hint=self.system_check_deprecated_details.get("hint"), obj=self, id=self.system_check_deprecated_details.get("id", "fields.WXXX"), ) ] return [] def get_col(self, alias, output_field=None): if alias == self.model._meta.db_table and ( output_field is None or output_field == self ): return self.cached_col from django.db.models.expressions import Col return Col(alias, self, output_field) @cached_property def cached_col(self): from django.db.models.expressions import Col return Col(self.model._meta.db_table, self) def select_format(self, compiler, sql, params): """ Custom format for select clauses. For example, GIS columns need to be selected as AsText(table.col) on MySQL as the table.col data can't be used by Django. """ return sql, params def deconstruct(self): """ Return enough information to recreate the field as a 4-tuple: * The name of the field on the model, if contribute_to_class() has been run. * The import path of the field, including the class, e.g. django.db.models.IntegerField. This should be the most portable version, so less specific may be better. * A list of positional arguments. * A dict of keyword arguments. Note that the positional or keyword arguments must contain values of the following types (including inner values of collection types): * None, bool, str, int, float, complex, set, frozenset, list, tuple, dict * UUID * datetime.datetime (naive), datetime.date * top-level classes, top-level functions - will be referenced by their full import path * Storage instances - these have their own deconstruct() method This is because the values here must be serialized into a text format (possibly new Python code, possibly JSON) and these are the only types with encoding handlers defined. There's no need to return the exact way the field was instantiated this time, just ensure that the resulting field is the same - prefer keyword arguments over positional ones, and omit parameters with their default values. """ # Short-form way of fetching all the default parameters keywords = {} possibles = { "verbose_name": None, "primary_key": False, "max_length": None, "unique": False, "blank": False, "null": False, "db_index": False, "default": NOT_PROVIDED, "editable": True, "serialize": True, "unique_for_date": None, "unique_for_month": None, "unique_for_year": None, "choices": None, "help_text": "", "db_column": None, "db_tablespace": None, "auto_created": False, "validators": [], "error_messages": None, } attr_overrides = { "unique": "_unique", "error_messages": "_error_messages", "validators": "_validators", "verbose_name": "_verbose_name", "db_tablespace": "_db_tablespace", } equals_comparison = {"choices", "validators"} for name, default in possibles.items(): value = getattr(self, attr_overrides.get(name, name)) # Unroll anything iterable for choices into a concrete list if name == "choices" and isinstance(value, collections.abc.Iterable): value = list(value) # Do correct kind of comparison if name in equals_comparison: if value != default: keywords[name] = value else: if value is not default: keywords[name] = value # Work out path - we shorten it for known Django core fields path = "%s.%s" % (self.__class__.__module__, self.__class__.__qualname__) if path.startswith("django.db.models.fields.related"): path = path.replace("django.db.models.fields.related", "django.db.models") elif path.startswith("django.db.models.fields.files"): path = path.replace("django.db.models.fields.files", "django.db.models") elif path.startswith("django.db.models.fields.json"): path = path.replace("django.db.models.fields.json", "django.db.models") elif path.startswith("django.db.models.fields.proxy"): path = path.replace("django.db.models.fields.proxy", "django.db.models") elif path.startswith("django.db.models.fields"): path = path.replace("django.db.models.fields", "django.db.models") # Return basic info - other fields should override this. return (self.name, path, [], keywords) def clone(self): """ Uses deconstruct() to clone a new copy of this Field. Will not preserve any class attachments/attribute names. """ name, path, args, kwargs = self.deconstruct() return self.__class__(*args, **kwargs) def __eq__(self, other): # Needed for @total_ordering if isinstance(other, Field): return self.creation_counter == other.creation_counter and getattr( self, "model", None ) == getattr(other, "model", None) return NotImplemented def __lt__(self, other): # This is needed because bisect does not take a comparison function. # Order by creation_counter first for backward compatibility. if isinstance(other, Field): if ( self.creation_counter != other.creation_counter or not hasattr(self, "model") and not hasattr(other, "model") ): return self.creation_counter < other.creation_counter elif hasattr(self, "model") != hasattr(other, "model"): return not hasattr(self, "model") # Order no-model fields first else: # creation_counter's are equal, compare only models. return (self.model._meta.app_label, self.model._meta.model_name) < ( other.model._meta.app_label, other.model._meta.model_name, ) return NotImplemented def __hash__(self): return hash(self.creation_counter) def __deepcopy__(self, memodict): # We don't have to deepcopy very much here, since most things are not # intended to be altered after initial creation. obj = copy.copy(self) if self.remote_field: obj.remote_field = copy.copy(self.remote_field) if hasattr(self.remote_field, "field") and self.remote_field.field is self: obj.remote_field.field = obj memodict[id(self)] = obj return obj def __copy__(self): # We need to avoid hitting __reduce__, so define this # slightly weird copy construct. obj = Empty() obj.__class__ = self.__class__ obj.__dict__ = self.__dict__.copy() return obj def __reduce__(self): """ Pickling should return the model._meta.fields instance of the field, not a new copy of that field. So, use the app registry to load the model and then the field back. """ if not hasattr(self, "model"): # Fields are sometimes used without attaching them to models (for # example in aggregation). In this case give back a plain field # instance. The code below will create a new empty instance of # class self.__class__, then update its dict with self.__dict__ # values - so, this is very close to normal pickle. state = self.__dict__.copy() # The _get_default cached_property can't be pickled due to lambda # usage. state.pop("_get_default", None) return _empty, (self.__class__,), state return _load_field, ( self.model._meta.app_label, self.model._meta.object_name, self.name, ) def get_pk_value_on_save(self, instance): """ Hook to generate new PK values on save. This method is called when saving instances with no primary key value set. If this method returns something else than None, then the returned value is used when saving the new instance. """ if self.default: return self.get_default() return None def to_python(self, value): """ Convert the input value into the expected Python data type, raising django.core.exceptions.ValidationError if the data can't be converted. Return the converted value. Subclasses should override this. """ return value @cached_property def error_messages(self): messages = {} for c in reversed(self.__class__.__mro__): messages.update(getattr(c, "default_error_messages", {})) messages.update(self._error_messages or {}) return messages @cached_property def validators(self): """ Some validators can't be created at field initialization time. This method provides a way to delay their creation until required. """ return [*self.default_validators, *self._validators] def run_validators(self, value): if value in self.empty_values: return errors = [] for v in self.validators: try: v(value) except exceptions.ValidationError as e: if hasattr(e, "code") and e.code in self.error_messages: e.message = self.error_messages[e.code] errors.extend(e.error_list) if errors: raise exceptions.ValidationError(errors) def validate(self, value, model_instance): """ Validate value and raise ValidationError if necessary. Subclasses should override this to provide validation logic. """ if not self.editable: # Skip validation for non-editable fields. return if self.choices is not None and value not in self.empty_values: for option_key, option_value in self.choices: if isinstance(option_value, (list, tuple)): # This is an optgroup, so look inside the group for # options. for optgroup_key, optgroup_value in option_value: if value == optgroup_key: return elif value == option_key: return raise exceptions.ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) if value is None and not self.null: raise exceptions.ValidationError(self.error_messages["null"], code="null") if not self.blank and value in self.empty_values: raise exceptions.ValidationError(self.error_messages["blank"], code="blank") def clean(self, value, model_instance): """ Convert the value's type and run validation. Validation errors from to_python() and validate() are propagated. Return the correct value if no error is raised. """ value = self.to_python(value) self.validate(value, model_instance) self.run_validators(value) return value def db_type_parameters(self, connection): return DictWrapper(self.__dict__, connection.ops.quote_name, "qn_") def db_check(self, connection): """ Return the database column check constraint for this field, for the provided connection. Works the same way as db_type() for the case that get_internal_type() does not map to a preexisting model field. """ data = self.db_type_parameters(connection) try: return ( connection.data_type_check_constraints[self.get_internal_type()] % data ) except KeyError: return None def db_type(self, connection): """ Return the database column data type for this field, for the provided connection. """ # The default implementation of this method looks at the # backend-specific data_types dictionary, looking up the field by its # "internal type". # # A Field class can implement the get_internal_type() method to specify # which *preexisting* Django Field class it's most similar to -- i.e., # a custom field might be represented by a TEXT column type, which is # the same as the TextField Django field type, which means the custom # field's get_internal_type() returns 'TextField'. # # But the limitation of the get_internal_type() / data_types approach # is that it cannot handle database column types that aren't already # mapped to one of the built-in Django field types. In this case, you # can implement db_type() instead of get_internal_type() to specify # exactly which wacky database column type you want to use. data = self.db_type_parameters(connection) try: return connection.data_types[self.get_internal_type()] % data except KeyError: return None def rel_db_type(self, connection): """ Return the data type that a related field pointing to this field should use. For example, this method is called by ForeignKey and OneToOneField to determine its data type. """ return self.db_type(connection) def cast_db_type(self, connection): """Return the data type to use in the Cast() function.""" db_type = connection.ops.cast_data_types.get(self.get_internal_type()) if db_type: return db_type % self.db_type_parameters(connection) return self.db_type(connection) def db_parameters(self, connection): """ Extension of db_type(), providing a range of different return values (type, checks). This will look at db_type(), allowing custom model fields to override it. """ type_string = self.db_type(connection) check_string = self.db_check(connection) return { "type": type_string, "check": check_string, } def db_type_suffix(self, connection): return connection.data_types_suffix.get(self.get_internal_type()) def get_db_converters(self, connection): if hasattr(self, "from_db_value"): return [self.from_db_value] return [] @property def unique(self): return self._unique or self.primary_key @property def db_tablespace(self): return self._db_tablespace or settings.DEFAULT_INDEX_TABLESPACE @property def db_returning(self): """ Private API intended only to be used by Django itself. Currently only the PostgreSQL backend supports returning multiple fields on a model. """ return False def set_attributes_from_name(self, name): self.name = self.name or name self.attname, self.column = self.get_attname_column() self.concrete = self.column is not None if self.verbose_name is None and self.name: self.verbose_name = self.name.replace("_", " ") def contribute_to_class(self, cls, name, private_only=False): """ Register the field with the model class it belongs to. If private_only is True, create a separate instance of this field for every subclass of cls, even if cls is not an abstract model. """ self.set_attributes_from_name(name) self.model = cls cls._meta.add_field(self, private=private_only) if self.column: setattr(cls, self.attname, self.descriptor_class(self)) if self.choices is not None: # Don't override a get_FOO_display() method defined explicitly on # this class, but don't check methods derived from inheritance, to # allow overriding inherited choices. For more complex inheritance # structures users should override contribute_to_class(). if "get_%s_display" % self.name not in cls.__dict__: setattr( cls, "get_%s_display" % self.name, partialmethod(cls._get_FIELD_display, field=self), ) def get_filter_kwargs_for_object(self, obj): """ Return a dict that when passed as kwargs to self.model.filter(), would yield all instances having the same value for this field as obj has. """ return {self.name: getattr(obj, self.attname)} def get_attname(self): return self.name def get_attname_column(self): attname = self.get_attname() column = self.db_column or attname return attname, column def get_internal_type(self): return self.__class__.__name__ def pre_save(self, model_instance, add): """Return field's value just before saving.""" return getattr(model_instance, self.attname) def get_prep_value(self, value): """Perform preliminary non-db specific value checks and conversions.""" if isinstance(value, Promise): value = value._proxy____cast() return value def get_db_prep_value(self, value, connection, prepared=False): """ Return field's value prepared for interacting with the database backend. Used by the default implementations of get_db_prep_save(). """ if not prepared: value = self.get_prep_value(value) return value def get_db_prep_save(self, value, connection): """Return field's value prepared for saving into a database.""" return self.get_db_prep_value(value, connection=connection, prepared=False) def has_default(self): """Return a boolean of whether this field has a default value.""" return self.default is not NOT_PROVIDED def get_default(self): """Return the default value for this field.""" return self._get_default() @cached_property def _get_default(self): if self.has_default(): if callable(self.default): return self.default return lambda: self.default if ( not self.empty_strings_allowed or self.null and not connection.features.interprets_empty_strings_as_nulls ): return return_None return str # return empty string def get_choices( self, include_blank=True, blank_choice=BLANK_CHOICE_DASH, limit_choices_to=None, ordering=(), ): """ Return choices with a default blank choices included, for use as <select> choices for this field. """ if self.choices is not None: choices = list(self.choices) if include_blank: blank_defined = any( choice in ("", None) for choice, _ in self.flatchoices ) if not blank_defined: choices = blank_choice + choices return choices rel_model = self.remote_field.model limit_choices_to = limit_choices_to or self.get_limit_choices_to() choice_func = operator.attrgetter( self.remote_field.get_related_field().attname if hasattr(self.remote_field, "get_related_field") else "pk" ) qs = rel_model._default_manager.complex_filter(limit_choices_to) if ordering: qs = qs.order_by(*ordering) return (blank_choice if include_blank else []) + [ (choice_func(x), str(x)) for x in qs ] def value_to_string(self, obj): """ Return a string value of this field from the passed obj. This is used by the serialization framework. """ return str(self.value_from_object(obj)) def _get_flatchoices(self): """Flattened version of choices tuple.""" if self.choices is None: return [] flat = [] for choice, value in self.choices: if isinstance(value, (list, tuple)): flat.extend(value) else: flat.append((choice, value)) return flat flatchoices = property(_get_flatchoices) def save_form_data(self, instance, data): setattr(instance, self.name, data) def formfield(self, form_class=None, choices_form_class=None, **kwargs): """Return a django.forms.Field instance for this field.""" defaults = { "required": not self.blank, "label": capfirst(self.verbose_name), "help_text": self.help_text, } if self.has_default(): if callable(self.default): defaults["initial"] = self.default defaults["show_hidden_initial"] = True else: defaults["initial"] = self.get_default() if self.choices is not None: # Fields with choices get special treatment. include_blank = self.blank or not ( self.has_default() or "initial" in kwargs ) defaults["choices"] = self.get_choices(include_blank=include_blank) defaults["coerce"] = self.to_python if self.null: defaults["empty_value"] = None if choices_form_class is not None: form_class = choices_form_class else: form_class = forms.TypedChoiceField # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that TypedChoiceField will understand. for k in list(kwargs): if k not in ( "coerce", "empty_value", "choices", "required", "widget", "label", "initial", "help_text", "error_messages", "show_hidden_initial", "disabled", ): del kwargs[k] defaults.update(kwargs) if form_class is None: form_class = forms.CharField return form_class(**defaults) def value_from_object(self, obj): """Return the value of this field in the given model instance.""" return getattr(obj, self.attname) class BooleanField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be either True or False."), "invalid_nullable": _("“%(value)s” value must be either True, False, or None."), } description = _("Boolean (Either True or False)") def get_internal_type(self): return "BooleanField" def to_python(self, value): if self.null and value in self.empty_values: return None if value in (True, False): # 1/0 are equal to True/False. bool() converts former to latter. return bool(value) if value in ("t", "True", "1"): return True if value in ("f", "False", "0"): return False raise exceptions.ValidationError( self.error_messages["invalid_nullable" if self.null else "invalid"], code="invalid", params={"value": value}, ) def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return self.to_python(value) def formfield(self, **kwargs): if self.choices is not None: include_blank = not (self.has_default() or "initial" in kwargs) defaults = {"choices": self.get_choices(include_blank=include_blank)} else: form_class = forms.NullBooleanField if self.null else forms.BooleanField # In HTML checkboxes, 'required' means "must be checked" which is # different from the choices case ("must select some value"). # required=False allows unchecked checkboxes. defaults = {"form_class": form_class, "required": False} return super().formfield(**{**defaults, **kwargs}) def select_format(self, compiler, sql, params): sql, params = super().select_format(compiler, sql, params) # Filters that match everything are handled as empty strings in the # WHERE clause, but in SELECT or GROUP BY list they must use a # predicate that's always True. if sql == "": sql = "1" return sql, params class CharField(Field): description = _("String (up to %(max_length)s)") def __init__(self, *args, db_collation=None, **kwargs): super().__init__(*args, **kwargs) self.db_collation = db_collation if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) def check(self, **kwargs): databases = kwargs.get("databases") or [] return [ *super().check(**kwargs), *self._check_db_collation(databases), *self._check_max_length_attribute(**kwargs), ] def _check_max_length_attribute(self, **kwargs): if self.max_length is None: return [ checks.Error( "CharFields must define a 'max_length' attribute.", obj=self, id="fields.E120", ) ] elif ( not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or self.max_length <= 0 ): return [ checks.Error( "'max_length' must be a positive integer.", obj=self, id="fields.E121", ) ] else: return [] def _check_db_collation(self, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( self.db_collation is None or "supports_collation_on_charfield" in self.model._meta.required_db_features or connection.features.supports_collation_on_charfield ): errors.append( checks.Error( "%s does not support a database collation on " "CharFields." % connection.display_name, obj=self, id="fields.E190", ), ) return errors def cast_db_type(self, connection): if self.max_length is None: return connection.ops.cast_char_field_without_max_length return super().cast_db_type(connection) def db_parameters(self, connection): db_params = super().db_parameters(connection) db_params["collation"] = self.db_collation return db_params def get_internal_type(self): return "CharField" def to_python(self, value): if isinstance(value, str) or value is None: return value return str(value) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). defaults = {"max_length": self.max_length} # TODO: Handle multiple backends with different feature flags. if self.null and not connection.features.interprets_empty_strings_as_nulls: defaults["empty_value"] = None defaults.update(kwargs) return super().formfield(**defaults) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.db_collation: kwargs["db_collation"] = self.db_collation return name, path, args, kwargs class CommaSeparatedIntegerField(CharField): default_validators = [validators.validate_comma_separated_integer_list] description = _("Comma-separated integers") system_check_removed_details = { "msg": ( "CommaSeparatedIntegerField is removed except for support in " "historical migrations." ), "hint": ( "Use CharField(validators=[validate_comma_separated_integer_list]) " "instead." ), "id": "fields.E901", } def _to_naive(value): if timezone.is_aware(value): value = timezone.make_naive(value, datetime.timezone.utc) return value def _get_naive_now(): return _to_naive(timezone.now()) class DateTimeCheckMixin: def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_mutually_exclusive_options(), *self._check_fix_default_value(), ] def _check_mutually_exclusive_options(self): # auto_now, auto_now_add, and default are mutually exclusive # options. The use of more than one of these options together # will trigger an Error mutually_exclusive_options = [ self.auto_now_add, self.auto_now, self.has_default(), ] enabled_options = [ option not in (None, False) for option in mutually_exclusive_options ].count(True) if enabled_options > 1: return [ checks.Error( "The options auto_now, auto_now_add, and default " "are mutually exclusive. Only one of these options " "may be present.", obj=self, id="fields.E160", ) ] else: return [] def _check_fix_default_value(self): return [] # Concrete subclasses use this in their implementations of # _check_fix_default_value(). def _check_if_value_fixed(self, value, now=None): """ Check if the given value appears to have been provided as a "fixed" time value, and include a warning in the returned list if it does. The value argument must be a date object or aware/naive datetime object. If now is provided, it must be a naive datetime object. """ if now is None: now = _get_naive_now() offset = datetime.timedelta(seconds=10) lower = now - offset upper = now + offset if isinstance(value, datetime.datetime): value = _to_naive(value) else: assert isinstance(value, datetime.date) lower = lower.date() upper = upper.date() if lower <= value <= upper: return [ checks.Warning( "Fixed default value provided.", hint=( "It seems you set a fixed date / time / datetime " "value as default for this field. This may not be " "what you want. If you want to have the current date " "as default, use `django.utils.timezone.now`" ), obj=self, id="fields.W161", ) ] return [] class DateField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid date format. It must be " "in YYYY-MM-DD format." ), "invalid_date": _( "“%(value)s” value has the correct format (YYYY-MM-DD) " "but it is an invalid date." ), } description = _("Date (without time)") def __init__( self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs ): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs["editable"] = False kwargs["blank"] = True super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, datetime.datetime): value = _to_naive(value).date() elif isinstance(value, datetime.date): pass else: # No explicit date / datetime value -- no checks necessary return [] # At this point, value is a date object. return self._check_if_value_fixed(value) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.auto_now: kwargs["auto_now"] = True if self.auto_now_add: kwargs["auto_now_add"] = True if self.auto_now or self.auto_now_add: del kwargs["editable"] del kwargs["blank"] return name, path, args, kwargs def get_internal_type(self): return "DateField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): if settings.USE_TZ and timezone.is_aware(value): # Convert aware datetimes to the default time zone # before casting them to dates (#17742). default_timezone = timezone.get_default_timezone() value = timezone.make_naive(value, default_timezone) return value.date() if isinstance(value, datetime.date): return value try: parsed = parse_date(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_date"], code="invalid_date", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.date.today() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def contribute_to_class(self, cls, name, **kwargs): super().contribute_to_class(cls, name, **kwargs) if not self.null: setattr( cls, "get_next_by_%s" % self.name, partialmethod( cls._get_next_or_previous_by_FIELD, field=self, is_next=True ), ) setattr( cls, "get_previous_by_%s" % self.name, partialmethod( cls._get_next_or_previous_by_FIELD, field=self, is_next=False ), ) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts dates into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_datefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DateField, **kwargs, } ) class DateTimeField(DateField): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format." ), "invalid_date": _( "“%(value)s” value has the correct format " "(YYYY-MM-DD) but it is an invalid date." ), "invalid_datetime": _( "“%(value)s” value has the correct format " "(YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]) " "but it is an invalid date/time." ), } description = _("Date (with time)") # __init__ is inherited from DateField def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, (datetime.datetime, datetime.date)): return self._check_if_value_fixed(value) # No explicit date / datetime value -- no checks necessary. return [] def get_internal_type(self): return "DateTimeField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): value = datetime.datetime(value.year, value.month, value.day) if settings.USE_TZ: # For backwards compatibility, interpret naive datetimes in # local time. This won't work during DST change, but we can't # do much about it, so we let the exceptions percolate up the # call stack. warnings.warn( "DateTimeField %s.%s received a naive datetime " "(%s) while time zone support is active." % (self.model.__name__, self.name, value), RuntimeWarning, ) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value try: parsed = parse_datetime(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_datetime"], code="invalid_datetime", params={"value": value}, ) try: parsed = parse_date(value) if parsed is not None: return datetime.datetime(parsed.year, parsed.month, parsed.day) except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_date"], code="invalid_date", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = timezone.now() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) # contribute_to_class is inherited from DateField, it registers # get_next_by_FOO and get_prev_by_FOO def get_prep_value(self, value): value = super().get_prep_value(value) value = self.to_python(value) if value is not None and settings.USE_TZ and timezone.is_naive(value): # For backwards compatibility, interpret naive datetimes in local # time. This won't work during DST change, but we can't do much # about it, so we let the exceptions percolate up the call stack. try: name = "%s.%s" % (self.model.__name__, self.name) except AttributeError: name = "(unbound)" warnings.warn( "DateTimeField %s received a naive datetime (%s)" " while time zone support is active." % (name, value), RuntimeWarning, ) default_timezone = timezone.get_default_timezone() value = timezone.make_aware(value, default_timezone) return value def get_db_prep_value(self, value, connection, prepared=False): # Casts datetimes into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_datetimefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DateTimeField, **kwargs, } ) class DecimalField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be a decimal number."), } description = _("Decimal number") def __init__( self, verbose_name=None, name=None, max_digits=None, decimal_places=None, **kwargs, ): self.max_digits, self.decimal_places = max_digits, decimal_places super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): errors = super().check(**kwargs) digits_errors = [ *self._check_decimal_places(), *self._check_max_digits(), ] if not digits_errors: errors.extend(self._check_decimal_places_and_max_digits(**kwargs)) else: errors.extend(digits_errors) return errors def _check_decimal_places(self): try: decimal_places = int(self.decimal_places) if decimal_places < 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'decimal_places' attribute.", obj=self, id="fields.E130", ) ] except ValueError: return [ checks.Error( "'decimal_places' must be a non-negative integer.", obj=self, id="fields.E131", ) ] else: return [] def _check_max_digits(self): try: max_digits = int(self.max_digits) if max_digits <= 0: raise ValueError() except TypeError: return [ checks.Error( "DecimalFields must define a 'max_digits' attribute.", obj=self, id="fields.E132", ) ] except ValueError: return [ checks.Error( "'max_digits' must be a positive integer.", obj=self, id="fields.E133", ) ] else: return [] def _check_decimal_places_and_max_digits(self, **kwargs): if int(self.decimal_places) > int(self.max_digits): return [ checks.Error( "'max_digits' must be greater or equal to 'decimal_places'.", obj=self, id="fields.E134", ) ] return [] @cached_property def validators(self): return super().validators + [ validators.DecimalValidator(self.max_digits, self.decimal_places) ] @cached_property def context(self): return decimal.Context(prec=self.max_digits) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.max_digits is not None: kwargs["max_digits"] = self.max_digits if self.decimal_places is not None: kwargs["decimal_places"] = self.decimal_places return name, path, args, kwargs def get_internal_type(self): return "DecimalField" def to_python(self, value): if value is None: return value if isinstance(value, float): if math.isnan(value): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) return self.context.create_decimal_from_float(value) try: return decimal.Decimal(value) except (decimal.InvalidOperation, TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def get_db_prep_save(self, value, connection): return connection.ops.adapt_decimalfield_value( self.to_python(value), self.max_digits, self.decimal_places ) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): return super().formfield( **{ "max_digits": self.max_digits, "decimal_places": self.decimal_places, "form_class": forms.DecimalField, **kwargs, } ) class DurationField(Field): """ Store timedelta objects. Use interval on PostgreSQL, INTERVAL DAY TO SECOND on Oracle, and bigint of microseconds on other databases. """ empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "[DD] [[HH:]MM:]ss[.uuuuuu] format." ) } description = _("Duration") def get_internal_type(self): return "DurationField" def to_python(self, value): if value is None: return value if isinstance(value, datetime.timedelta): return value try: parsed = parse_duration(value) except ValueError: pass else: if parsed is not None: return parsed raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def get_db_prep_value(self, value, connection, prepared=False): if connection.features.has_native_duration_field: return value if value is None: return None return duration_microseconds(value) def get_db_converters(self, connection): converters = [] if not connection.features.has_native_duration_field: converters.append(connection.ops.convert_durationfield_value) return converters + super().get_db_converters(connection) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else duration_string(val) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.DurationField, **kwargs, } ) class EmailField(CharField): default_validators = [validators.validate_email] description = _("Email address") def __init__(self, *args, **kwargs): # max_length=254 to be compliant with RFCs 3696 and 5321 kwargs.setdefault("max_length", 254) super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() # We do not exclude max_length if it matches default as we want to change # the default in future. return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause email validation to be performed # twice. return super().formfield( **{ "form_class": forms.EmailField, **kwargs, } ) class FilePathField(Field): description = _("File path") def __init__( self, verbose_name=None, name=None, path="", match=None, recursive=False, allow_files=True, allow_folders=False, **kwargs, ): self.path, self.match, self.recursive = path, match, recursive self.allow_files, self.allow_folders = allow_files, allow_folders kwargs.setdefault("max_length", 100) super().__init__(verbose_name, name, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_allowing_files_or_folders(**kwargs), ] def _check_allowing_files_or_folders(self, **kwargs): if not self.allow_files and not self.allow_folders: return [ checks.Error( "FilePathFields must have either 'allow_files' or 'allow_folders' " "set to True.", obj=self, id="fields.E140", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.path != "": kwargs["path"] = self.path if self.match is not None: kwargs["match"] = self.match if self.recursive is not False: kwargs["recursive"] = self.recursive if self.allow_files is not True: kwargs["allow_files"] = self.allow_files if self.allow_folders is not False: kwargs["allow_folders"] = self.allow_folders if kwargs.get("max_length") == 100: del kwargs["max_length"] return name, path, args, kwargs def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return str(value) def formfield(self, **kwargs): return super().formfield( **{ "path": self.path() if callable(self.path) else self.path, "match": self.match, "recursive": self.recursive, "form_class": forms.FilePathField, "allow_files": self.allow_files, "allow_folders": self.allow_folders, **kwargs, } ) def get_internal_type(self): return "FilePathField" class FloatField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be a float."), } description = _("Floating point number") def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return float(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e def get_internal_type(self): return "FloatField" def to_python(self, value): if value is None: return value try: return float(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.FloatField, **kwargs, } ) class IntegerField(Field): empty_strings_allowed = False default_error_messages = { "invalid": _("“%(value)s” value must be an integer."), } description = _("Integer") def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_max_length_warning(), ] def _check_max_length_warning(self): if self.max_length is not None: return [ checks.Warning( "'max_length' is ignored when used with %s." % self.__class__.__name__, hint="Remove 'max_length' from field", obj=self, id="fields.W122", ) ] return [] @cached_property def validators(self): # These validators can't be added at field initialization time since # they're based on values retrieved from `connection`. validators_ = super().validators internal_type = self.get_internal_type() min_value, max_value = connection.ops.integer_field_range(internal_type) if min_value is not None and not any( ( isinstance(validator, validators.MinValueValidator) and ( validator.limit_value() if callable(validator.limit_value) else validator.limit_value ) >= min_value ) for validator in validators_ ): validators_.append(validators.MinValueValidator(min_value)) if max_value is not None and not any( ( isinstance(validator, validators.MaxValueValidator) and ( validator.limit_value() if callable(validator.limit_value) else validator.limit_value ) <= max_value ) for validator in validators_ ): validators_.append(validators.MaxValueValidator(max_value)) return validators_ def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return int(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e def get_internal_type(self): return "IntegerField" def to_python(self, value): if value is None: return value try: return int(value) except (TypeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.IntegerField, **kwargs, } ) class BigIntegerField(IntegerField): description = _("Big (8 byte) integer") MAX_BIGINT = 9223372036854775807 def get_internal_type(self): return "BigIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": -BigIntegerField.MAX_BIGINT - 1, "max_value": BigIntegerField.MAX_BIGINT, **kwargs, } ) class SmallIntegerField(IntegerField): description = _("Small integer") def get_internal_type(self): return "SmallIntegerField" class IPAddressField(Field): empty_strings_allowed = False description = _("IPv4 address") system_check_removed_details = { "msg": ( "IPAddressField has been removed except for support in " "historical migrations." ), "hint": "Use GenericIPAddressField instead.", "id": "fields.E900", } def __init__(self, *args, **kwargs): kwargs["max_length"] = 15 super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None return str(value) def get_internal_type(self): return "IPAddressField" class GenericIPAddressField(Field): empty_strings_allowed = False description = _("IP address") default_error_messages = {} def __init__( self, verbose_name=None, name=None, protocol="both", unpack_ipv4=False, *args, **kwargs, ): self.unpack_ipv4 = unpack_ipv4 self.protocol = protocol ( self.default_validators, invalid_error_message, ) = validators.ip_address_validators(protocol, unpack_ipv4) self.default_error_messages["invalid"] = invalid_error_message kwargs["max_length"] = 39 super().__init__(verbose_name, name, *args, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_blank_and_null_values(**kwargs), ] def _check_blank_and_null_values(self, **kwargs): if not getattr(self, "null", False) and getattr(self, "blank", False): return [ checks.Error( "GenericIPAddressFields cannot have blank=True if null=False, " "as blank values are stored as nulls.", obj=self, id="fields.E150", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.unpack_ipv4 is not False: kwargs["unpack_ipv4"] = self.unpack_ipv4 if self.protocol != "both": kwargs["protocol"] = self.protocol if kwargs.get("max_length") == 39: del kwargs["max_length"] return name, path, args, kwargs def get_internal_type(self): return "GenericIPAddressField" def to_python(self, value): if value is None: return None if not isinstance(value, str): value = str(value) value = value.strip() if ":" in value: return clean_ipv6_address( value, self.unpack_ipv4, self.error_messages["invalid"] ) return value def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_ipaddressfield_value(value) def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None if value and ":" in value: try: return clean_ipv6_address(value, self.unpack_ipv4) except exceptions.ValidationError: pass return str(value) def formfield(self, **kwargs): return super().formfield( **{ "protocol": self.protocol, "form_class": forms.GenericIPAddressField, **kwargs, } ) class NullBooleanField(BooleanField): default_error_messages = { "invalid": _("“%(value)s” value must be either None, True or False."), "invalid_nullable": _("“%(value)s” value must be either None, True or False."), } description = _("Boolean (Either True, False or None)") system_check_removed_details = { "msg": ( "NullBooleanField is removed except for support in historical " "migrations." ), "hint": "Use BooleanField(null=True) instead.", "id": "fields.E903", } def __init__(self, *args, **kwargs): kwargs["null"] = True kwargs["blank"] = True super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["null"] del kwargs["blank"] return name, path, args, kwargs class PositiveIntegerRelDbTypeMixin: def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) if not hasattr(cls, "integer_field_class"): cls.integer_field_class = next( ( parent for parent in cls.__mro__[1:] if issubclass(parent, IntegerField) ), None, ) def rel_db_type(self, connection): """ Return the data type that a related field pointing to this field should use. In most cases, a foreign key pointing to a positive integer primary key will have an integer column data type but some databases (e.g. MySQL) have an unsigned integer type. In that case (related_fields_match_type=True), the primary key should return its db_type. """ if connection.features.related_fields_match_type: return self.db_type(connection) else: return self.integer_field_class().db_type(connection=connection) class PositiveBigIntegerField(PositiveIntegerRelDbTypeMixin, BigIntegerField): description = _("Positive big integer") def get_internal_type(self): return "PositiveBigIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField): description = _("Positive integer") def get_internal_type(self): return "PositiveIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, SmallIntegerField): description = _("Positive small integer") def get_internal_type(self): return "PositiveSmallIntegerField" def formfield(self, **kwargs): return super().formfield( **{ "min_value": 0, **kwargs, } ) class SlugField(CharField): default_validators = [validators.validate_slug] description = _("Slug (up to %(max_length)s)") def __init__( self, *args, max_length=50, db_index=True, allow_unicode=False, **kwargs ): self.allow_unicode = allow_unicode if self.allow_unicode: self.default_validators = [validators.validate_unicode_slug] super().__init__(*args, max_length=max_length, db_index=db_index, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 50: del kwargs["max_length"] if self.db_index is False: kwargs["db_index"] = False else: del kwargs["db_index"] if self.allow_unicode is not False: kwargs["allow_unicode"] = self.allow_unicode return name, path, args, kwargs def get_internal_type(self): return "SlugField" def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.SlugField, "allow_unicode": self.allow_unicode, **kwargs, } ) class TextField(Field): description = _("Text") def __init__(self, *args, db_collation=None, **kwargs): super().__init__(*args, **kwargs) self.db_collation = db_collation def check(self, **kwargs): databases = kwargs.get("databases") or [] return [ *super().check(**kwargs), *self._check_db_collation(databases), ] def _check_db_collation(self, databases): errors = [] for db in databases: if not router.allow_migrate_model(db, self.model): continue connection = connections[db] if not ( self.db_collation is None or "supports_collation_on_textfield" in self.model._meta.required_db_features or connection.features.supports_collation_on_textfield ): errors.append( checks.Error( "%s does not support a database collation on " "TextFields." % connection.display_name, obj=self, id="fields.E190", ), ) return errors def db_parameters(self, connection): db_params = super().db_parameters(connection) db_params["collation"] = self.db_collation return db_params def get_internal_type(self): return "TextField" def to_python(self, value): if isinstance(value, str) or value is None: return value return str(value) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def formfield(self, **kwargs): # Passing max_length to forms.CharField means that the value's length # will be validated twice. This is considered acceptable since we want # the value in the form field (to pass into widget for example). return super().formfield( **{ "max_length": self.max_length, **({} if self.choices is not None else {"widget": forms.Textarea}), **kwargs, } ) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.db_collation: kwargs["db_collation"] = self.db_collation return name, path, args, kwargs class TimeField(DateTimeCheckMixin, Field): empty_strings_allowed = False default_error_messages = { "invalid": _( "“%(value)s” value has an invalid format. It must be in " "HH:MM[:ss[.uuuuuu]] format." ), "invalid_time": _( "“%(value)s” value has the correct format " "(HH:MM[:ss[.uuuuuu]]) but it is an invalid time." ), } description = _("Time") def __init__( self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs ): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs["editable"] = False kwargs["blank"] = True super().__init__(verbose_name, name, **kwargs) def _check_fix_default_value(self): """ Warn that using an actual date or datetime value is probably wrong; it's only evaluated on server startup. """ if not self.has_default(): return [] value = self.default if isinstance(value, datetime.datetime): now = None elif isinstance(value, datetime.time): now = _get_naive_now() # This will not use the right date in the race condition where now # is just before the date change and value is just past 0:00. value = datetime.datetime.combine(now.date(), value) else: # No explicit time / datetime value -- no checks necessary return [] # At this point, value is a datetime object. return self._check_if_value_fixed(value, now=now) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.auto_now is not False: kwargs["auto_now"] = self.auto_now if self.auto_now_add is not False: kwargs["auto_now_add"] = self.auto_now_add if self.auto_now or self.auto_now_add: del kwargs["blank"] del kwargs["editable"] return name, path, args, kwargs def get_internal_type(self): return "TimeField" def to_python(self, value): if value is None: return None if isinstance(value, datetime.time): return value if isinstance(value, datetime.datetime): # Not usually a good idea to pass in a datetime here (it loses # information), but this can be a side-effect of interacting with a # database backend (e.g. Oracle), so we'll be accommodating. return value.time() try: parsed = parse_time(value) if parsed is not None: return parsed except ValueError: raise exceptions.ValidationError( self.error_messages["invalid_time"], code="invalid_time", params={"value": value}, ) raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.datetime.now().time() setattr(model_instance, self.attname, value) return value else: return super().pre_save(model_instance, add) def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): # Casts times into the format expected by the backend if not prepared: value = self.get_prep_value(value) return connection.ops.adapt_timefield_value(value) def value_to_string(self, obj): val = self.value_from_object(obj) return "" if val is None else val.isoformat() def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.TimeField, **kwargs, } ) class URLField(CharField): default_validators = [validators.URLValidator()] description = _("URL") def __init__(self, verbose_name=None, name=None, **kwargs): kwargs.setdefault("max_length", 200) super().__init__(verbose_name, name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() if kwargs.get("max_length") == 200: del kwargs["max_length"] return name, path, args, kwargs def formfield(self, **kwargs): # As with CharField, this will cause URL validation to be performed # twice. return super().formfield( **{ "form_class": forms.URLField, **kwargs, } ) class BinaryField(Field): description = _("Raw binary data") empty_values = [None, b""] def __init__(self, *args, **kwargs): kwargs.setdefault("editable", False) super().__init__(*args, **kwargs) if self.max_length is not None: self.validators.append(validators.MaxLengthValidator(self.max_length)) def check(self, **kwargs): return [*super().check(**kwargs), *self._check_str_default_value()] def _check_str_default_value(self): if self.has_default() and isinstance(self.default, str): return [ checks.Error( "BinaryField's default cannot be a string. Use bytes " "content instead.", obj=self, id="fields.E170", ) ] return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() if self.editable: kwargs["editable"] = True else: del kwargs["editable"] return name, path, args, kwargs def get_internal_type(self): return "BinaryField" def get_placeholder(self, value, compiler, connection): return connection.ops.binary_placeholder_sql(value) def get_default(self): if self.has_default() and not callable(self.default): return self.default default = super().get_default() if default == "": return b"" return default def get_db_prep_value(self, value, connection, prepared=False): value = super().get_db_prep_value(value, connection, prepared) if value is not None: return connection.Database.Binary(value) return value def value_to_string(self, obj): """Binary data is serialized as base64""" return b64encode(self.value_from_object(obj)).decode("ascii") def to_python(self, value): # If it's a string, it should be base64-encoded data if isinstance(value, str): return memoryview(b64decode(value.encode("ascii"))) return value class UUIDField(Field): default_error_messages = { "invalid": _("“%(value)s” is not a valid UUID."), } description = _("Universally unique identifier") empty_strings_allowed = False def __init__(self, verbose_name=None, **kwargs): kwargs["max_length"] = 32 super().__init__(verbose_name, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["max_length"] return name, path, args, kwargs def get_internal_type(self): return "UUIDField" def get_prep_value(self, value): value = super().get_prep_value(value) return self.to_python(value) def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None if not isinstance(value, uuid.UUID): value = self.to_python(value) if connection.features.has_native_uuid_field: return value return value.hex def to_python(self, value): if value is not None and not isinstance(value, uuid.UUID): input_form = "int" if isinstance(value, int) else "hex" try: return uuid.UUID(**{input_form: value}) except (AttributeError, ValueError): raise exceptions.ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) return value def formfield(self, **kwargs): return super().formfield( **{ "form_class": forms.UUIDField, **kwargs, } ) class AutoFieldMixin: db_returning = True def __init__(self, *args, **kwargs): kwargs["blank"] = True super().__init__(*args, **kwargs) def check(self, **kwargs): return [ *super().check(**kwargs), *self._check_primary_key(), ] def _check_primary_key(self): if not self.primary_key: return [ checks.Error( "AutoFields must set primary_key=True.", obj=self, id="fields.E100", ), ] else: return [] def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["blank"] kwargs["primary_key"] = True return name, path, args, kwargs def validate(self, value, model_instance): pass def get_db_prep_value(self, value, connection, prepared=False): if not prepared: value = self.get_prep_value(value) value = connection.ops.validate_autopk_value(value) return value def contribute_to_class(self, cls, name, **kwargs): if cls._meta.auto_field: raise ValueError( "Model %s can't have more than one auto-generated field." % cls._meta.label ) super().contribute_to_class(cls, name, **kwargs) cls._meta.auto_field = self def formfield(self, **kwargs): return None class AutoFieldMeta(type): """ Metaclass to maintain backward inheritance compatibility for AutoField. It is intended that AutoFieldMixin become public API when it is possible to create a non-integer automatically-generated field using column defaults stored in the database. In many areas Django also relies on using isinstance() to check for an automatically-generated field as a subclass of AutoField. A new flag needs to be implemented on Field to be used instead. When these issues have been addressed, this metaclass could be used to deprecate inheritance from AutoField and use of isinstance() with AutoField for detecting automatically-generated fields. """ @property def _subclasses(self): return (BigAutoField, SmallAutoField) def __instancecheck__(self, instance): return isinstance(instance, self._subclasses) or super().__instancecheck__( instance ) def __subclasscheck__(self, subclass): return issubclass(subclass, self._subclasses) or super().__subclasscheck__( subclass ) class AutoField(AutoFieldMixin, IntegerField, metaclass=AutoFieldMeta): def get_internal_type(self): return "AutoField" def rel_db_type(self, connection): return IntegerField().db_type(connection=connection) class BigAutoField(AutoFieldMixin, BigIntegerField): def get_internal_type(self): return "BigAutoField" def rel_db_type(self, connection): return BigIntegerField().db_type(connection=connection) class SmallAutoField(AutoFieldMixin, SmallIntegerField): def get_internal_type(self): return "SmallAutoField" def rel_db_type(self, connection): return SmallIntegerField().db_type(connection=connection)
5910c1162eca26cacf779f397aa4b4196053fcb76df311dca18a8f06f7eadabf
from django.db import DatabaseError, InterfaceError from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): minimum_database_version = (19,) # Oracle crashes with "ORA-00932: inconsistent datatypes: expected - got # BLOB" when grouping by LOBs (#24096). allows_group_by_lob = False interprets_empty_strings_as_nulls = True has_select_for_update = True has_select_for_update_nowait = True has_select_for_update_skip_locked = True has_select_for_update_of = True select_for_update_of_column = True can_return_columns_from_insert = True supports_subqueries_in_group_by = False ignores_unnecessary_order_by_in_subqueries = False supports_transactions = True supports_timezones = False has_native_duration_field = True can_defer_constraint_checks = True supports_partially_nullable_unique_constraints = False supports_deferrable_unique_constraints = True truncates_names = True supports_tablespaces = True supports_sequence_reset = False can_introspect_materialized_views = True atomic_transactions = False nulls_order_largest = True requires_literal_defaults = True closed_cursor_error_class = InterfaceError bare_select_suffix = " FROM DUAL" # Select for update with limit can be achieved on Oracle, but not with the # current backend. supports_select_for_update_with_limit = False supports_temporal_subtraction = True # Oracle doesn't ignore quoted identifiers case but the current backend # does by uppercasing all identifiers. ignores_table_name_case = True supports_index_on_text_field = False create_test_procedure_without_params_sql = """ CREATE PROCEDURE "TEST_PROCEDURE" AS V_I INTEGER; BEGIN V_I := 1; END; """ create_test_procedure_with_int_param_sql = """ CREATE PROCEDURE "TEST_PROCEDURE" (P_I INTEGER) AS V_I INTEGER; BEGIN V_I := P_I; END; """ create_test_table_with_composite_primary_key = """ CREATE TABLE test_table_composite_pk ( column_1 NUMBER(11) NOT NULL, column_2 NUMBER(11) NOT NULL, PRIMARY KEY (column_1, column_2) ) """ supports_callproc_kwargs = True supports_over_clause = True supports_frame_range_fixed_distance = True supports_ignore_conflicts = False max_query_params = 2**16 - 1 supports_partial_indexes = False can_rename_index = True supports_slicing_ordering_in_compound = True allows_multiple_constraints_on_same_fields = False supports_boolean_expr_in_select_clause = False supports_primitives_in_json_field = False supports_json_field_contains = False supports_collation_on_textfield = False test_collations = { "ci": "BINARY_CI", "cs": "BINARY", "non_default": "SWEDISH_CI", "swedish_ci": "SWEDISH_CI", } test_now_utc_template = "CURRENT_TIMESTAMP AT TIME ZONE 'UTC'" django_test_skips = { "Oracle doesn't support SHA224.": { "db_functions.text.test_sha224.SHA224Tests.test_basic", "db_functions.text.test_sha224.SHA224Tests.test_transform", }, "Oracle doesn't correctly calculate ISO 8601 week numbering before " "1583 (the Gregorian calendar was introduced in 1582).": { "db_functions.datetime.test_extract_trunc.DateFunctionTests." "test_trunc_week_before_1000", "db_functions.datetime.test_extract_trunc.DateFunctionWithTimeZoneTests." "test_trunc_week_before_1000", }, "Oracle extracts seconds including fractional seconds (#33517).": { "db_functions.datetime.test_extract_trunc.DateFunctionTests." "test_extract_second_func_no_fractional", "db_functions.datetime.test_extract_trunc.DateFunctionWithTimeZoneTests." "test_extract_second_func_no_fractional", }, "Oracle doesn't support bitwise XOR.": { "expressions.tests.ExpressionOperatorTests.test_lefthand_bitwise_xor", "expressions.tests.ExpressionOperatorTests.test_lefthand_bitwise_xor_null", "expressions.tests.ExpressionOperatorTests." "test_lefthand_bitwise_xor_right_null", }, "Oracle requires ORDER BY in row_number, ANSI:SQL doesn't.": { "expressions_window.tests.WindowFunctionTests.test_row_number_no_ordering", }, "Raises ORA-00600: internal error code.": { "model_fields.test_jsonfield.TestQuerying.test_usage_in_subquery", }, "Oracle doesn't support changing collations on indexed columns (#33671).": { "migrations.test_operations.OperationTests." "test_alter_field_pk_fk_db_collation", }, } django_test_expected_failures = { # A bug in Django/cx_Oracle with respect to string handling (#23843). "annotations.tests.NonAggregateAnnotationTestCase.test_custom_functions", "annotations.tests.NonAggregateAnnotationTestCase." "test_custom_functions_can_ref_other_functions", } @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "GenericIPAddressField": "CharField", "PositiveBigIntegerField": "BigIntegerField", "PositiveIntegerField": "IntegerField", "PositiveSmallIntegerField": "IntegerField", "SmallIntegerField": "IntegerField", "TimeField": "DateTimeField", } @cached_property def supports_collation_on_charfield(self): with self.connection.cursor() as cursor: try: cursor.execute("SELECT CAST('a' AS VARCHAR2(4001)) FROM dual") except DatabaseError as e: if e.args[0].code == 910: return False raise return True
72d5dbbfaad1becbb639da4233ba8e4facefb17178d305c0db98ec332ca3caf3
from collections import namedtuple import cx_Oracle from django.db import models from django.db.backends.base.introspection import BaseDatabaseIntrospection from django.db.backends.base.introspection import FieldInfo as BaseFieldInfo from django.db.backends.base.introspection import TableInfo from django.utils.functional import cached_property FieldInfo = namedtuple("FieldInfo", BaseFieldInfo._fields + ("is_autofield", "is_json")) class DatabaseIntrospection(BaseDatabaseIntrospection): cache_bust_counter = 1 # Maps type objects to Django Field types. @cached_property def data_types_reverse(self): if self.connection.cx_oracle_version < (8,): return { cx_Oracle.BLOB: "BinaryField", cx_Oracle.CLOB: "TextField", cx_Oracle.DATETIME: "DateField", cx_Oracle.FIXED_CHAR: "CharField", cx_Oracle.FIXED_NCHAR: "CharField", cx_Oracle.INTERVAL: "DurationField", cx_Oracle.NATIVE_FLOAT: "FloatField", cx_Oracle.NCHAR: "CharField", cx_Oracle.NCLOB: "TextField", cx_Oracle.NUMBER: "DecimalField", cx_Oracle.STRING: "CharField", cx_Oracle.TIMESTAMP: "DateTimeField", } else: return { cx_Oracle.DB_TYPE_DATE: "DateField", cx_Oracle.DB_TYPE_BINARY_DOUBLE: "FloatField", cx_Oracle.DB_TYPE_BLOB: "BinaryField", cx_Oracle.DB_TYPE_CHAR: "CharField", cx_Oracle.DB_TYPE_CLOB: "TextField", cx_Oracle.DB_TYPE_INTERVAL_DS: "DurationField", cx_Oracle.DB_TYPE_NCHAR: "CharField", cx_Oracle.DB_TYPE_NCLOB: "TextField", cx_Oracle.DB_TYPE_NVARCHAR: "CharField", cx_Oracle.DB_TYPE_NUMBER: "DecimalField", cx_Oracle.DB_TYPE_TIMESTAMP: "DateTimeField", cx_Oracle.DB_TYPE_VARCHAR: "CharField", } def get_field_type(self, data_type, description): if data_type == cx_Oracle.NUMBER: precision, scale = description[4:6] if scale == 0: if precision > 11: return ( "BigAutoField" if description.is_autofield else "BigIntegerField" ) elif 1 < precision < 6 and description.is_autofield: return "SmallAutoField" elif precision == 1: return "BooleanField" elif description.is_autofield: return "AutoField" else: return "IntegerField" elif scale == -127: return "FloatField" elif data_type == cx_Oracle.NCLOB and description.is_json: return "JSONField" return super().get_field_type(data_type, description) def get_table_list(self, cursor): """Return a list of table and view names in the current database.""" cursor.execute( """ SELECT table_name, 't' FROM user_tables WHERE NOT EXISTS ( SELECT 1 FROM user_mviews WHERE user_mviews.mview_name = user_tables.table_name ) UNION ALL SELECT view_name, 'v' FROM user_views UNION ALL SELECT mview_name, 'v' FROM user_mviews """ ) return [ TableInfo(self.identifier_converter(row[0]), row[1]) for row in cursor.fetchall() ] def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface. """ # user_tab_columns gives data default for columns cursor.execute( """ SELECT user_tab_cols.column_name, user_tab_cols.data_default, CASE WHEN user_tab_cols.collation = user_tables.default_collation THEN NULL ELSE user_tab_cols.collation END collation, CASE WHEN user_tab_cols.char_used IS NULL THEN user_tab_cols.data_length ELSE user_tab_cols.char_length END as internal_size, CASE WHEN user_tab_cols.identity_column = 'YES' THEN 1 ELSE 0 END as is_autofield, CASE WHEN EXISTS ( SELECT 1 FROM user_json_columns WHERE user_json_columns.table_name = user_tab_cols.table_name AND user_json_columns.column_name = user_tab_cols.column_name ) THEN 1 ELSE 0 END as is_json FROM user_tab_cols LEFT OUTER JOIN user_tables ON user_tables.table_name = user_tab_cols.table_name WHERE user_tab_cols.table_name = UPPER(%s) """, [table_name], ) field_map = { column: ( internal_size, default if default != "NULL" else None, collation, is_autofield, is_json, ) for ( column, default, collation, internal_size, is_autofield, is_json, ) in cursor.fetchall() } self.cache_bust_counter += 1 cursor.execute( "SELECT * FROM {} WHERE ROWNUM < 2 AND {} > 0".format( self.connection.ops.quote_name(table_name), self.cache_bust_counter ) ) description = [] for desc in cursor.description: name = desc[0] internal_size, default, collation, is_autofield, is_json = field_map[name] name = name % {} # cx_Oracle, for some reason, doubles percent signs. description.append( FieldInfo( self.identifier_converter(name), *desc[1:3], internal_size, desc[4] or 0, desc[5] or 0, *desc[6:], default, collation, is_autofield, is_json, ) ) return description def identifier_converter(self, name): """Identifier comparison is case insensitive under Oracle.""" return name.lower() def get_sequences(self, cursor, table_name, table_fields=()): cursor.execute( """ SELECT user_tab_identity_cols.sequence_name, user_tab_identity_cols.column_name FROM user_tab_identity_cols, user_constraints, user_cons_columns cols WHERE user_constraints.constraint_name = cols.constraint_name AND user_constraints.table_name = user_tab_identity_cols.table_name AND cols.column_name = user_tab_identity_cols.column_name AND user_constraints.constraint_type = 'P' AND user_tab_identity_cols.table_name = UPPER(%s) """, [table_name], ) # Oracle allows only one identity column per table. row = cursor.fetchone() if row: return [ { "name": self.identifier_converter(row[0]), "table": self.identifier_converter(table_name), "column": self.identifier_converter(row[1]), } ] # To keep backward compatibility for AutoFields that aren't Oracle # identity columns. for f in table_fields: if isinstance(f, models.AutoField): return [{"table": table_name, "column": f.column}] return [] def get_relations(self, cursor, table_name): """ Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all foreign keys in the given table. """ table_name = table_name.upper() cursor.execute( """ SELECT ca.column_name, cb.table_name, cb.column_name FROM user_constraints, USER_CONS_COLUMNS ca, USER_CONS_COLUMNS cb WHERE user_constraints.table_name = %s AND user_constraints.constraint_name = ca.constraint_name AND user_constraints.r_constraint_name = cb.constraint_name AND ca.position = cb.position""", [table_name], ) return { self.identifier_converter(field_name): ( self.identifier_converter(rel_field_name), self.identifier_converter(rel_table_name), ) for field_name, rel_table_name, rel_field_name in cursor.fetchall() } def get_primary_key_columns(self, cursor, table_name): cursor.execute( """ SELECT cols.column_name FROM user_constraints, user_cons_columns cols WHERE user_constraints.constraint_name = cols.constraint_name AND user_constraints.constraint_type = 'P' AND user_constraints.table_name = UPPER(%s) ORDER BY cols.position """, [table_name], ) return [self.identifier_converter(row[0]) for row in cursor.fetchall()] def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Loop over the constraints, getting PKs, uniques, and checks cursor.execute( """ SELECT user_constraints.constraint_name, LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.position), CASE user_constraints.constraint_type WHEN 'P' THEN 1 ELSE 0 END AS is_primary_key, CASE WHEN user_constraints.constraint_type IN ('P', 'U') THEN 1 ELSE 0 END AS is_unique, CASE user_constraints.constraint_type WHEN 'C' THEN 1 ELSE 0 END AS is_check_constraint FROM user_constraints LEFT OUTER JOIN user_cons_columns cols ON user_constraints.constraint_name = cols.constraint_name WHERE user_constraints.constraint_type = ANY('P', 'U', 'C') AND user_constraints.table_name = UPPER(%s) GROUP BY user_constraints.constraint_name, user_constraints.constraint_type """, [table_name], ) for constraint, columns, pk, unique, check in cursor.fetchall(): constraint = self.identifier_converter(constraint) constraints[constraint] = { "columns": columns.split(","), "primary_key": pk, "unique": unique, "foreign_key": None, "check": check, "index": unique, # All uniques come with an index } # Foreign key constraints cursor.execute( """ SELECT cons.constraint_name, LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.position), LOWER(rcols.table_name), LOWER(rcols.column_name) FROM user_constraints cons INNER JOIN user_cons_columns rcols ON rcols.constraint_name = cons.r_constraint_name AND rcols.position = 1 LEFT OUTER JOIN user_cons_columns cols ON cons.constraint_name = cols.constraint_name WHERE cons.constraint_type = 'R' AND cons.table_name = UPPER(%s) GROUP BY cons.constraint_name, rcols.table_name, rcols.column_name """, [table_name], ) for constraint, columns, other_table, other_column in cursor.fetchall(): constraint = self.identifier_converter(constraint) constraints[constraint] = { "primary_key": False, "unique": False, "foreign_key": (other_table, other_column), "check": False, "index": False, "columns": columns.split(","), } # Now get indexes cursor.execute( """ SELECT ind.index_name, LOWER(ind.index_type), LOWER(ind.uniqueness), LISTAGG(LOWER(cols.column_name), ',') WITHIN GROUP (ORDER BY cols.column_position), LISTAGG(cols.descend, ',') WITHIN GROUP (ORDER BY cols.column_position) FROM user_ind_columns cols, user_indexes ind WHERE cols.table_name = UPPER(%s) AND NOT EXISTS ( SELECT 1 FROM user_constraints cons WHERE ind.index_name = cons.index_name ) AND cols.index_name = ind.index_name GROUP BY ind.index_name, ind.index_type, ind.uniqueness """, [table_name], ) for constraint, type_, unique, columns, orders in cursor.fetchall(): constraint = self.identifier_converter(constraint) constraints[constraint] = { "primary_key": False, "unique": unique == "unique", "foreign_key": None, "check": False, "index": True, "type": "idx" if type_ == "normal" else type_, "columns": columns.split(","), "orders": orders.split(","), } return constraints
cfa27ece1bd33dff2e47139cd4f72ca0dc5e64e556d5295d293b6a8eec46a74c
from django.db import ProgrammingError from django.utils.functional import cached_property class BaseDatabaseFeatures: # An optional tuple indicating the minimum supported database version. minimum_database_version = None gis_enabled = False # Oracle can't group by LOB (large object) data types. allows_group_by_lob = True allows_group_by_pk = False allows_group_by_selected_pks = False empty_fetchmany_value = [] update_can_self_select = True # Does the backend distinguish between '' and None? interprets_empty_strings_as_nulls = False # Does the backend allow inserting duplicate NULL rows in a nullable # unique field? All core backends implement this correctly, but other # databases such as SQL Server do not. supports_nullable_unique_constraints = True # Does the backend allow inserting duplicate rows when a unique_together # constraint exists and some fields are nullable but not all of them? supports_partially_nullable_unique_constraints = True # Does the backend support initially deferrable unique constraints? supports_deferrable_unique_constraints = False can_use_chunked_reads = True can_return_columns_from_insert = False can_return_rows_from_bulk_insert = False has_bulk_insert = True uses_savepoints = True can_release_savepoints = False # If True, don't use integer foreign keys referring to, e.g., positive # integer primary keys. related_fields_match_type = False allow_sliced_subqueries_with_in = True has_select_for_update = False has_select_for_update_nowait = False has_select_for_update_skip_locked = False has_select_for_update_of = False has_select_for_no_key_update = False # Does the database's SELECT FOR UPDATE OF syntax require a column rather # than a table? select_for_update_of_column = False # Does the default test database allow multiple connections? # Usually an indication that the test database is in-memory test_db_allows_multiple_connections = True # Can an object be saved without an explicit primary key? supports_unspecified_pk = False # Can a fixture contain forward references? i.e., are # FK constraints checked at the end of transaction, or # at the end of each save operation? supports_forward_references = True # Does the backend truncate names properly when they are too long? truncates_names = False # Is there a REAL datatype in addition to floats/doubles? has_real_datatype = False supports_subqueries_in_group_by = True # Does the backend ignore unnecessary ORDER BY clauses in subqueries? ignores_unnecessary_order_by_in_subqueries = True # Is there a true datatype for uuid? has_native_uuid_field = False # Is there a true datatype for timedeltas? has_native_duration_field = False # Does the database driver supports same type temporal data subtraction # by returning the type used to store duration field? supports_temporal_subtraction = False # Does the __regex lookup support backreferencing and grouping? supports_regex_backreferencing = True # Can date/datetime lookups be performed using a string? supports_date_lookup_using_string = True # Can datetimes with timezones be used? supports_timezones = True # Does the database have a copy of the zoneinfo database? has_zoneinfo_database = True # When performing a GROUP BY, is an ORDER BY NULL required # to remove any ordering? requires_explicit_null_ordering_when_grouping = False # Does the backend order NULL values as largest or smallest? nulls_order_largest = False # Does the backend support NULLS FIRST and NULLS LAST in ORDER BY? supports_order_by_nulls_modifier = True # Does the backend orders NULLS FIRST by default? order_by_nulls_first = False # The database's limit on the number of query parameters. max_query_params = None # Can an object have an autoincrement primary key of 0? allows_auto_pk_0 = True # Do we need to NULL a ForeignKey out, or can the constraint check be # deferred can_defer_constraint_checks = False # Does the backend support tablespaces? Default to False because it isn't # in the SQL standard. supports_tablespaces = False # Does the backend reset sequences between tests? supports_sequence_reset = True # Can the backend introspect the default value of a column? can_introspect_default = True # Confirm support for introspected foreign keys # Every database can do this reliably, except MySQL, # which can't do it for MyISAM tables can_introspect_foreign_keys = True # Map fields which some backends may not be able to differentiate to the # field it's introspected as. introspected_field_types = { "AutoField": "AutoField", "BigAutoField": "BigAutoField", "BigIntegerField": "BigIntegerField", "BinaryField": "BinaryField", "BooleanField": "BooleanField", "CharField": "CharField", "DurationField": "DurationField", "GenericIPAddressField": "GenericIPAddressField", "IntegerField": "IntegerField", "PositiveBigIntegerField": "PositiveBigIntegerField", "PositiveIntegerField": "PositiveIntegerField", "PositiveSmallIntegerField": "PositiveSmallIntegerField", "SmallAutoField": "SmallAutoField", "SmallIntegerField": "SmallIntegerField", "TimeField": "TimeField", } # Can the backend introspect the column order (ASC/DESC) for indexes? supports_index_column_ordering = True # Does the backend support introspection of materialized views? can_introspect_materialized_views = False # Support for the DISTINCT ON clause can_distinct_on_fields = False # Does the backend prevent running SQL queries in broken transactions? atomic_transactions = True # Can we roll back DDL in a transaction? can_rollback_ddl = False # Does it support operations requiring references rename in a transaction? supports_atomic_references_rename = True # Can we issue more than one ALTER COLUMN clause in an ALTER TABLE? supports_combined_alters = False # Does it support foreign keys? supports_foreign_keys = True # Can it create foreign key constraints inline when adding columns? can_create_inline_fk = True # Can an index be renamed? can_rename_index = False # Does it automatically index foreign keys? indexes_foreign_keys = True # Does it support CHECK constraints? supports_column_check_constraints = True supports_table_check_constraints = True # Does the backend support introspection of CHECK constraints? can_introspect_check_constraints = True # Does the backend support 'pyformat' style ("... %(name)s ...", {'name': value}) # parameter passing? Note this can be provided by the backend even if not # supported by the Python driver supports_paramstyle_pyformat = True # Does the backend require literal defaults, rather than parameterized ones? requires_literal_defaults = False # Does the backend require a connection reset after each material schema change? connection_persists_old_columns = False # What kind of error does the backend throw when accessing closed cursor? closed_cursor_error_class = ProgrammingError # Does 'a' LIKE 'A' match? has_case_insensitive_like = False # Suffix for backends that don't support "SELECT xxx;" queries. bare_select_suffix = "" # If NULL is implied on columns without needing to be explicitly specified implied_column_null = False # Does the backend support "select for update" queries with limit (and offset)? supports_select_for_update_with_limit = True # Does the backend ignore null expressions in GREATEST and LEAST queries unless # every expression is null? greatest_least_ignores_nulls = False # Can the backend clone databases for parallel test execution? # Defaults to False to allow third-party backends to opt-in. can_clone_databases = False # Does the backend consider table names with different casing to # be equal? ignores_table_name_case = False # Place FOR UPDATE right after FROM clause. Used on MSSQL. for_update_after_from = False # Combinatorial flags supports_select_union = True supports_select_intersection = True supports_select_difference = True supports_slicing_ordering_in_compound = False supports_parentheses_in_compound = True # Does the database support SQL 2003 FILTER (WHERE ...) in aggregate # expressions? supports_aggregate_filter_clause = False # Does the backend support indexing a TextField? supports_index_on_text_field = True # Does the backend support window expressions (expression OVER (...))? supports_over_clause = False supports_frame_range_fixed_distance = False only_supports_unbounded_with_preceding_and_following = False # Does the backend support CAST with precision? supports_cast_with_precision = True # How many second decimals does the database return when casting a value to # a type with time? time_cast_precision = 6 # SQL to create a procedure for use by the Django test suite. The # functionality of the procedure isn't important. create_test_procedure_without_params_sql = None create_test_procedure_with_int_param_sql = None # SQL to create a table with a composite primary key for use by the Django # test suite. create_test_table_with_composite_primary_key = None # Does the backend support keyword parameters for cursor.callproc()? supports_callproc_kwargs = False # What formats does the backend EXPLAIN syntax support? supported_explain_formats = set() # Does the backend support the default parameter in lead() and lag()? supports_default_in_lead_lag = True # Does the backend support ignoring constraint or uniqueness errors during # INSERT? supports_ignore_conflicts = True # Does the backend support updating rows on constraint or uniqueness errors # during INSERT? supports_update_conflicts = False supports_update_conflicts_with_target = False # Does this backend require casting the results of CASE expressions used # in UPDATE statements to ensure the expression has the correct type? requires_casted_case_in_updates = False # Does the backend support partial indexes (CREATE INDEX ... WHERE ...)? supports_partial_indexes = True supports_functions_in_partial_indexes = True # Does the backend support covering indexes (CREATE INDEX ... INCLUDE ...)? supports_covering_indexes = False # Does the backend support indexes on expressions? supports_expression_indexes = True # Does the backend treat COLLATE as an indexed expression? collate_as_index_expression = False # Does the database allow more than one constraint or index on the same # field(s)? allows_multiple_constraints_on_same_fields = True # Does the backend support boolean expressions in SELECT and GROUP BY # clauses? supports_boolean_expr_in_select_clause = True # Does the backend support JSONField? supports_json_field = True # Can the backend introspect a JSONField? can_introspect_json_field = True # Does the backend support primitives in JSONField? supports_primitives_in_json_field = True # Is there a true datatype for JSON? has_native_json_field = False # Does the backend use PostgreSQL-style JSON operators like '->'? has_json_operators = False # Does the backend support __contains and __contained_by lookups for # a JSONField? supports_json_field_contains = True # Does value__d__contains={'f': 'g'} (without a list around the dict) match # {'d': [{'f': 'g'}]}? json_key_contains_list_matching_requires_list = False # Does the backend support JSONObject() database function? has_json_object_function = True # Does the backend support column collations? supports_collation_on_charfield = True supports_collation_on_textfield = True # Does the backend support non-deterministic collations? supports_non_deterministic_collations = True # Does the backend support the logical XOR operator? supports_logical_xor = False # Collation names for use by the Django test suite. test_collations = { "ci": None, # Case-insensitive. "cs": None, # Case-sensitive. "non_default": None, # Non-default. "swedish_ci": None, # Swedish case-insensitive. } # SQL template override for tests.aggregation.tests.NowUTC test_now_utc_template = None # A set of dotted paths to tests in Django's test suite that are expected # to fail on this database. django_test_expected_failures = set() # A map of reasons to sets of dotted paths to tests in Django's test suite # that should be skipped for this database. django_test_skips = {} def __init__(self, connection): self.connection = connection @cached_property def supports_explaining_query_execution(self): """Does this backend support explaining query execution?""" return self.connection.ops.explain_prefix is not None @cached_property def supports_transactions(self): """Confirm support for transactions.""" with self.connection.cursor() as cursor: cursor.execute("CREATE TABLE ROLLBACK_TEST (X INT)") self.connection.set_autocommit(False) cursor.execute("INSERT INTO ROLLBACK_TEST (X) VALUES (8)") self.connection.rollback() self.connection.set_autocommit(True) cursor.execute("SELECT COUNT(X) FROM ROLLBACK_TEST") (count,) = cursor.fetchone() cursor.execute("DROP TABLE ROLLBACK_TEST") return count == 0 def allows_group_by_selected_pks_on_model(self, model): if not self.allows_group_by_selected_pks: return False return model._meta.managed
0891b7314991fb0269366fa0356b8c44c3649d6a7765d67d0d151b2b1727c2ea
from collections import namedtuple # Structure returned by DatabaseIntrospection.get_table_list() TableInfo = namedtuple("TableInfo", ["name", "type"]) # Structure returned by the DB-API cursor.description interface (PEP 249) FieldInfo = namedtuple( "FieldInfo", "name type_code display_size internal_size precision scale null_ok " "default collation", ) class BaseDatabaseIntrospection: """Encapsulate backend-specific introspection utilities.""" data_types_reverse = {} def __init__(self, connection): self.connection = connection def get_field_type(self, data_type, description): """ Hook for a database backend to use the cursor description to match a Django field type to a database column. For Oracle, the column data_type on its own is insufficient to distinguish between a FloatField and IntegerField, for example. """ return self.data_types_reverse[data_type] def identifier_converter(self, name): """ Apply a conversion to the identifier for the purposes of comparison. The default identifier converter is for case sensitive comparison. """ return name def table_names(self, cursor=None, include_views=False): """ Return a list of names of all tables that exist in the database. Sort the returned table list by Python's default sorting. Do NOT use the database's ORDER BY here to avoid subtle differences in sorting order between databases. """ def get_names(cursor): return sorted( ti.name for ti in self.get_table_list(cursor) if include_views or ti.type == "t" ) if cursor is None: with self.connection.cursor() as cursor: return get_names(cursor) return get_names(cursor) def get_table_list(self, cursor): """ Return an unsorted list of TableInfo named tuples of all tables and views that exist in the database. """ raise NotImplementedError( "subclasses of BaseDatabaseIntrospection may require a get_table_list() " "method" ) def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface. """ raise NotImplementedError( "subclasses of BaseDatabaseIntrospection may require a " "get_table_description() method." ) def get_migratable_models(self): from django.apps import apps from django.db import router return ( model for app_config in apps.get_app_configs() for model in router.get_migratable_models(app_config, self.connection.alias) if model._meta.can_migrate(self.connection) ) def django_table_names(self, only_existing=False, include_views=True): """ Return a list of all table names that have associated Django models and are in INSTALLED_APPS. If only_existing is True, include only the tables in the database. """ tables = set() for model in self.get_migratable_models(): if not model._meta.managed: continue tables.add(model._meta.db_table) tables.update( f.m2m_db_table() for f in model._meta.local_many_to_many if f.remote_field.through._meta.managed ) tables = list(tables) if only_existing: existing_tables = set(self.table_names(include_views=include_views)) tables = [ t for t in tables if self.identifier_converter(t) in existing_tables ] return tables def installed_models(self, tables): """ Return a set of all models represented by the provided list of table names. """ tables = set(map(self.identifier_converter, tables)) return { m for m in self.get_migratable_models() if self.identifier_converter(m._meta.db_table) in tables } def sequence_list(self): """ Return a list of information about all DB sequences for all models in all apps. """ sequence_list = [] with self.connection.cursor() as cursor: for model in self.get_migratable_models(): if not model._meta.managed: continue if model._meta.swapped: continue sequence_list.extend( self.get_sequences( cursor, model._meta.db_table, model._meta.local_fields ) ) for f in model._meta.local_many_to_many: # If this is an m2m using an intermediate table, # we don't need to reset the sequence. if f.remote_field.through._meta.auto_created: sequence = self.get_sequences(cursor, f.m2m_db_table()) sequence_list.extend( sequence or [{"table": f.m2m_db_table(), "column": None}] ) return sequence_list def get_sequences(self, cursor, table_name, table_fields=()): """ Return a list of introspected sequences for table_name. Each sequence is a dict: {'table': <table_name>, 'column': <column_name>}. An optional 'name' key can be added if the backend supports named sequences. """ raise NotImplementedError( "subclasses of BaseDatabaseIntrospection may require a get_sequences() " "method" ) def get_relations(self, cursor, table_name): """ Return a dictionary of {field_name: (field_name_other_table, other_table)} representing all foreign keys in the given table. """ raise NotImplementedError( "subclasses of BaseDatabaseIntrospection may require a " "get_relations() method." ) def get_primary_key_column(self, cursor, table_name): """ Return the name of the primary key column for the given table. """ columns = self.get_primary_key_columns(cursor, table_name) return columns[0] if columns else None def get_primary_key_columns(self, cursor, table_name): """Return a list of primary key columns for the given table.""" for constraint in self.get_constraints(cursor, table_name).values(): if constraint["primary_key"]: return constraint["columns"] return None def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. Return a dict mapping constraint names to their attributes, where attributes is a dict with keys: * columns: List of columns this covers * primary_key: True if primary key, False otherwise * unique: True if this is a unique constraint, False otherwise * foreign_key: (table, column) of target, or None * check: True if check constraint, False otherwise * index: True if index, False otherwise. * orders: The order (ASC/DESC) defined for the columns of indexes * type: The type of the index (btree, hash, etc.) Some backends may return special constraint names that don't exist if they don't name constraints of a certain type (e.g. SQLite) """ raise NotImplementedError( "subclasses of BaseDatabaseIntrospection may require a get_constraints() " "method" )
dc35a7cb9bb74e736d6d64d9ffdd45df819e37b847b03f97551fad0c533bbd87
import logging import operator from datetime import datetime from django.db.backends.ddl_references import ( Columns, Expressions, ForeignKeyName, IndexName, Statement, Table, ) from django.db.backends.utils import names_digest, split_identifier from django.db.models import Deferrable, Index from django.db.models.sql import Query from django.db.transaction import TransactionManagementError, atomic from django.utils import timezone logger = logging.getLogger("django.db.backends.schema") def _is_relevant_relation(relation, altered_field): """ When altering the given field, must constraints on its model from the given relation be temporarily dropped? """ field = relation.field if field.many_to_many: # M2M reverse field return False if altered_field.primary_key and field.to_fields == [None]: # Foreign key constraint on the primary key, which is being altered. return True # Is the constraint targeting the field being altered? return altered_field.name in field.to_fields def _all_related_fields(model): # Related fields must be returned in a deterministic order. return sorted( model._meta._get_fields( forward=False, reverse=True, include_hidden=True, include_parents=False, ), key=operator.attrgetter("name"), ) def _related_non_m2m_objects(old_field, new_field): # Filter out m2m objects from reverse relations. # Return (old_relation, new_relation) tuples. related_fields = zip( ( obj for obj in _all_related_fields(old_field.model) if _is_relevant_relation(obj, old_field) ), ( obj for obj in _all_related_fields(new_field.model) if _is_relevant_relation(obj, new_field) ), ) for old_rel, new_rel in related_fields: yield old_rel, new_rel yield from _related_non_m2m_objects( old_rel.remote_field, new_rel.remote_field, ) class BaseDatabaseSchemaEditor: """ This class and its subclasses are responsible for emitting schema-changing statements to the databases - model creation/removal/alteration, field renaming, index fiddling, and so on. """ # Overrideable SQL templates sql_create_table = "CREATE TABLE %(table)s (%(definition)s)" sql_rename_table = "ALTER TABLE %(old_table)s RENAME TO %(new_table)s" sql_retablespace_table = "ALTER TABLE %(table)s SET TABLESPACE %(new_tablespace)s" sql_delete_table = "DROP TABLE %(table)s CASCADE" sql_create_column = "ALTER TABLE %(table)s ADD COLUMN %(column)s %(definition)s" sql_alter_column = "ALTER TABLE %(table)s %(changes)s" sql_alter_column_type = "ALTER COLUMN %(column)s TYPE %(type)s" sql_alter_column_null = "ALTER COLUMN %(column)s DROP NOT NULL" sql_alter_column_not_null = "ALTER COLUMN %(column)s SET NOT NULL" sql_alter_column_default = "ALTER COLUMN %(column)s SET DEFAULT %(default)s" sql_alter_column_no_default = "ALTER COLUMN %(column)s DROP DEFAULT" sql_alter_column_no_default_null = sql_alter_column_no_default sql_alter_column_collate = "ALTER COLUMN %(column)s TYPE %(type)s%(collation)s" sql_delete_column = "ALTER TABLE %(table)s DROP COLUMN %(column)s CASCADE" sql_rename_column = ( "ALTER TABLE %(table)s RENAME COLUMN %(old_column)s TO %(new_column)s" ) sql_update_with_default = ( "UPDATE %(table)s SET %(column)s = %(default)s WHERE %(column)s IS NULL" ) sql_unique_constraint = "UNIQUE (%(columns)s)%(deferrable)s" sql_check_constraint = "CHECK (%(check)s)" sql_delete_constraint = "ALTER TABLE %(table)s DROP CONSTRAINT %(name)s" sql_constraint = "CONSTRAINT %(name)s %(constraint)s" sql_create_check = "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s CHECK (%(check)s)" sql_delete_check = sql_delete_constraint sql_create_unique = ( "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s " "UNIQUE (%(columns)s)%(deferrable)s" ) sql_delete_unique = sql_delete_constraint sql_create_fk = ( "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s FOREIGN KEY (%(column)s) " "REFERENCES %(to_table)s (%(to_column)s)%(deferrable)s" ) sql_create_inline_fk = None sql_create_column_inline_fk = None sql_delete_fk = sql_delete_constraint sql_create_index = ( "CREATE INDEX %(name)s ON %(table)s " "(%(columns)s)%(include)s%(extra)s%(condition)s" ) sql_create_unique_index = ( "CREATE UNIQUE INDEX %(name)s ON %(table)s " "(%(columns)s)%(include)s%(condition)s" ) sql_rename_index = "ALTER INDEX %(old_name)s RENAME TO %(new_name)s" sql_delete_index = "DROP INDEX %(name)s" sql_create_pk = ( "ALTER TABLE %(table)s ADD CONSTRAINT %(name)s PRIMARY KEY (%(columns)s)" ) sql_delete_pk = sql_delete_constraint sql_delete_procedure = "DROP PROCEDURE %(procedure)s" def __init__(self, connection, collect_sql=False, atomic=True): self.connection = connection self.collect_sql = collect_sql if self.collect_sql: self.collected_sql = [] self.atomic_migration = self.connection.features.can_rollback_ddl and atomic # State-managing methods def __enter__(self): self.deferred_sql = [] if self.atomic_migration: self.atomic = atomic(self.connection.alias) self.atomic.__enter__() return self def __exit__(self, exc_type, exc_value, traceback): if exc_type is None: for sql in self.deferred_sql: self.execute(sql) if self.atomic_migration: self.atomic.__exit__(exc_type, exc_value, traceback) # Core utility functions def execute(self, sql, params=()): """Execute the given SQL statement, with optional parameters.""" # Don't perform the transactional DDL check if SQL is being collected # as it's not going to be executed anyway. if ( not self.collect_sql and self.connection.in_atomic_block and not self.connection.features.can_rollback_ddl ): raise TransactionManagementError( "Executing DDL statements while in a transaction on databases " "that can't perform a rollback is prohibited." ) # Account for non-string statement objects. sql = str(sql) # Log the command we're running, then run it logger.debug( "%s; (params %r)", sql, params, extra={"params": params, "sql": sql} ) if self.collect_sql: ending = "" if sql.rstrip().endswith(";") else ";" if params is not None: self.collected_sql.append( (sql % tuple(map(self.quote_value, params))) + ending ) else: self.collected_sql.append(sql + ending) else: with self.connection.cursor() as cursor: cursor.execute(sql, params) def quote_name(self, name): return self.connection.ops.quote_name(name) def table_sql(self, model): """Take a model and return its table definition.""" # Add any unique_togethers (always deferred, as some fields might be # created afterward, like geometry fields with some backends). for field_names in model._meta.unique_together: fields = [model._meta.get_field(field) for field in field_names] self.deferred_sql.append(self._create_unique_sql(model, fields)) # Create column SQL, add FK deferreds if needed. column_sqls = [] params = [] for field in model._meta.local_fields: # SQL. definition, extra_params = self.column_sql(model, field) if definition is None: continue # Check constraints can go on the column SQL here. db_params = field.db_parameters(connection=self.connection) if db_params["check"]: definition += " " + self.sql_check_constraint % db_params # Autoincrement SQL (for backends with inline variant). col_type_suffix = field.db_type_suffix(connection=self.connection) if col_type_suffix: definition += " %s" % col_type_suffix params.extend(extra_params) # FK. if field.remote_field and field.db_constraint: to_table = field.remote_field.model._meta.db_table to_column = field.remote_field.model._meta.get_field( field.remote_field.field_name ).column if self.sql_create_inline_fk: definition += " " + self.sql_create_inline_fk % { "to_table": self.quote_name(to_table), "to_column": self.quote_name(to_column), } elif self.connection.features.supports_foreign_keys: self.deferred_sql.append( self._create_fk_sql( model, field, "_fk_%(to_table)s_%(to_column)s" ) ) # Add the SQL to our big list. column_sqls.append( "%s %s" % ( self.quote_name(field.column), definition, ) ) # Autoincrement SQL (for backends with post table definition # variant). if field.get_internal_type() in ( "AutoField", "BigAutoField", "SmallAutoField", ): autoinc_sql = self.connection.ops.autoinc_sql( model._meta.db_table, field.column ) if autoinc_sql: self.deferred_sql.extend(autoinc_sql) constraints = [ constraint.constraint_sql(model, self) for constraint in model._meta.constraints ] sql = self.sql_create_table % { "table": self.quote_name(model._meta.db_table), "definition": ", ".join( constraint for constraint in (*column_sqls, *constraints) if constraint ), } if model._meta.db_tablespace: tablespace_sql = self.connection.ops.tablespace_sql( model._meta.db_tablespace ) if tablespace_sql: sql += " " + tablespace_sql return sql, params # Field <-> database mapping functions def _iter_column_sql( self, column_db_type, params, model, field, field_db_params, include_default ): yield column_db_type if collation := field_db_params.get("collation"): yield self._collate_sql(collation) # Work out nullability. null = field.null # Include a default value, if requested. include_default = ( include_default and not self.skip_default(field) and # Don't include a default value if it's a nullable field and the # default cannot be dropped in the ALTER COLUMN statement (e.g. # MySQL longtext and longblob). not (null and self.skip_default_on_alter(field)) ) if include_default: default_value = self.effective_default(field) if default_value is not None: column_default = "DEFAULT " + self._column_default_sql(field) if self.connection.features.requires_literal_defaults: # Some databases can't take defaults as a parameter (Oracle). # If this is the case, the individual schema backend should # implement prepare_default(). yield column_default % self.prepare_default(default_value) else: yield column_default params.append(default_value) # Oracle treats the empty string ('') as null, so coerce the null # option whenever '' is a possible value. if ( field.empty_strings_allowed and not field.primary_key and self.connection.features.interprets_empty_strings_as_nulls ): null = True if not null: yield "NOT NULL" elif not self.connection.features.implied_column_null: yield "NULL" if field.primary_key: yield "PRIMARY KEY" elif field.unique: yield "UNIQUE" # Optionally add the tablespace if it's an implicitly indexed column. tablespace = field.db_tablespace or model._meta.db_tablespace if ( tablespace and self.connection.features.supports_tablespaces and field.unique ): yield self.connection.ops.tablespace_sql(tablespace, inline=True) def column_sql(self, model, field, include_default=False): """ Return the column definition for a field. The field must already have had set_attributes_from_name() called. """ # Get the column's type and use that as the basis of the SQL. field_db_params = field.db_parameters(connection=self.connection) column_db_type = field_db_params["type"] # Check for fields that aren't actually columns (e.g. M2M). if column_db_type is None: return None, None params = [] return ( " ".join( # This appends to the params being returned. self._iter_column_sql( column_db_type, params, model, field, field_db_params, include_default, ) ), params, ) def skip_default(self, field): """ Some backends don't accept default values for certain columns types (i.e. MySQL longtext and longblob). """ return False def skip_default_on_alter(self, field): """ Some backends don't accept default values for certain columns types (i.e. MySQL longtext and longblob) in the ALTER COLUMN statement. """ return False def prepare_default(self, value): """ Only used for backends which have requires_literal_defaults feature """ raise NotImplementedError( "subclasses of BaseDatabaseSchemaEditor for backends which have " "requires_literal_defaults must provide a prepare_default() method" ) def _column_default_sql(self, field): """ Return the SQL to use in a DEFAULT clause. The resulting string should contain a '%s' placeholder for a default value. """ return "%s" @staticmethod def _effective_default(field): # This method allows testing its logic without a connection. if field.has_default(): default = field.get_default() elif not field.null and field.blank and field.empty_strings_allowed: if field.get_internal_type() == "BinaryField": default = b"" else: default = "" elif getattr(field, "auto_now", False) or getattr(field, "auto_now_add", False): internal_type = field.get_internal_type() if internal_type == "DateTimeField": default = timezone.now() else: default = datetime.now() if internal_type == "DateField": default = default.date() elif internal_type == "TimeField": default = default.time() else: default = None return default def effective_default(self, field): """Return a field's effective database default value.""" return field.get_db_prep_save(self._effective_default(field), self.connection) def quote_value(self, value): """ Return a quoted version of the value so it's safe to use in an SQL string. This is not safe against injection from user code; it is intended only for use in making SQL scripts or preparing default values for particularly tricky backends (defaults are not user-defined, though, so this is safe). """ raise NotImplementedError() # Actions def create_model(self, model): """ Create a table and any accompanying indexes or unique constraints for the given `model`. """ sql, params = self.table_sql(model) # Prevent using [] as params, in the case a literal '%' is used in the # definition. self.execute(sql, params or None) # Add any field index and index_together's (deferred as SQLite # _remake_table needs it). self.deferred_sql.extend(self._model_indexes_sql(model)) # Make M2M tables for field in model._meta.local_many_to_many: if field.remote_field.through._meta.auto_created: self.create_model(field.remote_field.through) def delete_model(self, model): """Delete a model from the database.""" # Handle auto-created intermediary models for field in model._meta.local_many_to_many: if field.remote_field.through._meta.auto_created: self.delete_model(field.remote_field.through) # Delete the table self.execute( self.sql_delete_table % { "table": self.quote_name(model._meta.db_table), } ) # Remove all deferred statements referencing the deleted table. for sql in list(self.deferred_sql): if isinstance(sql, Statement) and sql.references_table( model._meta.db_table ): self.deferred_sql.remove(sql) def add_index(self, model, index): """Add an index on a model.""" if ( index.contains_expressions and not self.connection.features.supports_expression_indexes ): return None # Index.create_sql returns interpolated SQL which makes params=None a # necessity to avoid escaping attempts on execution. self.execute(index.create_sql(model, self), params=None) def remove_index(self, model, index): """Remove an index from a model.""" if ( index.contains_expressions and not self.connection.features.supports_expression_indexes ): return None self.execute(index.remove_sql(model, self)) def rename_index(self, model, old_index, new_index): if self.connection.features.can_rename_index: self.execute( self._rename_index_sql(model, old_index.name, new_index.name), params=None, ) else: self.remove_index(model, old_index) self.add_index(model, new_index) def add_constraint(self, model, constraint): """Add a constraint to a model.""" sql = constraint.create_sql(model, self) if sql: # Constraint.create_sql returns interpolated SQL which makes # params=None a necessity to avoid escaping attempts on execution. self.execute(sql, params=None) def remove_constraint(self, model, constraint): """Remove a constraint from a model.""" sql = constraint.remove_sql(model, self) if sql: self.execute(sql) def alter_unique_together(self, model, old_unique_together, new_unique_together): """ Deal with a model changing its unique_together. The input unique_togethers must be doubly-nested, not the single-nested ["foo", "bar"] format. """ olds = {tuple(fields) for fields in old_unique_together} news = {tuple(fields) for fields in new_unique_together} # Deleted uniques for fields in olds.difference(news): self._delete_composed_index( model, fields, {"unique": True, "primary_key": False}, self.sql_delete_unique, ) # Created uniques for field_names in news.difference(olds): fields = [model._meta.get_field(field) for field in field_names] self.execute(self._create_unique_sql(model, fields)) def alter_index_together(self, model, old_index_together, new_index_together): """ Deal with a model changing its index_together. The input index_togethers must be doubly-nested, not the single-nested ["foo", "bar"] format. """ olds = {tuple(fields) for fields in old_index_together} news = {tuple(fields) for fields in new_index_together} # Deleted indexes for fields in olds.difference(news): self._delete_composed_index( model, fields, {"index": True, "unique": False}, self.sql_delete_index, ) # Created indexes for field_names in news.difference(olds): fields = [model._meta.get_field(field) for field in field_names] self.execute(self._create_index_sql(model, fields=fields, suffix="_idx")) def _delete_composed_index(self, model, fields, constraint_kwargs, sql): meta_constraint_names = { constraint.name for constraint in model._meta.constraints } meta_index_names = {constraint.name for constraint in model._meta.indexes} columns = [model._meta.get_field(field).column for field in fields] constraint_names = self._constraint_names( model, columns, exclude=meta_constraint_names | meta_index_names, **constraint_kwargs, ) if ( constraint_kwargs.get("unique") is True and constraint_names and self.connection.features.allows_multiple_constraints_on_same_fields ): # Constraint matching the unique_together name. default_name = str( self._unique_constraint_name(model._meta.db_table, columns, quote=False) ) if default_name in constraint_names: constraint_names = [default_name] if len(constraint_names) != 1: raise ValueError( "Found wrong number (%s) of constraints for %s(%s)" % ( len(constraint_names), model._meta.db_table, ", ".join(columns), ) ) self.execute(self._delete_constraint_sql(sql, model, constraint_names[0])) def alter_db_table(self, model, old_db_table, new_db_table): """Rename the table a model points to.""" if old_db_table == new_db_table or ( self.connection.features.ignores_table_name_case and old_db_table.lower() == new_db_table.lower() ): return self.execute( self.sql_rename_table % { "old_table": self.quote_name(old_db_table), "new_table": self.quote_name(new_db_table), } ) # Rename all references to the old table name. for sql in self.deferred_sql: if isinstance(sql, Statement): sql.rename_table_references(old_db_table, new_db_table) def alter_db_tablespace(self, model, old_db_tablespace, new_db_tablespace): """Move a model's table between tablespaces.""" self.execute( self.sql_retablespace_table % { "table": self.quote_name(model._meta.db_table), "old_tablespace": self.quote_name(old_db_tablespace), "new_tablespace": self.quote_name(new_db_tablespace), } ) def add_field(self, model, field): """ Create a field on a model. Usually involves adding a column, but may involve adding a table instead (for M2M fields). """ # Special-case implicit M2M tables if field.many_to_many and field.remote_field.through._meta.auto_created: return self.create_model(field.remote_field.through) # Get the column's definition definition, params = self.column_sql(model, field, include_default=True) # It might not actually have a column behind it if definition is None: return # Check constraints can go on the column SQL here db_params = field.db_parameters(connection=self.connection) if db_params["check"]: definition += " " + self.sql_check_constraint % db_params if ( field.remote_field and self.connection.features.supports_foreign_keys and field.db_constraint ): constraint_suffix = "_fk_%(to_table)s_%(to_column)s" # Add FK constraint inline, if supported. if self.sql_create_column_inline_fk: to_table = field.remote_field.model._meta.db_table to_column = field.remote_field.model._meta.get_field( field.remote_field.field_name ).column namespace, _ = split_identifier(model._meta.db_table) definition += " " + self.sql_create_column_inline_fk % { "name": self._fk_constraint_name(model, field, constraint_suffix), "namespace": "%s." % self.quote_name(namespace) if namespace else "", "column": self.quote_name(field.column), "to_table": self.quote_name(to_table), "to_column": self.quote_name(to_column), "deferrable": self.connection.ops.deferrable_sql(), } # Otherwise, add FK constraints later. else: self.deferred_sql.append( self._create_fk_sql(model, field, constraint_suffix) ) # Build the SQL and run it sql = self.sql_create_column % { "table": self.quote_name(model._meta.db_table), "column": self.quote_name(field.column), "definition": definition, } self.execute(sql, params) # Drop the default if we need to # (Django usually does not use in-database defaults) if ( not self.skip_default_on_alter(field) and self.effective_default(field) is not None ): changes_sql, params = self._alter_column_default_sql( model, None, field, drop=True ) sql = self.sql_alter_column % { "table": self.quote_name(model._meta.db_table), "changes": changes_sql, } self.execute(sql, params) # Add an index, if required self.deferred_sql.extend(self._field_indexes_sql(model, field)) # Reset connection if required if self.connection.features.connection_persists_old_columns: self.connection.close() def remove_field(self, model, field): """ Remove a field from a model. Usually involves deleting a column, but for M2Ms may involve deleting a table. """ # Special-case implicit M2M tables if field.many_to_many and field.remote_field.through._meta.auto_created: return self.delete_model(field.remote_field.through) # It might not actually have a column behind it if field.db_parameters(connection=self.connection)["type"] is None: return # Drop any FK constraints, MySQL requires explicit deletion if field.remote_field: fk_names = self._constraint_names(model, [field.column], foreign_key=True) for fk_name in fk_names: self.execute(self._delete_fk_sql(model, fk_name)) # Delete the column sql = self.sql_delete_column % { "table": self.quote_name(model._meta.db_table), "column": self.quote_name(field.column), } self.execute(sql) # Reset connection if required if self.connection.features.connection_persists_old_columns: self.connection.close() # Remove all deferred statements referencing the deleted column. for sql in list(self.deferred_sql): if isinstance(sql, Statement) and sql.references_column( model._meta.db_table, field.column ): self.deferred_sql.remove(sql) def alter_field(self, model, old_field, new_field, strict=False): """ Allow a field's type, uniqueness, nullability, default, column, constraints, etc. to be modified. `old_field` is required to compute the necessary changes. If `strict` is True, raise errors if the old column does not match `old_field` precisely. """ if not self._field_should_be_altered(old_field, new_field): return # Ensure this field is even column-based old_db_params = old_field.db_parameters(connection=self.connection) old_type = old_db_params["type"] new_db_params = new_field.db_parameters(connection=self.connection) new_type = new_db_params["type"] if (old_type is None and old_field.remote_field is None) or ( new_type is None and new_field.remote_field is None ): raise ValueError( "Cannot alter field %s into %s - they do not properly define " "db_type (are you using a badly-written custom field?)" % (old_field, new_field), ) elif ( old_type is None and new_type is None and ( old_field.remote_field.through and new_field.remote_field.through and old_field.remote_field.through._meta.auto_created and new_field.remote_field.through._meta.auto_created ) ): return self._alter_many_to_many(model, old_field, new_field, strict) elif ( old_type is None and new_type is None and ( old_field.remote_field.through and new_field.remote_field.through and not old_field.remote_field.through._meta.auto_created and not new_field.remote_field.through._meta.auto_created ) ): # Both sides have through models; this is a no-op. return elif old_type is None or new_type is None: raise ValueError( "Cannot alter field %s into %s - they are not compatible types " "(you cannot alter to or from M2M fields, or add or remove " "through= on M2M fields)" % (old_field, new_field) ) self._alter_field( model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict, ) def _alter_field( self, model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict=False, ): """Perform a "physical" (non-ManyToMany) field update.""" # Drop any FK constraints, we'll remake them later fks_dropped = set() if ( self.connection.features.supports_foreign_keys and old_field.remote_field and old_field.db_constraint ): fk_names = self._constraint_names( model, [old_field.column], foreign_key=True ) if strict and len(fk_names) != 1: raise ValueError( "Found wrong number (%s) of foreign key constraints for %s.%s" % ( len(fk_names), model._meta.db_table, old_field.column, ) ) for fk_name in fk_names: fks_dropped.add((old_field.column,)) self.execute(self._delete_fk_sql(model, fk_name)) # Has unique been removed? if old_field.unique and ( not new_field.unique or self._field_became_primary_key(old_field, new_field) ): # Find the unique constraint for this field meta_constraint_names = { constraint.name for constraint in model._meta.constraints } constraint_names = self._constraint_names( model, [old_field.column], unique=True, primary_key=False, exclude=meta_constraint_names, ) if strict and len(constraint_names) != 1: raise ValueError( "Found wrong number (%s) of unique constraints for %s.%s" % ( len(constraint_names), model._meta.db_table, old_field.column, ) ) for constraint_name in constraint_names: self.execute(self._delete_unique_sql(model, constraint_name)) # Drop incoming FK constraints if the field is a primary key or unique, # which might be a to_field target, and things are going to change. old_collation = old_db_params.get("collation") new_collation = new_db_params.get("collation") drop_foreign_keys = ( self.connection.features.supports_foreign_keys and ( (old_field.primary_key and new_field.primary_key) or (old_field.unique and new_field.unique) ) and ((old_type != new_type) or (old_collation != new_collation)) ) if drop_foreign_keys: # '_meta.related_field' also contains M2M reverse fields, these # will be filtered out for _old_rel, new_rel in _related_non_m2m_objects(old_field, new_field): rel_fk_names = self._constraint_names( new_rel.related_model, [new_rel.field.column], foreign_key=True ) for fk_name in rel_fk_names: self.execute(self._delete_fk_sql(new_rel.related_model, fk_name)) # Removed an index? (no strict check, as multiple indexes are possible) # Remove indexes if db_index switched to False or a unique constraint # will now be used in lieu of an index. The following lines from the # truth table show all True cases; the rest are False: # # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique # ------------------------------------------------------------------------------ # True | False | False | False # True | False | False | True # True | False | True | True if ( old_field.db_index and not old_field.unique and (not new_field.db_index or new_field.unique) ): # Find the index for this field meta_index_names = {index.name for index in model._meta.indexes} # Retrieve only BTREE indexes since this is what's created with # db_index=True. index_names = self._constraint_names( model, [old_field.column], index=True, type_=Index.suffix, exclude=meta_index_names, ) for index_name in index_names: # The only way to check if an index was created with # db_index=True or with Index(['field'], name='foo') # is to look at its name (refs #28053). self.execute(self._delete_index_sql(model, index_name)) # Change check constraints? if old_db_params["check"] != new_db_params["check"] and old_db_params["check"]: meta_constraint_names = { constraint.name for constraint in model._meta.constraints } constraint_names = self._constraint_names( model, [old_field.column], check=True, exclude=meta_constraint_names, ) if strict and len(constraint_names) != 1: raise ValueError( "Found wrong number (%s) of check constraints for %s.%s" % ( len(constraint_names), model._meta.db_table, old_field.column, ) ) for constraint_name in constraint_names: self.execute(self._delete_check_sql(model, constraint_name)) # Have they renamed the column? if old_field.column != new_field.column: self.execute( self._rename_field_sql( model._meta.db_table, old_field, new_field, new_type ) ) # Rename all references to the renamed column. for sql in self.deferred_sql: if isinstance(sql, Statement): sql.rename_column_references( model._meta.db_table, old_field.column, new_field.column ) # Next, start accumulating actions to do actions = [] null_actions = [] post_actions = [] # Type suffix change? (e.g. auto increment). old_type_suffix = old_field.db_type_suffix(connection=self.connection) new_type_suffix = new_field.db_type_suffix(connection=self.connection) # Collation change? if old_collation != new_collation: # Collation change handles also a type change. fragment = self._alter_column_collation_sql( model, new_field, new_type, new_collation ) actions.append(fragment) # Type change? elif (old_type, old_type_suffix) != (new_type, new_type_suffix): fragment, other_actions = self._alter_column_type_sql( model, old_field, new_field, new_type ) actions.append(fragment) post_actions.extend(other_actions) # When changing a column NULL constraint to NOT NULL with a given # default value, we need to perform 4 steps: # 1. Add a default for new incoming writes # 2. Update existing NULL rows with new default # 3. Replace NULL constraint with NOT NULL # 4. Drop the default again. # Default change? needs_database_default = False if old_field.null and not new_field.null: old_default = self.effective_default(old_field) new_default = self.effective_default(new_field) if ( not self.skip_default_on_alter(new_field) and old_default != new_default and new_default is not None ): needs_database_default = True actions.append( self._alter_column_default_sql(model, old_field, new_field) ) # Nullability change? if old_field.null != new_field.null: fragment = self._alter_column_null_sql(model, old_field, new_field) if fragment: null_actions.append(fragment) # Only if we have a default and there is a change from NULL to NOT NULL four_way_default_alteration = new_field.has_default() and ( old_field.null and not new_field.null ) if actions or null_actions: if not four_way_default_alteration: # If we don't have to do a 4-way default alteration we can # directly run a (NOT) NULL alteration actions = actions + null_actions # Combine actions together if we can (e.g. postgres) if self.connection.features.supports_combined_alters and actions: sql, params = tuple(zip(*actions)) actions = [(", ".join(sql), sum(params, []))] # Apply those actions for sql, params in actions: self.execute( self.sql_alter_column % { "table": self.quote_name(model._meta.db_table), "changes": sql, }, params, ) if four_way_default_alteration: # Update existing rows with default value self.execute( self.sql_update_with_default % { "table": self.quote_name(model._meta.db_table), "column": self.quote_name(new_field.column), "default": "%s", }, [new_default], ) # Since we didn't run a NOT NULL change before we need to do it # now for sql, params in null_actions: self.execute( self.sql_alter_column % { "table": self.quote_name(model._meta.db_table), "changes": sql, }, params, ) if post_actions: for sql, params in post_actions: self.execute(sql, params) # If primary_key changed to False, delete the primary key constraint. if old_field.primary_key and not new_field.primary_key: self._delete_primary_key(model, strict) # Added a unique? if self._unique_should_be_added(old_field, new_field): self.execute(self._create_unique_sql(model, [new_field])) # Added an index? Add an index if db_index switched to True or a unique # constraint will no longer be used in lieu of an index. The following # lines from the truth table show all True cases; the rest are False: # # old_field.db_index | old_field.unique | new_field.db_index | new_field.unique # ------------------------------------------------------------------------------ # False | False | True | False # False | True | True | False # True | True | True | False if ( (not old_field.db_index or old_field.unique) and new_field.db_index and not new_field.unique ): self.execute(self._create_index_sql(model, fields=[new_field])) # Type alteration on primary key? Then we need to alter the column # referring to us. rels_to_update = [] if drop_foreign_keys: rels_to_update.extend(_related_non_m2m_objects(old_field, new_field)) # Changed to become primary key? if self._field_became_primary_key(old_field, new_field): # Make the new one self.execute(self._create_primary_key_sql(model, new_field)) # Update all referencing columns rels_to_update.extend(_related_non_m2m_objects(old_field, new_field)) # Handle our type alters on the other end of rels from the PK stuff above for old_rel, new_rel in rels_to_update: rel_db_params = new_rel.field.db_parameters(connection=self.connection) rel_type = rel_db_params["type"] rel_collation = rel_db_params.get("collation") old_rel_db_params = old_rel.field.db_parameters(connection=self.connection) old_rel_collation = old_rel_db_params.get("collation") if old_rel_collation != rel_collation: # Collation change handles also a type change. fragment = self._alter_column_collation_sql( new_rel.related_model, new_rel.field, rel_type, rel_collation, ) other_actions = [] else: fragment, other_actions = self._alter_column_type_sql( new_rel.related_model, old_rel.field, new_rel.field, rel_type ) self.execute( self.sql_alter_column % { "table": self.quote_name(new_rel.related_model._meta.db_table), "changes": fragment[0], }, fragment[1], ) for sql, params in other_actions: self.execute(sql, params) # Does it have a foreign key? if ( self.connection.features.supports_foreign_keys and new_field.remote_field and ( fks_dropped or not old_field.remote_field or not old_field.db_constraint ) and new_field.db_constraint ): self.execute( self._create_fk_sql(model, new_field, "_fk_%(to_table)s_%(to_column)s") ) # Rebuild FKs that pointed to us if we previously had to drop them if drop_foreign_keys: for _, rel in rels_to_update: if rel.field.db_constraint: self.execute( self._create_fk_sql(rel.related_model, rel.field, "_fk") ) # Does it have check constraints we need to add? if old_db_params["check"] != new_db_params["check"] and new_db_params["check"]: constraint_name = self._create_index_name( model._meta.db_table, [new_field.column], suffix="_check" ) self.execute( self._create_check_sql(model, constraint_name, new_db_params["check"]) ) # Drop the default if we need to # (Django usually does not use in-database defaults) if needs_database_default: changes_sql, params = self._alter_column_default_sql( model, old_field, new_field, drop=True ) sql = self.sql_alter_column % { "table": self.quote_name(model._meta.db_table), "changes": changes_sql, } self.execute(sql, params) # Reset connection if required if self.connection.features.connection_persists_old_columns: self.connection.close() def _alter_column_null_sql(self, model, old_field, new_field): """ Hook to specialize column null alteration. Return a (sql, params) fragment to set a column to null or non-null as required by new_field, or None if no changes are required. """ if ( self.connection.features.interprets_empty_strings_as_nulls and new_field.empty_strings_allowed ): # The field is nullable in the database anyway, leave it alone. return else: new_db_params = new_field.db_parameters(connection=self.connection) sql = ( self.sql_alter_column_null if new_field.null else self.sql_alter_column_not_null ) return ( sql % { "column": self.quote_name(new_field.column), "type": new_db_params["type"], }, [], ) def _alter_column_default_sql(self, model, old_field, new_field, drop=False): """ Hook to specialize column default alteration. Return a (sql, params) fragment to add or drop (depending on the drop argument) a default to new_field's column. """ new_default = self.effective_default(new_field) default = self._column_default_sql(new_field) params = [new_default] if drop: params = [] elif self.connection.features.requires_literal_defaults: # Some databases (Oracle) can't take defaults as a parameter # If this is the case, the SchemaEditor for that database should # implement prepare_default(). default = self.prepare_default(new_default) params = [] new_db_params = new_field.db_parameters(connection=self.connection) if drop: if new_field.null: sql = self.sql_alter_column_no_default_null else: sql = self.sql_alter_column_no_default else: sql = self.sql_alter_column_default return ( sql % { "column": self.quote_name(new_field.column), "type": new_db_params["type"], "default": default, }, params, ) def _alter_column_type_sql(self, model, old_field, new_field, new_type): """ Hook to specialize column type alteration for different backends, for cases when a creation type is different to an alteration type (e.g. SERIAL in PostgreSQL, PostGIS fields). Return a two-tuple of: an SQL fragment of (sql, params) to insert into an ALTER TABLE statement and a list of extra (sql, params) tuples to run once the field is altered. """ return ( ( self.sql_alter_column_type % { "column": self.quote_name(new_field.column), "type": new_type, }, [], ), [], ) def _alter_column_collation_sql(self, model, new_field, new_type, new_collation): return ( self.sql_alter_column_collate % { "column": self.quote_name(new_field.column), "type": new_type, "collation": " " + self._collate_sql(new_collation) if new_collation else "", }, [], ) def _alter_many_to_many(self, model, old_field, new_field, strict): """Alter M2Ms to repoint their to= endpoints.""" # Rename the through table if ( old_field.remote_field.through._meta.db_table != new_field.remote_field.through._meta.db_table ): self.alter_db_table( old_field.remote_field.through, old_field.remote_field.through._meta.db_table, new_field.remote_field.through._meta.db_table, ) # Repoint the FK to the other side self.alter_field( new_field.remote_field.through, # The field that points to the target model is needed, so we can # tell alter_field to change it - this is m2m_reverse_field_name() # (as opposed to m2m_field_name(), which points to our model). old_field.remote_field.through._meta.get_field( old_field.m2m_reverse_field_name() ), new_field.remote_field.through._meta.get_field( new_field.m2m_reverse_field_name() ), ) self.alter_field( new_field.remote_field.through, # for self-referential models we need to alter field from the other end too old_field.remote_field.through._meta.get_field(old_field.m2m_field_name()), new_field.remote_field.through._meta.get_field(new_field.m2m_field_name()), ) def _create_index_name(self, table_name, column_names, suffix=""): """ Generate a unique name for an index/unique constraint. The name is divided into 3 parts: the table name, the column names, and a unique digest and suffix. """ _, table_name = split_identifier(table_name) hash_suffix_part = "%s%s" % ( names_digest(table_name, *column_names, length=8), suffix, ) max_length = self.connection.ops.max_name_length() or 200 # If everything fits into max_length, use that name. index_name = "%s_%s_%s" % (table_name, "_".join(column_names), hash_suffix_part) if len(index_name) <= max_length: return index_name # Shorten a long suffix. if len(hash_suffix_part) > max_length / 3: hash_suffix_part = hash_suffix_part[: max_length // 3] other_length = (max_length - len(hash_suffix_part)) // 2 - 1 index_name = "%s_%s_%s" % ( table_name[:other_length], "_".join(column_names)[:other_length], hash_suffix_part, ) # Prepend D if needed to prevent the name from starting with an # underscore or a number (not permitted on Oracle). if index_name[0] == "_" or index_name[0].isdigit(): index_name = "D%s" % index_name[:-1] return index_name def _get_index_tablespace_sql(self, model, fields, db_tablespace=None): if db_tablespace is None: if len(fields) == 1 and fields[0].db_tablespace: db_tablespace = fields[0].db_tablespace elif model._meta.db_tablespace: db_tablespace = model._meta.db_tablespace if db_tablespace is not None: return " " + self.connection.ops.tablespace_sql(db_tablespace) return "" def _index_condition_sql(self, condition): if condition: return " WHERE " + condition return "" def _index_include_sql(self, model, columns): if not columns or not self.connection.features.supports_covering_indexes: return "" return Statement( " INCLUDE (%(columns)s)", columns=Columns(model._meta.db_table, columns, self.quote_name), ) def _create_index_sql( self, model, *, fields=None, name=None, suffix="", using="", db_tablespace=None, col_suffixes=(), sql=None, opclasses=(), condition=None, include=None, expressions=None, ): """ Return the SQL statement to create the index for one or several fields or expressions. `sql` can be specified if the syntax differs from the standard (GIS indexes, ...). """ fields = fields or [] expressions = expressions or [] compiler = Query(model, alias_cols=False).get_compiler( connection=self.connection, ) tablespace_sql = self._get_index_tablespace_sql( model, fields, db_tablespace=db_tablespace ) columns = [field.column for field in fields] sql_create_index = sql or self.sql_create_index table = model._meta.db_table def create_index_name(*args, **kwargs): nonlocal name if name is None: name = self._create_index_name(*args, **kwargs) return self.quote_name(name) return Statement( sql_create_index, table=Table(table, self.quote_name), name=IndexName(table, columns, suffix, create_index_name), using=using, columns=( self._index_columns(table, columns, col_suffixes, opclasses) if columns else Expressions(table, expressions, compiler, self.quote_value) ), extra=tablespace_sql, condition=self._index_condition_sql(condition), include=self._index_include_sql(model, include), ) def _delete_index_sql(self, model, name, sql=None): return Statement( sql or self.sql_delete_index, table=Table(model._meta.db_table, self.quote_name), name=self.quote_name(name), ) def _rename_index_sql(self, model, old_name, new_name): return Statement( self.sql_rename_index, table=Table(model._meta.db_table, self.quote_name), old_name=self.quote_name(old_name), new_name=self.quote_name(new_name), ) def _index_columns(self, table, columns, col_suffixes, opclasses): return Columns(table, columns, self.quote_name, col_suffixes=col_suffixes) def _model_indexes_sql(self, model): """ Return a list of all index SQL statements (field indexes, index_together, Meta.indexes) for the specified model. """ if not model._meta.managed or model._meta.proxy or model._meta.swapped: return [] output = [] for field in model._meta.local_fields: output.extend(self._field_indexes_sql(model, field)) for field_names in model._meta.index_together: fields = [model._meta.get_field(field) for field in field_names] output.append(self._create_index_sql(model, fields=fields, suffix="_idx")) for index in model._meta.indexes: if ( not index.contains_expressions or self.connection.features.supports_expression_indexes ): output.append(index.create_sql(model, self)) return output def _field_indexes_sql(self, model, field): """ Return a list of all index SQL statements for the specified field. """ output = [] if self._field_should_be_indexed(model, field): output.append(self._create_index_sql(model, fields=[field])) return output def _field_should_be_altered(self, old_field, new_field): _, old_path, old_args, old_kwargs = old_field.deconstruct() _, new_path, new_args, new_kwargs = new_field.deconstruct() # Don't alter when: # - changing only a field name # - changing an attribute that doesn't affect the schema # - adding only a db_column and the column name is not changed for attr in old_field.non_db_attrs: old_kwargs.pop(attr, None) for attr in new_field.non_db_attrs: new_kwargs.pop(attr, None) return self.quote_name(old_field.column) != self.quote_name( new_field.column ) or (old_path, old_args, old_kwargs) != (new_path, new_args, new_kwargs) def _field_should_be_indexed(self, model, field): return field.db_index and not field.unique def _field_became_primary_key(self, old_field, new_field): return not old_field.primary_key and new_field.primary_key def _unique_should_be_added(self, old_field, new_field): return ( not new_field.primary_key and new_field.unique and (not old_field.unique or old_field.primary_key) ) def _rename_field_sql(self, table, old_field, new_field, new_type): return self.sql_rename_column % { "table": self.quote_name(table), "old_column": self.quote_name(old_field.column), "new_column": self.quote_name(new_field.column), "type": new_type, } def _create_fk_sql(self, model, field, suffix): table = Table(model._meta.db_table, self.quote_name) name = self._fk_constraint_name(model, field, suffix) column = Columns(model._meta.db_table, [field.column], self.quote_name) to_table = Table(field.target_field.model._meta.db_table, self.quote_name) to_column = Columns( field.target_field.model._meta.db_table, [field.target_field.column], self.quote_name, ) deferrable = self.connection.ops.deferrable_sql() return Statement( self.sql_create_fk, table=table, name=name, column=column, to_table=to_table, to_column=to_column, deferrable=deferrable, ) def _fk_constraint_name(self, model, field, suffix): def create_fk_name(*args, **kwargs): return self.quote_name(self._create_index_name(*args, **kwargs)) return ForeignKeyName( model._meta.db_table, [field.column], split_identifier(field.target_field.model._meta.db_table)[1], [field.target_field.column], suffix, create_fk_name, ) def _delete_fk_sql(self, model, name): return self._delete_constraint_sql(self.sql_delete_fk, model, name) def _deferrable_constraint_sql(self, deferrable): if deferrable is None: return "" if deferrable == Deferrable.DEFERRED: return " DEFERRABLE INITIALLY DEFERRED" if deferrable == Deferrable.IMMEDIATE: return " DEFERRABLE INITIALLY IMMEDIATE" def _unique_sql( self, model, fields, name, condition=None, deferrable=None, include=None, opclasses=None, expressions=None, ): if ( deferrable and not self.connection.features.supports_deferrable_unique_constraints ): return None if condition or include or opclasses or expressions: # Databases support conditional, covering, and functional unique # constraints via a unique index. sql = self._create_unique_sql( model, fields, name=name, condition=condition, include=include, opclasses=opclasses, expressions=expressions, ) if sql: self.deferred_sql.append(sql) return None constraint = self.sql_unique_constraint % { "columns": ", ".join([self.quote_name(field.column) for field in fields]), "deferrable": self._deferrable_constraint_sql(deferrable), } return self.sql_constraint % { "name": self.quote_name(name), "constraint": constraint, } def _create_unique_sql( self, model, fields, name=None, condition=None, deferrable=None, include=None, opclasses=None, expressions=None, ): if ( ( deferrable and not self.connection.features.supports_deferrable_unique_constraints ) or (condition and not self.connection.features.supports_partial_indexes) or (include and not self.connection.features.supports_covering_indexes) or ( expressions and not self.connection.features.supports_expression_indexes ) ): return None compiler = Query(model, alias_cols=False).get_compiler( connection=self.connection ) table = model._meta.db_table columns = [field.column for field in fields] if name is None: name = self._unique_constraint_name(table, columns, quote=True) else: name = self.quote_name(name) if condition or include or opclasses or expressions: sql = self.sql_create_unique_index else: sql = self.sql_create_unique if columns: columns = self._index_columns( table, columns, col_suffixes=(), opclasses=opclasses ) else: columns = Expressions(table, expressions, compiler, self.quote_value) return Statement( sql, table=Table(table, self.quote_name), name=name, columns=columns, condition=self._index_condition_sql(condition), deferrable=self._deferrable_constraint_sql(deferrable), include=self._index_include_sql(model, include), ) def _unique_constraint_name(self, table, columns, quote=True): if quote: def create_unique_name(*args, **kwargs): return self.quote_name(self._create_index_name(*args, **kwargs)) else: create_unique_name = self._create_index_name return IndexName(table, columns, "_uniq", create_unique_name) def _delete_unique_sql( self, model, name, condition=None, deferrable=None, include=None, opclasses=None, expressions=None, ): if ( ( deferrable and not self.connection.features.supports_deferrable_unique_constraints ) or (condition and not self.connection.features.supports_partial_indexes) or (include and not self.connection.features.supports_covering_indexes) or ( expressions and not self.connection.features.supports_expression_indexes ) ): return None if condition or include or opclasses or expressions: sql = self.sql_delete_index else: sql = self.sql_delete_unique return self._delete_constraint_sql(sql, model, name) def _check_sql(self, name, check): return self.sql_constraint % { "name": self.quote_name(name), "constraint": self.sql_check_constraint % {"check": check}, } def _create_check_sql(self, model, name, check): return Statement( self.sql_create_check, table=Table(model._meta.db_table, self.quote_name), name=self.quote_name(name), check=check, ) def _delete_check_sql(self, model, name): return self._delete_constraint_sql(self.sql_delete_check, model, name) def _delete_constraint_sql(self, template, model, name): return Statement( template, table=Table(model._meta.db_table, self.quote_name), name=self.quote_name(name), ) def _constraint_names( self, model, column_names=None, unique=None, primary_key=None, index=None, foreign_key=None, check=None, type_=None, exclude=None, ): """Return all constraint names matching the columns and conditions.""" if column_names is not None: column_names = [ self.connection.introspection.identifier_converter(name) for name in column_names ] with self.connection.cursor() as cursor: constraints = self.connection.introspection.get_constraints( cursor, model._meta.db_table ) result = [] for name, infodict in constraints.items(): if column_names is None or column_names == infodict["columns"]: if unique is not None and infodict["unique"] != unique: continue if primary_key is not None and infodict["primary_key"] != primary_key: continue if index is not None and infodict["index"] != index: continue if check is not None and infodict["check"] != check: continue if foreign_key is not None and not infodict["foreign_key"]: continue if type_ is not None and infodict["type"] != type_: continue if not exclude or name not in exclude: result.append(name) return result def _delete_primary_key(self, model, strict=False): constraint_names = self._constraint_names(model, primary_key=True) if strict and len(constraint_names) != 1: raise ValueError( "Found wrong number (%s) of PK constraints for %s" % ( len(constraint_names), model._meta.db_table, ) ) for constraint_name in constraint_names: self.execute(self._delete_primary_key_sql(model, constraint_name)) def _create_primary_key_sql(self, model, field): return Statement( self.sql_create_pk, table=Table(model._meta.db_table, self.quote_name), name=self.quote_name( self._create_index_name( model._meta.db_table, [field.column], suffix="_pk" ) ), columns=Columns(model._meta.db_table, [field.column], self.quote_name), ) def _delete_primary_key_sql(self, model, name): return self._delete_constraint_sql(self.sql_delete_pk, model, name) def _collate_sql(self, collation): return "COLLATE " + self.quote_name(collation) def remove_procedure(self, procedure_name, param_types=()): sql = self.sql_delete_procedure % { "procedure": self.quote_name(procedure_name), "param_types": ",".join(param_types), } self.execute(sql)
924fd10c468c2a64d8e3f761e7d3e9a98c53f9cd534eed77a29bdfb14409693c
import operator from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): empty_fetchmany_value = () allows_group_by_pk = True related_fields_match_type = True # MySQL doesn't support sliced subqueries with IN/ALL/ANY/SOME. allow_sliced_subqueries_with_in = False has_select_for_update = True supports_forward_references = False supports_regex_backreferencing = False supports_date_lookup_using_string = False supports_timezones = False requires_explicit_null_ordering_when_grouping = True can_release_savepoints = True atomic_transactions = False can_clone_databases = True supports_temporal_subtraction = True supports_select_intersection = False supports_select_difference = False supports_slicing_ordering_in_compound = True supports_index_on_text_field = False supports_update_conflicts = True create_test_procedure_without_params_sql = """ CREATE PROCEDURE test_procedure () BEGIN DECLARE V_I INTEGER; SET V_I = 1; END; """ create_test_procedure_with_int_param_sql = """ CREATE PROCEDURE test_procedure (P_I INTEGER) BEGIN DECLARE V_I INTEGER; SET V_I = P_I; END; """ create_test_table_with_composite_primary_key = """ CREATE TABLE test_table_composite_pk ( column_1 INTEGER NOT NULL, column_2 INTEGER NOT NULL, PRIMARY KEY(column_1, column_2) ) """ # Neither MySQL nor MariaDB support partial indexes. supports_partial_indexes = False # COLLATE must be wrapped in parentheses because MySQL treats COLLATE as an # indexed expression. collate_as_index_expression = True supports_order_by_nulls_modifier = False order_by_nulls_first = True supports_logical_xor = True @cached_property def minimum_database_version(self): if self.connection.mysql_is_mariadb: return (10, 4) else: return (5, 7) @cached_property def bare_select_suffix(self): if not self.connection.mysql_is_mariadb and self.connection.mysql_version < ( 8, ): return " FROM DUAL" return "" @cached_property def test_collations(self): charset = "utf8" if self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 6, ): # utf8 is an alias for utf8mb3 in MariaDB 10.6+. charset = "utf8mb3" return { "ci": f"{charset}_general_ci", "non_default": f"{charset}_esperanto_ci", "swedish_ci": f"{charset}_swedish_ci", } test_now_utc_template = "UTC_TIMESTAMP" @cached_property def django_test_skips(self): skips = { "This doesn't work on MySQL.": { "db_functions.comparison.test_greatest.GreatestTests." "test_coalesce_workaround", "db_functions.comparison.test_least.LeastTests." "test_coalesce_workaround", }, "Running on MySQL requires utf8mb4 encoding (#18392).": { "model_fields.test_textfield.TextFieldTests.test_emoji", "model_fields.test_charfield.TestCharField.test_emoji", }, "MySQL doesn't support functional indexes on a function that " "returns JSON": { "schema.tests.SchemaTests.test_func_index_json_key_transform", }, "MySQL supports multiplying and dividing DurationFields by a " "scalar value but it's not implemented (#25287).": { "expressions.tests.FTimeDeltaTests.test_durationfield_multiply_divide", }, } if "ONLY_FULL_GROUP_BY" in self.connection.sql_mode: skips.update( { "GROUP BY optimization does not work properly when " "ONLY_FULL_GROUP_BY mode is enabled on MySQL, see #31331.": { "aggregation.tests.AggregateTestCase." "test_aggregation_subquery_annotation_multivalued", "annotations.tests.NonAggregateAnnotationTestCase." "test_annotation_aggregate_with_m2o", }, } ) if not self.connection.mysql_is_mariadb and self.connection.mysql_version < ( 8, ): skips.update( { "Casting to datetime/time is not supported by MySQL < 8.0. " "(#30224)": { "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_time_from_python", "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_datetime_from_python", }, "MySQL < 8.0 returns string type instead of datetime/time. " "(#30224)": { "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_time_from_database", "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_datetime_from_database", }, } ) if self.connection.mysql_is_mariadb and ( 10, 4, 3, ) < self.connection.mysql_version < (10, 5, 2): skips.update( { "https://jira.mariadb.org/browse/MDEV-19598": { "schema.tests.SchemaTests." "test_alter_not_unique_field_to_primary_key", }, } ) if self.connection.mysql_is_mariadb and ( 10, 4, 12, ) < self.connection.mysql_version < (10, 5): skips.update( { "https://jira.mariadb.org/browse/MDEV-22775": { "schema.tests.SchemaTests." "test_alter_pk_with_self_referential_field", }, } ) if not self.supports_explain_analyze: skips.update( { "MariaDB and MySQL >= 8.0.18 specific.": { "queries.test_explain.ExplainTests.test_mysql_analyze", }, } ) return skips @cached_property def _mysql_storage_engine(self): "Internal method used in Django tests. Don't rely on this from your code" return self.connection.mysql_server_data["default_storage_engine"] @cached_property def allows_auto_pk_0(self): """ Autoincrement primary key can be set to 0 if it doesn't generate new autoincrement values. """ return "NO_AUTO_VALUE_ON_ZERO" in self.connection.sql_mode @cached_property def update_can_self_select(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 3, 2, ) @cached_property def can_introspect_foreign_keys(self): "Confirm support for introspected foreign keys" return self._mysql_storage_engine != "MyISAM" @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "BinaryField": "TextField", "BooleanField": "IntegerField", "DurationField": "BigIntegerField", "GenericIPAddressField": "CharField", } @cached_property def can_return_columns_from_insert(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 5, 0, ) can_return_rows_from_bulk_insert = property( operator.attrgetter("can_return_columns_from_insert") ) @cached_property def has_zoneinfo_database(self): return self.connection.mysql_server_data["has_zoneinfo_database"] @cached_property def is_sql_auto_is_null_enabled(self): return self.connection.mysql_server_data["sql_auto_is_null"] @cached_property def supports_over_clause(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 2) supports_frame_range_fixed_distance = property( operator.attrgetter("supports_over_clause") ) @cached_property def supports_column_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) supports_table_check_constraints = property( operator.attrgetter("supports_column_check_constraints") ) @cached_property def can_introspect_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) @cached_property def has_select_for_update_skip_locked(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 6) return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_nowait(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_of(self): return ( not self.connection.mysql_is_mariadb and self.connection.mysql_version >= (8, 0, 1) ) @cached_property def supports_explain_analyze(self): return self.connection.mysql_is_mariadb or self.connection.mysql_version >= ( 8, 0, 18, ) @cached_property def supported_explain_formats(self): # Alias MySQL's TRADITIONAL to TEXT for consistency with other # backends. formats = {"JSON", "TEXT", "TRADITIONAL"} if not self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 8, 0, 16, ): formats.add("TREE") return formats @cached_property def supports_transactions(self): """ All storage engines except MyISAM support transactions. """ return self._mysql_storage_engine != "MyISAM" uses_savepoints = property(operator.attrgetter("supports_transactions")) can_release_savepoints = property(operator.attrgetter("supports_transactions")) @cached_property def ignores_table_name_case(self): return self.connection.mysql_server_data["lower_case_table_names"] @cached_property def supports_default_in_lead_lag(self): # To be added in https://jira.mariadb.org/browse/MDEV-12981. return not self.connection.mysql_is_mariadb @cached_property def supports_json_field(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (5, 7, 8) @cached_property def can_introspect_json_field(self): if self.connection.mysql_is_mariadb: return self.supports_json_field and self.can_introspect_check_constraints return self.supports_json_field @cached_property def supports_index_column_ordering(self): if self._mysql_storage_engine != "InnoDB": return False if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 8) return self.connection.mysql_version >= (8, 0, 1) @cached_property def supports_expression_indexes(self): return ( not self.connection.mysql_is_mariadb and self._mysql_storage_engine != "MyISAM" and self.connection.mysql_version >= (8, 0, 13) ) @cached_property def can_rename_index(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 5, 2) return True
f22422d380af1e3dc5a523288063a2e6e6bcfe8bcdef4f26da202b73c8db2c69
import uuid from django.conf import settings from django.db.backends.base.operations import BaseDatabaseOperations from django.db.backends.utils import split_tzname_delta from django.db.models import Exists, ExpressionWrapper, Lookup from django.db.models.constants import OnConflict from django.utils import timezone from django.utils.encoding import force_str class DatabaseOperations(BaseDatabaseOperations): compiler_module = "django.db.backends.mysql.compiler" # MySQL stores positive fields as UNSIGNED ints. integer_field_ranges = { **BaseDatabaseOperations.integer_field_ranges, "PositiveSmallIntegerField": (0, 65535), "PositiveIntegerField": (0, 4294967295), "PositiveBigIntegerField": (0, 18446744073709551615), } cast_data_types = { "AutoField": "signed integer", "BigAutoField": "signed integer", "SmallAutoField": "signed integer", "CharField": "char(%(max_length)s)", "DecimalField": "decimal(%(max_digits)s, %(decimal_places)s)", "TextField": "char", "IntegerField": "signed integer", "BigIntegerField": "signed integer", "SmallIntegerField": "signed integer", "PositiveBigIntegerField": "unsigned integer", "PositiveIntegerField": "unsigned integer", "PositiveSmallIntegerField": "unsigned integer", "DurationField": "signed integer", } cast_char_field_without_max_length = "char" explain_prefix = "EXPLAIN" def date_extract_sql(self, lookup_type, field_name): # https://dev.mysql.com/doc/mysql/en/date-and-time-functions.html if lookup_type == "week_day": # DAYOFWEEK() returns an integer, 1-7, Sunday=1. return "DAYOFWEEK(%s)" % field_name elif lookup_type == "iso_week_day": # WEEKDAY() returns an integer, 0-6, Monday=0. return "WEEKDAY(%s) + 1" % field_name elif lookup_type == "week": # Override the value of default_week_format for consistency with # other database backends. # Mode 3: Monday, 1-53, with 4 or more days this year. return "WEEK(%s, 3)" % field_name elif lookup_type == "iso_year": # Get the year part from the YEARWEEK function, which returns a # number as year * 100 + week. return "TRUNCATE(YEARWEEK(%s, 3), -2) / 100" % field_name else: # EXTRACT returns 1-53 based on ISO-8601 for the week number. return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name) def date_trunc_sql(self, lookup_type, field_name, tzname=None): field_name = self._convert_field_to_tz(field_name, tzname) fields = { "year": "%%Y-01-01", "month": "%%Y-%%m-01", } # Use double percents to escape. if lookup_type in fields: format_str = fields[lookup_type] return "CAST(DATE_FORMAT(%s, '%s') AS DATE)" % (field_name, format_str) elif lookup_type == "quarter": return ( "MAKEDATE(YEAR(%s), 1) + " "INTERVAL QUARTER(%s) QUARTER - INTERVAL 1 QUARTER" % (field_name, field_name) ) elif lookup_type == "week": return "DATE_SUB(%s, INTERVAL WEEKDAY(%s) DAY)" % (field_name, field_name) else: return "DATE(%s)" % (field_name) def _prepare_tzname_delta(self, tzname): tzname, sign, offset = split_tzname_delta(tzname) return f"{sign}{offset}" if offset else tzname def _convert_field_to_tz(self, field_name, tzname): if tzname and settings.USE_TZ and self.connection.timezone_name != tzname: field_name = "CONVERT_TZ(%s, '%s', '%s')" % ( field_name, self.connection.timezone_name, self._prepare_tzname_delta(tzname), ) return field_name def datetime_cast_date_sql(self, field_name, tzname): field_name = self._convert_field_to_tz(field_name, tzname) return "DATE(%s)" % field_name def datetime_cast_time_sql(self, field_name, tzname): field_name = self._convert_field_to_tz(field_name, tzname) return "TIME(%s)" % field_name def datetime_extract_sql(self, lookup_type, field_name, tzname): field_name = self._convert_field_to_tz(field_name, tzname) return self.date_extract_sql(lookup_type, field_name) def datetime_trunc_sql(self, lookup_type, field_name, tzname): field_name = self._convert_field_to_tz(field_name, tzname) fields = ["year", "month", "day", "hour", "minute", "second"] format = ( "%%Y-", "%%m", "-%%d", " %%H:", "%%i", ":%%s", ) # Use double percents to escape. format_def = ("0000-", "01", "-01", " 00:", "00", ":00") if lookup_type == "quarter": return ( "CAST(DATE_FORMAT(MAKEDATE(YEAR({field_name}), 1) + " "INTERVAL QUARTER({field_name}) QUARTER - " + "INTERVAL 1 QUARTER, '%%Y-%%m-01 00:00:00') AS DATETIME)" ).format(field_name=field_name) if lookup_type == "week": return ( "CAST(DATE_FORMAT(DATE_SUB({field_name}, " "INTERVAL WEEKDAY({field_name}) DAY), " "'%%Y-%%m-%%d 00:00:00') AS DATETIME)" ).format(field_name=field_name) try: i = fields.index(lookup_type) + 1 except ValueError: sql = field_name else: format_str = "".join(format[:i] + format_def[i:]) sql = "CAST(DATE_FORMAT(%s, '%s') AS DATETIME)" % (field_name, format_str) return sql def time_trunc_sql(self, lookup_type, field_name, tzname=None): field_name = self._convert_field_to_tz(field_name, tzname) fields = { "hour": "%%H:00:00", "minute": "%%H:%%i:00", "second": "%%H:%%i:%%s", } # Use double percents to escape. if lookup_type in fields: format_str = fields[lookup_type] return "CAST(DATE_FORMAT(%s, '%s') AS TIME)" % (field_name, format_str) else: return "TIME(%s)" % (field_name) def fetch_returned_insert_rows(self, cursor): """ Given a cursor object that has just performed an INSERT...RETURNING statement into a table, return the tuple of returned data. """ return cursor.fetchall() def format_for_duration_arithmetic(self, sql): return "INTERVAL %s MICROSECOND" % sql def force_no_ordering(self): """ "ORDER BY NULL" prevents MySQL from implicitly ordering by grouped columns. If no ordering would otherwise be applied, we don't want any implicit sorting going on. """ return [(None, ("NULL", [], False))] def adapt_decimalfield_value(self, value, max_digits=None, decimal_places=None): return value def last_executed_query(self, cursor, sql, params): # With MySQLdb, cursor objects have an (undocumented) "_executed" # attribute where the exact query sent to the database is saved. # See MySQLdb/cursors.py in the source distribution. # MySQLdb returns string, PyMySQL bytes. return force_str(getattr(cursor, "_executed", None), errors="replace") def no_limit_value(self): # 2**64 - 1, as recommended by the MySQL documentation return 18446744073709551615 def quote_name(self, name): if name.startswith("`") and name.endswith("`"): return name # Quoting once is enough. return "`%s`" % name def return_insert_columns(self, fields): # MySQL and MariaDB < 10.5.0 don't support an INSERT...RETURNING # statement. if not fields: return "", () columns = [ "%s.%s" % ( self.quote_name(field.model._meta.db_table), self.quote_name(field.column), ) for field in fields ] return "RETURNING %s" % ", ".join(columns), () def sql_flush(self, style, tables, *, reset_sequences=False, allow_cascade=False): if not tables: return [] sql = ["SET FOREIGN_KEY_CHECKS = 0;"] if reset_sequences: # It's faster to TRUNCATE tables that require a sequence reset # since ALTER TABLE AUTO_INCREMENT is slower than TRUNCATE. sql.extend( "%s %s;" % ( style.SQL_KEYWORD("TRUNCATE"), style.SQL_FIELD(self.quote_name(table_name)), ) for table_name in tables ) else: # Otherwise issue a simple DELETE since it's faster than TRUNCATE # and preserves sequences. sql.extend( "%s %s %s;" % ( style.SQL_KEYWORD("DELETE"), style.SQL_KEYWORD("FROM"), style.SQL_FIELD(self.quote_name(table_name)), ) for table_name in tables ) sql.append("SET FOREIGN_KEY_CHECKS = 1;") return sql def sequence_reset_by_name_sql(self, style, sequences): return [ "%s %s %s %s = 1;" % ( style.SQL_KEYWORD("ALTER"), style.SQL_KEYWORD("TABLE"), style.SQL_FIELD(self.quote_name(sequence_info["table"])), style.SQL_FIELD("AUTO_INCREMENT"), ) for sequence_info in sequences ] def validate_autopk_value(self, value): # Zero in AUTO_INCREMENT field does not work without the # NO_AUTO_VALUE_ON_ZERO SQL mode. if value == 0 and not self.connection.features.allows_auto_pk_0: raise ValueError( "The database backend does not accept 0 as a value for AutoField." ) return value def adapt_datetimefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # MySQL doesn't support tz-aware datetimes if timezone.is_aware(value): if settings.USE_TZ: value = timezone.make_naive(value, self.connection.timezone) else: raise ValueError( "MySQL backend does not support timezone-aware datetimes when " "USE_TZ is False." ) return str(value) def adapt_timefield_value(self, value): if value is None: return None # Expression values are adapted by the database. if hasattr(value, "resolve_expression"): return value # MySQL doesn't support tz-aware times if timezone.is_aware(value): raise ValueError("MySQL backend does not support timezone-aware times.") return value.isoformat(timespec="microseconds") def max_name_length(self): return 64 def pk_default_value(self): return "NULL" def bulk_insert_sql(self, fields, placeholder_rows): placeholder_rows_sql = (", ".join(row) for row in placeholder_rows) values_sql = ", ".join("(%s)" % sql for sql in placeholder_rows_sql) return "VALUES " + values_sql def combine_expression(self, connector, sub_expressions): if connector == "^": return "POW(%s)" % ",".join(sub_expressions) # Convert the result to a signed integer since MySQL's binary operators # return an unsigned integer. elif connector in ("&", "|", "<<", "#"): connector = "^" if connector == "#" else connector return "CONVERT(%s, SIGNED)" % connector.join(sub_expressions) elif connector == ">>": lhs, rhs = sub_expressions return "FLOOR(%(lhs)s / POW(2, %(rhs)s))" % {"lhs": lhs, "rhs": rhs} return super().combine_expression(connector, sub_expressions) def get_db_converters(self, expression): converters = super().get_db_converters(expression) internal_type = expression.output_field.get_internal_type() if internal_type == "BooleanField": converters.append(self.convert_booleanfield_value) elif internal_type == "DateTimeField": if settings.USE_TZ: converters.append(self.convert_datetimefield_value) elif internal_type == "UUIDField": converters.append(self.convert_uuidfield_value) return converters def convert_booleanfield_value(self, value, expression, connection): if value in (0, 1): value = bool(value) return value def convert_datetimefield_value(self, value, expression, connection): if value is not None: value = timezone.make_aware(value, self.connection.timezone) return value def convert_uuidfield_value(self, value, expression, connection): if value is not None: value = uuid.UUID(value) return value def binary_placeholder_sql(self, value): return ( "_binary %s" if value is not None and not hasattr(value, "as_sql") else "%s" ) def subtract_temporals(self, internal_type, lhs, rhs): lhs_sql, lhs_params = lhs rhs_sql, rhs_params = rhs if internal_type == "TimeField": if self.connection.mysql_is_mariadb: # MariaDB includes the microsecond component in TIME_TO_SEC as # a decimal. MySQL returns an integer without microseconds. return ( "CAST((TIME_TO_SEC(%(lhs)s) - TIME_TO_SEC(%(rhs)s)) " "* 1000000 AS SIGNED)" ) % { "lhs": lhs_sql, "rhs": rhs_sql, }, ( *lhs_params, *rhs_params, ) return ( "((TIME_TO_SEC(%(lhs)s) * 1000000 + MICROSECOND(%(lhs)s)) -" " (TIME_TO_SEC(%(rhs)s) * 1000000 + MICROSECOND(%(rhs)s)))" ) % {"lhs": lhs_sql, "rhs": rhs_sql}, tuple(lhs_params) * 2 + tuple( rhs_params ) * 2 params = (*rhs_params, *lhs_params) return "TIMESTAMPDIFF(MICROSECOND, %s, %s)" % (rhs_sql, lhs_sql), params def explain_query_prefix(self, format=None, **options): # Alias MySQL's TRADITIONAL to TEXT for consistency with other backends. if format and format.upper() == "TEXT": format = "TRADITIONAL" elif ( not format and "TREE" in self.connection.features.supported_explain_formats ): # Use TREE by default (if supported) as it's more informative. format = "TREE" analyze = options.pop("analyze", False) prefix = super().explain_query_prefix(format, **options) if analyze and self.connection.features.supports_explain_analyze: # MariaDB uses ANALYZE instead of EXPLAIN ANALYZE. prefix = ( "ANALYZE" if self.connection.mysql_is_mariadb else prefix + " ANALYZE" ) if format and not (analyze and not self.connection.mysql_is_mariadb): # Only MariaDB supports the analyze option with formats. prefix += " FORMAT=%s" % format return prefix def regex_lookup(self, lookup_type): # REGEXP BINARY doesn't work correctly in MySQL 8+ and REGEXP_LIKE # doesn't exist in MySQL 5.x or in MariaDB. if ( self.connection.mysql_version < (8, 0, 0) or self.connection.mysql_is_mariadb ): if lookup_type == "regex": return "%s REGEXP BINARY %s" return "%s REGEXP %s" match_option = "c" if lookup_type == "regex" else "i" return "REGEXP_LIKE(%%s, %%s, '%s')" % match_option def insert_statement(self, on_conflict=None): if on_conflict == OnConflict.IGNORE: return "INSERT IGNORE INTO" return super().insert_statement(on_conflict=on_conflict) def lookup_cast(self, lookup_type, internal_type=None): lookup = "%s" if internal_type == "JSONField": if self.connection.mysql_is_mariadb or lookup_type in ( "iexact", "contains", "icontains", "startswith", "istartswith", "endswith", "iendswith", "regex", "iregex", ): lookup = "JSON_UNQUOTE(%s)" return lookup def conditional_expression_supported_in_where_clause(self, expression): # MySQL ignores indexes with boolean fields unless they're compared # directly to a boolean value. if isinstance(expression, (Exists, Lookup)): return True if isinstance(expression, ExpressionWrapper) and expression.conditional: return self.conditional_expression_supported_in_where_clause( expression.expression ) if getattr(expression, "conditional", False): return False return super().conditional_expression_supported_in_where_clause(expression) def on_conflict_suffix_sql(self, fields, on_conflict, update_fields, unique_fields): if on_conflict == OnConflict.UPDATE: conflict_suffix_sql = "ON DUPLICATE KEY UPDATE %(fields)s" # The use of VALUES() is deprecated in MySQL 8.0.20+. Instead, use # aliases for the new row and its columns available in MySQL # 8.0.19+. if not self.connection.mysql_is_mariadb: if self.connection.mysql_version >= (8, 0, 19): conflict_suffix_sql = f"AS new {conflict_suffix_sql}" field_sql = "%(field)s = new.%(field)s" else: field_sql = "%(field)s = VALUES(%(field)s)" # Use VALUE() on MariaDB. else: field_sql = "%(field)s = VALUE(%(field)s)" fields = ", ".join( [ field_sql % {"field": field} for field in map(self.quote_name, update_fields) ] ) return conflict_suffix_sql % {"fields": fields} return super().on_conflict_suffix_sql( fields, on_conflict, update_fields, unique_fields, )
229c1d23e1f9afe414a0cf19bcf5c7ca437129bdb07af714c7c1efc539ffa2d5
import signal from django.db.backends.base.client import BaseDatabaseClient class DatabaseClient(BaseDatabaseClient): executable_name = "mysql" @classmethod def settings_to_cmd_args_env(cls, settings_dict, parameters): args = [cls.executable_name] env = None database = settings_dict["OPTIONS"].get( "database", settings_dict["OPTIONS"].get("db", settings_dict["NAME"]), ) user = settings_dict["OPTIONS"].get("user", settings_dict["USER"]) password = settings_dict["OPTIONS"].get( "password", settings_dict["OPTIONS"].get("passwd", settings_dict["PASSWORD"]), ) host = settings_dict["OPTIONS"].get("host", settings_dict["HOST"]) port = settings_dict["OPTIONS"].get("port", settings_dict["PORT"]) server_ca = settings_dict["OPTIONS"].get("ssl", {}).get("ca") client_cert = settings_dict["OPTIONS"].get("ssl", {}).get("cert") client_key = settings_dict["OPTIONS"].get("ssl", {}).get("key") defaults_file = settings_dict["OPTIONS"].get("read_default_file") charset = settings_dict["OPTIONS"].get("charset") # Seems to be no good way to set sql_mode with CLI. if defaults_file: args += ["--defaults-file=%s" % defaults_file] if user: args += ["--user=%s" % user] if password: # The MYSQL_PWD environment variable usage is discouraged per # MySQL's documentation due to the possibility of exposure through # `ps` on old Unix flavors but --password suffers from the same # flaw on even more systems. Usage of an environment variable also # prevents password exposure if the subprocess.run(check=True) call # raises a CalledProcessError since the string representation of # the latter includes all of the provided `args`. env = {"MYSQL_PWD": password} if host: if "/" in host: args += ["--socket=%s" % host] else: args += ["--host=%s" % host] if port: args += ["--port=%s" % port] if server_ca: args += ["--ssl-ca=%s" % server_ca] if client_cert: args += ["--ssl-cert=%s" % client_cert] if client_key: args += ["--ssl-key=%s" % client_key] if charset: args += ["--default-character-set=%s" % charset] if database: args += [database] args.extend(parameters) return args, env def runshell(self, parameters): sigint_handler = signal.getsignal(signal.SIGINT) try: # Allow SIGINT to pass to mysql to abort queries. signal.signal(signal.SIGINT, signal.SIG_IGN) super().runshell(parameters) finally: # Restore the original SIGINT handler. signal.signal(signal.SIGINT, sigint_handler)
a5e724f6b8b4b8c06517161adb0ad3e37325bbb2be6ead35e4cd7109e35aef1c
import operator from django.db import InterfaceError from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): minimum_database_version = (12,) allows_group_by_selected_pks = True can_return_columns_from_insert = True can_return_rows_from_bulk_insert = True has_real_datatype = True has_native_uuid_field = True has_native_duration_field = True has_native_json_field = True can_defer_constraint_checks = True has_select_for_update = True has_select_for_update_nowait = True has_select_for_update_of = True has_select_for_update_skip_locked = True has_select_for_no_key_update = True can_release_savepoints = True supports_tablespaces = True supports_transactions = True can_introspect_materialized_views = True can_distinct_on_fields = True can_rollback_ddl = True supports_combined_alters = True nulls_order_largest = True closed_cursor_error_class = InterfaceError greatest_least_ignores_nulls = True can_clone_databases = True supports_temporal_subtraction = True supports_slicing_ordering_in_compound = True create_test_procedure_without_params_sql = """ CREATE FUNCTION test_procedure () RETURNS void AS $$ DECLARE V_I INTEGER; BEGIN V_I := 1; END; $$ LANGUAGE plpgsql;""" create_test_procedure_with_int_param_sql = """ CREATE FUNCTION test_procedure (P_I INTEGER) RETURNS void AS $$ DECLARE V_I INTEGER; BEGIN V_I := P_I; END; $$ LANGUAGE plpgsql;""" create_test_table_with_composite_primary_key = """ CREATE TABLE test_table_composite_pk ( column_1 INTEGER NOT NULL, column_2 INTEGER NOT NULL, PRIMARY KEY(column_1, column_2) ) """ requires_casted_case_in_updates = True supports_over_clause = True only_supports_unbounded_with_preceding_and_following = True supports_aggregate_filter_clause = True supported_explain_formats = {"JSON", "TEXT", "XML", "YAML"} supports_deferrable_unique_constraints = True has_json_operators = True json_key_contains_list_matching_requires_list = True supports_update_conflicts = True supports_update_conflicts_with_target = True supports_covering_indexes = True can_rename_index = True test_collations = { "non_default": "sv-x-icu", "swedish_ci": "sv-x-icu", } test_now_utc_template = "STATEMENT_TIMESTAMP() AT TIME ZONE 'UTC'" django_test_skips = { "opclasses are PostgreSQL only.": { "indexes.tests.SchemaIndexesNotPostgreSQLTests." "test_create_index_ignores_opclasses", }, } @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "PositiveBigIntegerField": "BigIntegerField", "PositiveIntegerField": "IntegerField", "PositiveSmallIntegerField": "SmallIntegerField", } @cached_property def is_postgresql_13(self): return self.connection.pg_version >= 130000 @cached_property def is_postgresql_14(self): return self.connection.pg_version >= 140000 has_bit_xor = property(operator.attrgetter("is_postgresql_14")) supports_covering_spgist_indexes = property(operator.attrgetter("is_postgresql_14"))
68faf97cd165457c88f8d9b043f54a6996895851c3642641912b0369530a6504
import operator from django.db import transaction from django.db.backends.base.features import BaseDatabaseFeatures from django.db.utils import OperationalError from django.utils.functional import cached_property from .base import Database class DatabaseFeatures(BaseDatabaseFeatures): minimum_database_version = (3, 9) test_db_allows_multiple_connections = False supports_unspecified_pk = True supports_timezones = False max_query_params = 999 supports_transactions = True atomic_transactions = False can_rollback_ddl = True can_create_inline_fk = False supports_paramstyle_pyformat = False requires_literal_defaults = True can_clone_databases = True supports_temporal_subtraction = True ignores_table_name_case = True supports_cast_with_precision = False time_cast_precision = 3 can_release_savepoints = True has_case_insensitive_like = True # Is "ALTER TABLE ... RENAME COLUMN" supported? can_alter_table_rename_column = Database.sqlite_version_info >= (3, 25, 0) # Is "ALTER TABLE ... DROP COLUMN" supported? can_alter_table_drop_column = Database.sqlite_version_info >= (3, 35, 5) supports_parentheses_in_compound = False # Deferred constraint checks can be emulated on SQLite < 3.20 but not in a # reasonably performant way. supports_pragma_foreign_key_check = Database.sqlite_version_info >= (3, 20, 0) can_defer_constraint_checks = supports_pragma_foreign_key_check supports_functions_in_partial_indexes = Database.sqlite_version_info >= (3, 15, 0) supports_over_clause = Database.sqlite_version_info >= (3, 25, 0) supports_frame_range_fixed_distance = Database.sqlite_version_info >= (3, 28, 0) supports_aggregate_filter_clause = Database.sqlite_version_info >= (3, 30, 1) supports_order_by_nulls_modifier = Database.sqlite_version_info >= (3, 30, 0) order_by_nulls_first = True supports_json_field_contains = False supports_update_conflicts = Database.sqlite_version_info >= (3, 24, 0) supports_update_conflicts_with_target = supports_update_conflicts test_collations = { "ci": "nocase", "cs": "binary", "non_default": "nocase", } django_test_expected_failures = { # The django_format_dtdelta() function doesn't properly handle mixed # Date/DateTime fields and timedeltas. "expressions.tests.FTimeDeltaTests.test_mixed_comparisons1", } create_test_table_with_composite_primary_key = """ CREATE TABLE test_table_composite_pk ( column_1 INTEGER NOT NULL, column_2 INTEGER NOT NULL, PRIMARY KEY(column_1, column_2) ) """ @cached_property def django_test_skips(self): skips = { "SQLite stores values rounded to 15 significant digits.": { "model_fields.test_decimalfield.DecimalFieldTests." "test_fetch_from_db_without_float_rounding", }, "SQLite naively remakes the table on field alteration.": { "schema.tests.SchemaTests.test_unique_no_unnecessary_fk_drops", "schema.tests.SchemaTests.test_unique_and_reverse_m2m", "schema.tests.SchemaTests." "test_alter_field_default_doesnt_perform_queries", "schema.tests.SchemaTests." "test_rename_column_renames_deferred_sql_references", }, "SQLite doesn't support negative precision for ROUND().": { "db_functions.math.test_round.RoundTests." "test_null_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_decimal_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_float_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_integer_with_negative_precision", }, } if Database.sqlite_version_info < (3, 27): skips.update( { "Nondeterministic failure on SQLite < 3.27.": { "expressions_window.tests.WindowFunctionTests." "test_subquery_row_range_rank", }, } ) if self.connection.is_in_memory_db(): skips.update( { "the sqlite backend's close() method is a no-op when using an " "in-memory database": { "servers.test_liveserverthread.LiveServerThreadTest." "test_closes_connections", "servers.tests.LiveServerTestCloseConnectionTest." "test_closes_connections", }, } ) return skips @cached_property def supports_atomic_references_rename(self): return Database.sqlite_version_info >= (3, 26, 0) @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "BigAutoField": "AutoField", "DurationField": "BigIntegerField", "GenericIPAddressField": "CharField", "SmallAutoField": "AutoField", } @cached_property def supports_json_field(self): with self.connection.cursor() as cursor: try: with transaction.atomic(self.connection.alias): cursor.execute('SELECT JSON(\'{"a": "b"}\')') except OperationalError: return False return True can_introspect_json_field = property(operator.attrgetter("supports_json_field")) has_json_object_function = property(operator.attrgetter("supports_json_field")) @cached_property def can_return_columns_from_insert(self): return Database.sqlite_version_info >= (3, 35) can_return_rows_from_bulk_insert = property( operator.attrgetter("can_return_columns_from_insert") )
fb47c45f48071b9675bb4c47648dab133b303e0e84fd8377d4b2aaf5870f03a5
from collections import namedtuple import sqlparse from django.db import DatabaseError from django.db.backends.base.introspection import BaseDatabaseIntrospection from django.db.backends.base.introspection import FieldInfo as BaseFieldInfo from django.db.backends.base.introspection import TableInfo from django.db.models import Index from django.utils.regex_helper import _lazy_re_compile FieldInfo = namedtuple( "FieldInfo", BaseFieldInfo._fields + ("pk", "has_json_constraint") ) field_size_re = _lazy_re_compile(r"^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$") def get_field_size(name): """Extract the size number from a "varchar(11)" type name""" m = field_size_re.search(name) return int(m[1]) if m else None # This light wrapper "fakes" a dictionary interface, because some SQLite data # types include variables in them -- e.g. "varchar(30)" -- and can't be matched # as a simple dictionary lookup. class FlexibleFieldLookupDict: # Maps SQL types to Django Field types. Some of the SQL types have multiple # entries here because SQLite allows for anything and doesn't normalize the # field type; it uses whatever was given. base_data_types_reverse = { "bool": "BooleanField", "boolean": "BooleanField", "smallint": "SmallIntegerField", "smallint unsigned": "PositiveSmallIntegerField", "smallinteger": "SmallIntegerField", "int": "IntegerField", "integer": "IntegerField", "bigint": "BigIntegerField", "integer unsigned": "PositiveIntegerField", "bigint unsigned": "PositiveBigIntegerField", "decimal": "DecimalField", "real": "FloatField", "text": "TextField", "char": "CharField", "varchar": "CharField", "blob": "BinaryField", "date": "DateField", "datetime": "DateTimeField", "time": "TimeField", } def __getitem__(self, key): key = key.lower().split("(", 1)[0].strip() return self.base_data_types_reverse[key] class DatabaseIntrospection(BaseDatabaseIntrospection): data_types_reverse = FlexibleFieldLookupDict() def get_field_type(self, data_type, description): field_type = super().get_field_type(data_type, description) if description.pk and field_type in { "BigIntegerField", "IntegerField", "SmallIntegerField", }: # No support for BigAutoField or SmallAutoField as SQLite treats # all integer primary keys as signed 64-bit integers. return "AutoField" if description.has_json_constraint: return "JSONField" return field_type def get_table_list(self, cursor): """Return a list of table and view names in the current database.""" # Skip the sqlite_sequence system table used for autoincrement key # generation. cursor.execute( """ SELECT name, type FROM sqlite_master WHERE type in ('table', 'view') AND NOT name='sqlite_sequence' ORDER BY name""" ) return [TableInfo(row[0], row[1][0]) for row in cursor.fetchall()] def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface. """ cursor.execute( "PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name) ) table_info = cursor.fetchall() if not table_info: raise DatabaseError(f"Table {table_name} does not exist (empty pragma).") collations = self._get_column_collations(cursor, table_name) json_columns = set() if self.connection.features.can_introspect_json_field: for line in table_info: column = line[1] json_constraint_sql = '%%json_valid("%s")%%' % column has_json_constraint = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s AND sql LIKE %s """, [table_name, json_constraint_sql], ).fetchone() if has_json_constraint: json_columns.add(column) return [ FieldInfo( name, data_type, None, get_field_size(data_type), None, None, not notnull, default, collations.get(name), pk == 1, name in json_columns, ) for cid, name, data_type, notnull, default, pk in table_info ] def get_sequences(self, cursor, table_name, table_fields=()): pk_col = self.get_primary_key_column(cursor, table_name) return [{"table": table_name, "column": pk_col}] def get_relations(self, cursor, table_name): """ Return a dictionary of {column_name: (ref_column_name, ref_table_name)} representing all foreign keys in the given table. """ cursor.execute( "PRAGMA foreign_key_list(%s)" % self.connection.ops.quote_name(table_name) ) return { column_name: (ref_column_name, ref_table_name) for ( _, _, ref_table_name, column_name, ref_column_name, *_, ) in cursor.fetchall() } def get_primary_key_columns(self, cursor, table_name): cursor.execute( "PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name) ) return [name for _, name, *_, pk in cursor.fetchall() if pk] def _parse_column_or_constraint_definition(self, tokens, columns): token = None is_constraint_definition = None field_name = None constraint_name = None unique = False unique_columns = [] check = False check_columns = [] braces_deep = 0 for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): braces_deep += 1 elif token.match(sqlparse.tokens.Punctuation, ")"): braces_deep -= 1 if braces_deep < 0: # End of columns and constraints for table definition. break elif braces_deep == 0 and token.match(sqlparse.tokens.Punctuation, ","): # End of current column or constraint definition. break # Detect column or constraint definition by first token. if is_constraint_definition is None: is_constraint_definition = token.match( sqlparse.tokens.Keyword, "CONSTRAINT" ) if is_constraint_definition: continue if is_constraint_definition: # Detect constraint name by second token. if constraint_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): constraint_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: constraint_name = token.value[1:-1] # Start constraint columns parsing after UNIQUE keyword. if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique = True unique_braces_deep = braces_deep elif unique: if unique_braces_deep == braces_deep: if unique_columns: # Stop constraint parsing. unique = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): unique_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: unique_columns.append(token.value[1:-1]) else: # Detect field name by first token. if field_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): field_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: field_name = token.value[1:-1] if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique_columns = [field_name] # Start constraint columns parsing after CHECK keyword. if token.match(sqlparse.tokens.Keyword, "CHECK"): check = True check_braces_deep = braces_deep elif check: if check_braces_deep == braces_deep: if check_columns: # Stop constraint parsing. check = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): if token.value in columns: check_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: if token.value[1:-1] in columns: check_columns.append(token.value[1:-1]) unique_constraint = ( { "unique": True, "columns": unique_columns, "primary_key": False, "foreign_key": None, "check": False, "index": False, } if unique_columns else None ) check_constraint = ( { "check": True, "columns": check_columns, "primary_key": False, "unique": False, "foreign_key": None, "index": False, } if check_columns else None ) return constraint_name, unique_constraint, check_constraint, token def _parse_table_constraints(self, sql, columns): # Check constraint parsing is based of SQLite syntax diagram. # https://www.sqlite.org/syntaxdiagrams.html#table-constraint statement = sqlparse.parse(sql)[0] constraints = {} unnamed_constrains_index = 0 tokens = (token for token in statement.flatten() if not token.is_whitespace) # Go to columns and constraint definition for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): break # Parse columns and constraint definition while True: ( constraint_name, unique, check, end_token, ) = self._parse_column_or_constraint_definition(tokens, columns) if unique: if constraint_name: constraints[constraint_name] = unique else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = unique if check: if constraint_name: constraints[constraint_name] = check else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = check if end_token.match(sqlparse.tokens.Punctuation, ")"): break return constraints def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Find inline check constraints. try: table_schema = cursor.execute( "SELECT sql FROM sqlite_master WHERE type='table' and name=%s" % (self.connection.ops.quote_name(table_name),) ).fetchone()[0] except TypeError: # table_name is a view. pass else: columns = { info.name for info in self.get_table_description(cursor, table_name) } constraints.update(self._parse_table_constraints(table_schema, columns)) # Get the index info cursor.execute( "PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name) ) for row in cursor.fetchall(): # SQLite 3.8.9+ has 5 columns, however older versions only give 3 # columns. Discard last 2 columns if there. number, index, unique = row[:3] cursor.execute( "SELECT sql FROM sqlite_master " "WHERE type='index' AND name=%s" % self.connection.ops.quote_name(index) ) # There's at most one row. (sql,) = cursor.fetchone() or (None,) # Inline constraints are already detected in # _parse_table_constraints(). The reasons to avoid fetching inline # constraints from `PRAGMA index_list` are: # - Inline constraints can have a different name and information # than what `PRAGMA index_list` gives. # - Not all inline constraints may appear in `PRAGMA index_list`. if not sql: # An inline constraint continue # Get the index info for that index cursor.execute( "PRAGMA index_info(%s)" % self.connection.ops.quote_name(index) ) for index_rank, column_rank, column in cursor.fetchall(): if index not in constraints: constraints[index] = { "columns": [], "primary_key": False, "unique": bool(unique), "foreign_key": None, "check": False, "index": True, } constraints[index]["columns"].append(column) # Add type and column orders for indexes if constraints[index]["index"]: # SQLite doesn't support any index type other than b-tree constraints[index]["type"] = Index.suffix orders = self._get_index_columns_orders(sql) if orders is not None: constraints[index]["orders"] = orders # Get the PK pk_columns = self.get_primary_key_columns(cursor, table_name) if pk_columns: # SQLite doesn't actually give a name to the PK constraint, # so we invent one. This is fine, as the SQLite backend never # deletes PK constraints by name, as you can't delete constraints # in SQLite; we remake the table with a new PK instead. constraints["__primary__"] = { "columns": pk_columns, "primary_key": True, "unique": False, # It's not actually a unique constraint. "foreign_key": None, "check": False, "index": False, } relations = enumerate(self.get_relations(cursor, table_name).items()) constraints.update( { f"fk_{index}": { "columns": [column_name], "primary_key": False, "unique": False, "foreign_key": (ref_table_name, ref_column_name), "check": False, "index": False, } for index, (column_name, (ref_column_name, ref_table_name)) in relations } ) return constraints def _get_index_columns_orders(self, sql): tokens = sqlparse.parse(sql)[0] for token in tokens: if isinstance(token, sqlparse.sql.Parenthesis): columns = str(token).strip("()").split(", ") return ["DESC" if info.endswith("DESC") else "ASC" for info in columns] return None def _get_column_collations(self, cursor, table_name): row = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s """, [table_name], ).fetchone() if not row: return {} sql = row[0] columns = str(sqlparse.parse(sql)[0][-1]).strip("()").split(", ") collations = {} for column in columns: tokens = column[1:].split() column_name = tokens[0].strip('"') for index, token in enumerate(tokens): if token == "COLLATE": collation = tokens[index + 1] break else: collation = None collations[column_name] = collation return collations
52885cf458f6dc7878cbf2aea56a89180db9a6282169846f4eae0f8c24644e3b
""" Base classes for writing management commands (named commands which can be executed through ``django-admin`` or ``manage.py``). """ import argparse import os import sys from argparse import ArgumentParser, HelpFormatter from io import TextIOBase import django from django.core import checks from django.core.exceptions import ImproperlyConfigured from django.core.management.color import color_style, no_style from django.db import DEFAULT_DB_ALIAS, connections ALL_CHECKS = "__all__" class CommandError(Exception): """ Exception class indicating a problem while executing a management command. If this exception is raised during the execution of a management command, it will be caught and turned into a nicely-printed error message to the appropriate output stream (i.e., stderr); as a result, raising this exception (with a sensible description of the error) is the preferred way to indicate that something has gone wrong in the execution of a command. """ def __init__(self, *args, returncode=1, **kwargs): self.returncode = returncode super().__init__(*args, **kwargs) class SystemCheckError(CommandError): """ The system check framework detected unrecoverable errors. """ pass class CommandParser(ArgumentParser): """ Customized ArgumentParser class to improve some error messages and prevent SystemExit in several occasions, as SystemExit is unacceptable when a command is called programmatically. """ def __init__( self, *, missing_args_message=None, called_from_command_line=None, **kwargs ): self.missing_args_message = missing_args_message self.called_from_command_line = called_from_command_line super().__init__(**kwargs) def parse_args(self, args=None, namespace=None): # Catch missing argument for a better error message if self.missing_args_message and not ( args or any(not arg.startswith("-") for arg in args) ): self.error(self.missing_args_message) return super().parse_args(args, namespace) def error(self, message): if self.called_from_command_line: super().error(message) else: raise CommandError("Error: %s" % message) def handle_default_options(options): """ Include any default options that all commands should accept here so that ManagementUtility can handle them before searching for user commands. """ if options.settings: os.environ["DJANGO_SETTINGS_MODULE"] = options.settings if options.pythonpath: sys.path.insert(0, options.pythonpath) def no_translations(handle_func): """Decorator that forces a command to run with translations deactivated.""" def wrapper(*args, **kwargs): from django.utils import translation saved_locale = translation.get_language() translation.deactivate_all() try: res = handle_func(*args, **kwargs) finally: if saved_locale is not None: translation.activate(saved_locale) return res return wrapper class DjangoHelpFormatter(HelpFormatter): """ Customized formatter so that command-specific arguments appear in the --help output before arguments common to all commands. """ show_last = { "--version", "--verbosity", "--traceback", "--settings", "--pythonpath", "--no-color", "--force-color", "--skip-checks", } def _reordered_actions(self, actions): return sorted( actions, key=lambda a: set(a.option_strings) & self.show_last != set() ) def add_usage(self, usage, actions, *args, **kwargs): super().add_usage(usage, self._reordered_actions(actions), *args, **kwargs) def add_arguments(self, actions): super().add_arguments(self._reordered_actions(actions)) class OutputWrapper(TextIOBase): """ Wrapper around stdout/stderr """ @property def style_func(self): return self._style_func @style_func.setter def style_func(self, style_func): if style_func and self.isatty(): self._style_func = style_func else: self._style_func = lambda x: x def __init__(self, out, ending="\n"): self._out = out self.style_func = None self.ending = ending def __getattr__(self, name): return getattr(self._out, name) def flush(self): if hasattr(self._out, "flush"): self._out.flush() def isatty(self): return hasattr(self._out, "isatty") and self._out.isatty() def write(self, msg="", style_func=None, ending=None): ending = self.ending if ending is None else ending if ending and not msg.endswith(ending): msg += ending style_func = style_func or self.style_func self._out.write(style_func(msg)) class BaseCommand: """ The base class from which all management commands ultimately derive. Use this class if you want access to all of the mechanisms which parse the command-line arguments and work out what code to call in response; if you don't need to change any of that behavior, consider using one of the subclasses defined in this file. If you are interested in overriding/customizing various aspects of the command-parsing and -execution behavior, the normal flow works as follows: 1. ``django-admin`` or ``manage.py`` loads the command class and calls its ``run_from_argv()`` method. 2. The ``run_from_argv()`` method calls ``create_parser()`` to get an ``ArgumentParser`` for the arguments, parses them, performs any environment changes requested by options like ``pythonpath``, and then calls the ``execute()`` method, passing the parsed arguments. 3. The ``execute()`` method attempts to carry out the command by calling the ``handle()`` method with the parsed arguments; any output produced by ``handle()`` will be printed to standard output and, if the command is intended to produce a block of SQL statements, will be wrapped in ``BEGIN`` and ``COMMIT``. 4. If ``handle()`` or ``execute()`` raised any exception (e.g. ``CommandError``), ``run_from_argv()`` will instead print an error message to ``stderr``. Thus, the ``handle()`` method is typically the starting point for subclasses; many built-in commands and command types either place all of their logic in ``handle()``, or perform some additional parsing work in ``handle()`` and then delegate from it to more specialized methods as needed. Several attributes affect behavior at various steps along the way: ``help`` A short description of the command, which will be printed in help messages. ``output_transaction`` A boolean indicating whether the command outputs SQL statements; if ``True``, the output will automatically be wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is ``False``. ``requires_migrations_checks`` A boolean; if ``True``, the command prints a warning if the set of migrations on disk don't match the migrations in the database. ``requires_system_checks`` A list or tuple of tags, e.g. [Tags.staticfiles, Tags.models]. System checks registered in the chosen tags will be checked for errors prior to executing the command. The value '__all__' can be used to specify that all system checks should be performed. Default value is '__all__'. To validate an individual application's models rather than all applications' models, call ``self.check(app_configs)`` from ``handle()``, where ``app_configs`` is the list of application's configuration provided by the app registry. ``stealth_options`` A tuple of any options the command uses which aren't defined by the argument parser. """ # Metadata about this command. help = "" # Configuration shortcuts that alter various logic. _called_from_command_line = False output_transaction = False # Whether to wrap the output in a "BEGIN; COMMIT;" requires_migrations_checks = False requires_system_checks = "__all__" # Arguments, common to all commands, which aren't defined by the argument # parser. base_stealth_options = ("stderr", "stdout") # Command-specific options not defined by the argument parser. stealth_options = () suppressed_base_arguments = set() def __init__(self, stdout=None, stderr=None, no_color=False, force_color=False): self.stdout = OutputWrapper(stdout or sys.stdout) self.stderr = OutputWrapper(stderr or sys.stderr) if no_color and force_color: raise CommandError("'no_color' and 'force_color' can't be used together.") if no_color: self.style = no_style() else: self.style = color_style(force_color) self.stderr.style_func = self.style.ERROR if ( not isinstance(self.requires_system_checks, (list, tuple)) and self.requires_system_checks != ALL_CHECKS ): raise TypeError("requires_system_checks must be a list or tuple.") def get_version(self): """ Return the Django version, which should be correct for all built-in Django commands. User-supplied commands can override this method to return their own version. """ return django.get_version() def create_parser(self, prog_name, subcommand, **kwargs): """ Create and return the ``ArgumentParser`` which will be used to parse the arguments to this command. """ parser = CommandParser( prog="%s %s" % (os.path.basename(prog_name), subcommand), description=self.help or None, formatter_class=DjangoHelpFormatter, missing_args_message=getattr(self, "missing_args_message", None), called_from_command_line=getattr(self, "_called_from_command_line", None), **kwargs, ) self.add_base_argument( parser, "--version", action="version", version=self.get_version(), help="Show program's version number and exit.", ) self.add_base_argument( parser, "-v", "--verbosity", default=1, type=int, choices=[0, 1, 2, 3], help=( "Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, " "3=very verbose output" ), ) self.add_base_argument( parser, "--settings", help=( "The Python path to a settings module, e.g. " '"myproject.settings.main". If this isn\'t provided, the ' "DJANGO_SETTINGS_MODULE environment variable will be used." ), ) self.add_base_argument( parser, "--pythonpath", help=( "A directory to add to the Python path, e.g. " '"/home/djangoprojects/myproject".' ), ) self.add_base_argument( parser, "--traceback", action="store_true", help="Raise on CommandError exceptions.", ) self.add_base_argument( parser, "--no-color", action="store_true", help="Don't colorize the command output.", ) self.add_base_argument( parser, "--force-color", action="store_true", help="Force colorization of the command output.", ) if self.requires_system_checks: parser.add_argument( "--skip-checks", action="store_true", help="Skip system checks.", ) self.add_arguments(parser) return parser def add_arguments(self, parser): """ Entry point for subclassed commands to add custom arguments. """ pass def add_base_argument(self, parser, *args, **kwargs): """ Call the parser's add_argument() method, suppressing the help text according to BaseCommand.suppressed_base_arguments. """ for arg in args: if arg in self.suppressed_base_arguments: kwargs["help"] = argparse.SUPPRESS break parser.add_argument(*args, **kwargs) def print_help(self, prog_name, subcommand): """ Print the help message for this command, derived from ``self.usage()``. """ parser = self.create_parser(prog_name, subcommand) parser.print_help() def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. If the ``--traceback`` option is present or the raised ``Exception`` is not ``CommandError``, raise it. """ self._called_from_command_line = True parser = self.create_parser(argv[0], argv[1]) options = parser.parse_args(argv[2:]) cmd_options = vars(options) # Move positional args out of options to mimic legacy optparse args = cmd_options.pop("args", ()) handle_default_options(options) try: self.execute(*args, **cmd_options) except CommandError as e: if options.traceback: raise # SystemCheckError takes care of its own formatting. if isinstance(e, SystemCheckError): self.stderr.write(str(e), lambda x: x) else: self.stderr.write("%s: %s" % (e.__class__.__name__, e)) sys.exit(e.returncode) finally: try: connections.close_all() except ImproperlyConfigured: # Ignore if connections aren't setup at this point (e.g. no # configured settings). pass def execute(self, *args, **options): """ Try to execute this command, performing system checks if needed (as controlled by the ``requires_system_checks`` attribute, except if force-skipped). """ if options["force_color"] and options["no_color"]: raise CommandError( "The --no-color and --force-color options can't be used together." ) if options["force_color"]: self.style = color_style(force_color=True) elif options["no_color"]: self.style = no_style() self.stderr.style_func = None if options.get("stdout"): self.stdout = OutputWrapper(options["stdout"]) if options.get("stderr"): self.stderr = OutputWrapper(options["stderr"]) if self.requires_system_checks and not options["skip_checks"]: if self.requires_system_checks == ALL_CHECKS: self.check() else: self.check(tags=self.requires_system_checks) if self.requires_migrations_checks: self.check_migrations() output = self.handle(*args, **options) if output: if self.output_transaction: connection = connections[options.get("database", DEFAULT_DB_ALIAS)] output = "%s\n%s\n%s" % ( self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()), output, self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()), ) self.stdout.write(output) return output def check( self, app_configs=None, tags=None, display_num_errors=False, include_deployment_checks=False, fail_level=checks.ERROR, databases=None, ): """ Use the system check framework to validate entire Django project. Raise CommandError for any serious message (error or critical errors). If there are only light messages (like warnings), print them to stderr and don't raise an exception. """ all_issues = checks.run_checks( app_configs=app_configs, tags=tags, include_deployment_checks=include_deployment_checks, databases=databases, ) header, body, footer = "", "", "" visible_issue_count = 0 # excludes silenced warnings if all_issues: debugs = [ e for e in all_issues if e.level < checks.INFO and not e.is_silenced() ] infos = [ e for e in all_issues if checks.INFO <= e.level < checks.WARNING and not e.is_silenced() ] warnings = [ e for e in all_issues if checks.WARNING <= e.level < checks.ERROR and not e.is_silenced() ] errors = [ e for e in all_issues if checks.ERROR <= e.level < checks.CRITICAL and not e.is_silenced() ] criticals = [ e for e in all_issues if checks.CRITICAL <= e.level and not e.is_silenced() ] sorted_issues = [ (criticals, "CRITICALS"), (errors, "ERRORS"), (warnings, "WARNINGS"), (infos, "INFOS"), (debugs, "DEBUGS"), ] for issues, group_name in sorted_issues: if issues: visible_issue_count += len(issues) formatted = ( self.style.ERROR(str(e)) if e.is_serious() else self.style.WARNING(str(e)) for e in issues ) formatted = "\n".join(sorted(formatted)) body += "\n%s:\n%s\n" % (group_name, formatted) if visible_issue_count: header = "System check identified some issues:\n" if display_num_errors: if visible_issue_count: footer += "\n" footer += "System check identified %s (%s silenced)." % ( "no issues" if visible_issue_count == 0 else "1 issue" if visible_issue_count == 1 else "%s issues" % visible_issue_count, len(all_issues) - visible_issue_count, ) if any(e.is_serious(fail_level) and not e.is_silenced() for e in all_issues): msg = self.style.ERROR("SystemCheckError: %s" % header) + body + footer raise SystemCheckError(msg) else: msg = header + body + footer if msg: if visible_issue_count: self.stderr.write(msg, lambda x: x) else: self.stdout.write(msg) def check_migrations(self): """ Print a warning if the set of migrations on disk don't match the migrations in the database. """ from django.db.migrations.executor import MigrationExecutor try: executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) except ImproperlyConfigured: # No databases are configured (or the dummy one) return plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) if plan: apps_waiting_migration = sorted( {migration.app_label for migration, backwards in plan} ) self.stdout.write( self.style.NOTICE( "\nYou have %(unapplied_migration_count)s unapplied migration(s). " "Your project may not work properly until you apply the " "migrations for app(s): %(apps_waiting_migration)s." % { "unapplied_migration_count": len(plan), "apps_waiting_migration": ", ".join(apps_waiting_migration), } ) ) self.stdout.write( self.style.NOTICE("Run 'python manage.py migrate' to apply them.") ) def handle(self, *args, **options): """ The actual logic of the command. Subclasses must implement this method. """ raise NotImplementedError( "subclasses of BaseCommand must provide a handle() method" ) class AppCommand(BaseCommand): """ A management command which takes one or more installed application labels as arguments, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_app_config()``, which will be called once for each application. """ missing_args_message = "Enter at least one application label." def add_arguments(self, parser): parser.add_argument( "args", metavar="app_label", nargs="+", help="One or more application label.", ) def handle(self, *app_labels, **options): from django.apps import apps try: app_configs = [apps.get_app_config(app_label) for app_label in app_labels] except (LookupError, ImportError) as e: raise CommandError( "%s. Are you sure your INSTALLED_APPS setting is correct?" % e ) output = [] for app_config in app_configs: app_output = self.handle_app_config(app_config, **options) if app_output: output.append(app_output) return "\n".join(output) def handle_app_config(self, app_config, **options): """ Perform the command's actions for app_config, an AppConfig instance corresponding to an application label given on the command line. """ raise NotImplementedError( "Subclasses of AppCommand must provide a handle_app_config() method." ) class LabelCommand(BaseCommand): """ A management command which takes one or more arbitrary arguments (labels) on the command line, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_label()``, which will be called once for each label. If the arguments should be names of installed applications, use ``AppCommand`` instead. """ label = "label" missing_args_message = "Enter at least one %s." % label def add_arguments(self, parser): parser.add_argument("args", metavar=self.label, nargs="+") def handle(self, *labels, **options): output = [] for label in labels: label_output = self.handle_label(label, **options) if label_output: output.append(label_output) return "\n".join(output) def handle_label(self, label, **options): """ Perform the command's actions for ``label``, which will be the string as given on the command line. """ raise NotImplementedError( "subclasses of LabelCommand must provide a handle_label() method" )
fea3e1c6fc550915ae1efc8e5156aae9ec1bbde95deebbfb1c0bb63cf97b26bf
import logging import sys import tempfile import traceback from asgiref.sync import ThreadSensitiveContext, sync_to_async from django.conf import settings from django.core import signals from django.core.exceptions import RequestAborted, RequestDataTooBig from django.core.handlers import base from django.http import ( FileResponse, HttpRequest, HttpResponse, HttpResponseBadRequest, HttpResponseServerError, QueryDict, parse_cookie, ) from django.urls import set_script_prefix from django.utils.functional import cached_property logger = logging.getLogger("django.request") class ASGIRequest(HttpRequest): """ Custom request subclass that decodes from an ASGI-standard request dict and wraps request body handling. """ # Number of seconds until a Request gives up on trying to read a request # body and aborts. body_receive_timeout = 60 def __init__(self, scope, body_file): self.scope = scope self._post_parse_error = False self._read_started = False self.resolver_match = None self.script_name = self.scope.get("root_path", "") if self.script_name and scope["path"].startswith(self.script_name): # TODO: Better is-prefix checking, slash handling? self.path_info = scope["path"][len(self.script_name) :] else: self.path_info = scope["path"] # The Django path is different from ASGI scope path args, it should # combine with script name. if self.script_name: self.path = "%s/%s" % ( self.script_name.rstrip("/"), self.path_info.replace("/", "", 1), ) else: self.path = scope["path"] # HTTP basics. self.method = self.scope["method"].upper() # Ensure query string is encoded correctly. query_string = self.scope.get("query_string", "") if isinstance(query_string, bytes): query_string = query_string.decode() self.META = { "REQUEST_METHOD": self.method, "QUERY_STRING": query_string, "SCRIPT_NAME": self.script_name, "PATH_INFO": self.path_info, # WSGI-expecting code will need these for a while "wsgi.multithread": True, "wsgi.multiprocess": True, } if self.scope.get("client"): self.META["REMOTE_ADDR"] = self.scope["client"][0] self.META["REMOTE_HOST"] = self.META["REMOTE_ADDR"] self.META["REMOTE_PORT"] = self.scope["client"][1] if self.scope.get("server"): self.META["SERVER_NAME"] = self.scope["server"][0] self.META["SERVER_PORT"] = str(self.scope["server"][1]) else: self.META["SERVER_NAME"] = "unknown" self.META["SERVER_PORT"] = "0" # Headers go into META. for name, value in self.scope.get("headers", []): name = name.decode("latin1") if name == "content-length": corrected_name = "CONTENT_LENGTH" elif name == "content-type": corrected_name = "CONTENT_TYPE" else: corrected_name = "HTTP_%s" % name.upper().replace("-", "_") # HTTP/2 say only ASCII chars are allowed in headers, but decode # latin1 just in case. value = value.decode("latin1") if corrected_name in self.META: value = self.META[corrected_name] + "," + value self.META[corrected_name] = value # Pull out request encoding, if provided. self._set_content_type_params(self.META) # Directly assign the body file to be our stream. self._stream = body_file # Other bits. self.resolver_match = None @cached_property def GET(self): return QueryDict(self.META["QUERY_STRING"]) def _get_scheme(self): return self.scope.get("scheme") or super()._get_scheme() def _get_post(self): if not hasattr(self, "_post"): self._load_post_and_files() return self._post def _set_post(self, post): self._post = post def _get_files(self): if not hasattr(self, "_files"): self._load_post_and_files() return self._files POST = property(_get_post, _set_post) FILES = property(_get_files) @cached_property def COOKIES(self): return parse_cookie(self.META.get("HTTP_COOKIE", "")) class ASGIHandler(base.BaseHandler): """Handler for ASGI requests.""" request_class = ASGIRequest # Size to chunk response bodies into for multiple response messages. chunk_size = 2**16 def __init__(self): super().__init__() self.load_middleware(is_async=True) async def __call__(self, scope, receive, send): """ Async entrypoint - parses the request and hands off to get_response. """ # Serve only HTTP connections. # FIXME: Allow to override this. if scope["type"] != "http": raise ValueError( "Django can only handle ASGI/HTTP connections, not %s." % scope["type"] ) async with ThreadSensitiveContext(): await self.handle(scope, receive, send) async def handle(self, scope, receive, send): """ Handles the ASGI request. Called via the __call__ method. """ # Receive the HTTP request body as a stream object. try: body_file = await self.read_body(receive) except RequestAborted: return # Request is complete and can be served. try: set_script_prefix(self.get_script_prefix(scope)) await sync_to_async(signals.request_started.send, thread_sensitive=True)( sender=self.__class__, scope=scope ) # Get the request and check for basic issues. request, error_response = self.create_request(scope, body_file) if request is None: await self.send_response(error_response, send) return # Get the response, using the async mode of BaseHandler. response = await self.get_response_async(request) response._handler_class = self.__class__ finally: body_file.close() # Increase chunk size on file responses (ASGI servers handles low-level # chunking). if isinstance(response, FileResponse): response.block_size = self.chunk_size # Send the response. await self.send_response(response, send) async def read_body(self, receive): """Reads an HTTP body from an ASGI connection.""" # Use the tempfile that auto rolls-over to a disk file as it fills up. body_file = tempfile.SpooledTemporaryFile( max_size=settings.FILE_UPLOAD_MAX_MEMORY_SIZE, mode="w+b" ) while True: message = await receive() if message["type"] == "http.disconnect": body_file.close() # Early client disconnect. raise RequestAborted() # Add a body chunk from the message, if provided. if "body" in message: body_file.write(message["body"]) # Quit out if that's the end. if not message.get("more_body", False): break body_file.seek(0) return body_file def create_request(self, scope, body_file): """ Create the Request object and returns either (request, None) or (None, response) if there is an error response. """ try: return self.request_class(scope, body_file), None except UnicodeDecodeError: logger.warning( "Bad Request (UnicodeDecodeError)", exc_info=sys.exc_info(), extra={"status_code": 400}, ) return None, HttpResponseBadRequest() except RequestDataTooBig: return None, HttpResponse("413 Payload too large", status=413) def handle_uncaught_exception(self, request, resolver, exc_info): """Last-chance handler for exceptions.""" # There's no WSGI server to catch the exception further up # if this fails, so translate it into a plain text response. try: return super().handle_uncaught_exception(request, resolver, exc_info) except Exception: return HttpResponseServerError( traceback.format_exc() if settings.DEBUG else "Internal Server Error", content_type="text/plain", ) async def send_response(self, response, send): """Encode and send a response out over ASGI.""" # Collect cookies into headers. Have to preserve header case as there # are some non-RFC compliant clients that require e.g. Content-Type. response_headers = [] for header, value in response.items(): if isinstance(header, str): header = header.encode("ascii") if isinstance(value, str): value = value.encode("latin1") response_headers.append((bytes(header), bytes(value))) for c in response.cookies.values(): response_headers.append( (b"Set-Cookie", c.output(header="").encode("ascii").strip()) ) # Initial response message. await send( { "type": "http.response.start", "status": response.status_code, "headers": response_headers, } ) # Streaming responses need to be pinned to their iterator. if response.streaming: # Access `__iter__` and not `streaming_content` directly in case # it has been overridden in a subclass. for part in response: for chunk, _ in self.chunk_bytes(part): await send( { "type": "http.response.body", "body": chunk, # Ignore "more" as there may be more parts; instead, # use an empty final closing message with False. "more_body": True, } ) # Final closing message. await send({"type": "http.response.body"}) # Other responses just need chunking. else: # Yield chunks of response. for chunk, last in self.chunk_bytes(response.content): await send( { "type": "http.response.body", "body": chunk, "more_body": not last, } ) await sync_to_async(response.close, thread_sensitive=True)() @classmethod def chunk_bytes(cls, data): """ Chunks some data up so it can be sent in reasonable size messages. Yields (chunk, last_chunk) tuples. """ position = 0 if not data: yield data, True return while position < len(data): yield ( data[position : position + cls.chunk_size], (position + cls.chunk_size) >= len(data), ) position += cls.chunk_size def get_script_prefix(self, scope): """ Return the script prefix to use from either the scope or a setting. """ if settings.FORCE_SCRIPT_NAME: return settings.FORCE_SCRIPT_NAME return scope.get("root_path", "") or ""
0fb6c93d670484a94f62ad8fa77c5ec174fcec3d86fb2e56fa661e30b8defed5
import keyword import re from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections from django.db.models.constants import LOOKUP_SEP class Command(BaseCommand): help = ( "Introspects the database tables in the given database and outputs a Django " "model module." ) requires_system_checks = [] stealth_options = ("table_name_filter",) db_module = "django.db" def add_arguments(self, parser): parser.add_argument( "table", nargs="*", type=str, help="Selects what tables or views should be introspected.", ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, help=( 'Nominates a database to introspect. Defaults to using the "default" ' "database." ), ) parser.add_argument( "--include-partitions", action="store_true", help="Also output models for partition tables.", ) parser.add_argument( "--include-views", action="store_true", help="Also output models for database views.", ) def handle(self, **options): try: for line in self.handle_inspection(options): self.stdout.write(line) except NotImplementedError: raise CommandError( "Database inspection isn't supported for the currently selected " "database backend." ) def handle_inspection(self, options): connection = connections[options["database"]] # 'table_name_filter' is a stealth option table_name_filter = options.get("table_name_filter") def table2model(table_name): return re.sub(r"[^a-zA-Z0-9]", "", table_name.title()) with connection.cursor() as cursor: yield "# This is an auto-generated Django model module." yield "# You'll have to do the following manually to clean this up:" yield "# * Rearrange models' order" yield "# * Make sure each model has one field with primary_key=True" yield ( "# * Make sure each ForeignKey and OneToOneField has `on_delete` set " "to the desired behavior" ) yield ( "# * Remove `managed = False` lines if you wish to allow " "Django to create, modify, and delete the table" ) yield ( "# Feel free to rename the models, but don't rename db_table values or " "field names." ) yield "from %s import models" % self.db_module known_models = [] table_info = connection.introspection.get_table_list(cursor) # Determine types of tables and/or views to be introspected. types = {"t"} if options["include_partitions"]: types.add("p") if options["include_views"]: types.add("v") for table_name in options["table"] or sorted( info.name for info in table_info if info.type in types ): if table_name_filter is not None and callable(table_name_filter): if not table_name_filter(table_name): continue try: try: relations = connection.introspection.get_relations( cursor, table_name ) except NotImplementedError: relations = {} try: constraints = connection.introspection.get_constraints( cursor, table_name ) except NotImplementedError: constraints = {} primary_key_columns = ( connection.introspection.get_primary_key_columns( cursor, table_name ) ) primary_key_column = ( primary_key_columns[0] if primary_key_columns else None ) unique_columns = [ c["columns"][0] for c in constraints.values() if c["unique"] and len(c["columns"]) == 1 ] table_description = connection.introspection.get_table_description( cursor, table_name ) except Exception as e: yield "# Unable to inspect table '%s'" % table_name yield "# The error was: %s" % e continue yield "" yield "" yield "class %s(models.Model):" % table2model(table_name) known_models.append(table2model(table_name)) used_column_names = [] # Holds column names used in the table so far column_to_field_name = {} # Maps column names to names of model fields for row in table_description: comment_notes = ( [] ) # Holds Field notes, to be displayed in a Python comment. extra_params = {} # Holds Field parameters such as 'db_column'. column_name = row.name is_relation = column_name in relations att_name, params, notes = self.normalize_col_name( column_name, used_column_names, is_relation ) extra_params.update(params) comment_notes.extend(notes) used_column_names.append(att_name) column_to_field_name[column_name] = att_name # Add primary_key and unique, if necessary. if column_name == primary_key_column: extra_params["primary_key"] = True if len(primary_key_columns) > 1: comment_notes.append( "The composite primary key (%s) found, that is not " "supported. The first column is selected." % ", ".join(primary_key_columns) ) elif column_name in unique_columns: extra_params["unique"] = True if is_relation: ref_db_column, ref_db_table = relations[column_name] if extra_params.pop("unique", False) or extra_params.get( "primary_key" ): rel_type = "OneToOneField" else: rel_type = "ForeignKey" ref_pk_column = ( connection.introspection.get_primary_key_column( cursor, ref_db_table ) ) if ref_pk_column and ref_pk_column != ref_db_column: extra_params["to_field"] = ref_db_column rel_to = ( "self" if ref_db_table == table_name else table2model(ref_db_table) ) if rel_to in known_models: field_type = "%s(%s" % (rel_type, rel_to) else: field_type = "%s('%s'" % (rel_type, rel_to) else: # Calling `get_field_type` to get the field type string and any # additional parameters and notes. field_type, field_params, field_notes = self.get_field_type( connection, table_name, row ) extra_params.update(field_params) comment_notes.extend(field_notes) field_type += "(" # Don't output 'id = meta.AutoField(primary_key=True)', because # that's assumed if it doesn't exist. if att_name == "id" and extra_params == {"primary_key": True}: if field_type == "AutoField(": continue elif ( field_type == connection.features.introspected_field_types["AutoField"] + "(" ): comment_notes.append("AutoField?") # Add 'null' and 'blank', if the 'null_ok' flag was present in the # table description. if row.null_ok: # If it's NULL... extra_params["blank"] = True extra_params["null"] = True field_desc = "%s = %s%s" % ( att_name, # Custom fields will have a dotted path "" if "." in field_type else "models.", field_type, ) if field_type.startswith(("ForeignKey(", "OneToOneField(")): field_desc += ", models.DO_NOTHING" if extra_params: if not field_desc.endswith("("): field_desc += ", " field_desc += ", ".join( "%s=%r" % (k, v) for k, v in extra_params.items() ) field_desc += ")" if comment_notes: field_desc += " # " + " ".join(comment_notes) yield " %s" % field_desc is_view = any( info.name == table_name and info.type == "v" for info in table_info ) is_partition = any( info.name == table_name and info.type == "p" for info in table_info ) yield from self.get_meta( table_name, constraints, column_to_field_name, is_view, is_partition ) def normalize_col_name(self, col_name, used_column_names, is_relation): """ Modify the column name to make it Python-compatible as a field name """ field_params = {} field_notes = [] new_name = col_name.lower() if new_name != col_name: field_notes.append("Field name made lowercase.") if is_relation: if new_name.endswith("_id"): new_name = new_name[:-3] else: field_params["db_column"] = col_name new_name, num_repl = re.subn(r"\W", "_", new_name) if num_repl > 0: field_notes.append("Field renamed to remove unsuitable characters.") if new_name.find(LOOKUP_SEP) >= 0: while new_name.find(LOOKUP_SEP) >= 0: new_name = new_name.replace(LOOKUP_SEP, "_") if col_name.lower().find(LOOKUP_SEP) >= 0: # Only add the comment if the double underscore was in the original name field_notes.append( "Field renamed because it contained more than one '_' in a row." ) if new_name.startswith("_"): new_name = "field%s" % new_name field_notes.append("Field renamed because it started with '_'.") if new_name.endswith("_"): new_name = "%sfield" % new_name field_notes.append("Field renamed because it ended with '_'.") if keyword.iskeyword(new_name): new_name += "_field" field_notes.append("Field renamed because it was a Python reserved word.") if new_name[0].isdigit(): new_name = "number_%s" % new_name field_notes.append( "Field renamed because it wasn't a valid Python identifier." ) if new_name in used_column_names: num = 0 while "%s_%d" % (new_name, num) in used_column_names: num += 1 new_name = "%s_%d" % (new_name, num) field_notes.append("Field renamed because of name conflict.") if col_name != new_name and field_notes: field_params["db_column"] = col_name return new_name, field_params, field_notes def get_field_type(self, connection, table_name, row): """ Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. """ field_params = {} field_notes = [] try: field_type = connection.introspection.get_field_type(row.type_code, row) except KeyError: field_type = "TextField" field_notes.append("This field type is a guess.") # Add max_length for all CharFields. if field_type == "CharField" and row.internal_size: field_params["max_length"] = int(row.internal_size) if field_type in {"CharField", "TextField"} and row.collation: field_params["db_collation"] = row.collation if field_type == "DecimalField": if row.precision is None or row.scale is None: field_notes.append( "max_digits and decimal_places have been guessed, as this " "database handles decimal fields as float" ) field_params["max_digits"] = ( row.precision if row.precision is not None else 10 ) field_params["decimal_places"] = ( row.scale if row.scale is not None else 5 ) else: field_params["max_digits"] = row.precision field_params["decimal_places"] = row.scale return field_type, field_params, field_notes def get_meta( self, table_name, constraints, column_to_field_name, is_view, is_partition ): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ unique_together = [] has_unsupported_constraint = False for params in constraints.values(): if params["unique"]: columns = params["columns"] if None in columns: has_unsupported_constraint = True columns = [ x for x in columns if x is not None and x in column_to_field_name ] if len(columns) > 1: unique_together.append( str(tuple(column_to_field_name[c] for c in columns)) ) if is_view: managed_comment = " # Created from a view. Don't remove." elif is_partition: managed_comment = " # Created from a partition. Don't remove." else: managed_comment = "" meta = [""] if has_unsupported_constraint: meta.append(" # A unique constraint could not be introspected.") meta += [ " class Meta:", " managed = False%s" % managed_comment, " db_table = %r" % table_name, ] if unique_together: tup = "(" + ", ".join(unique_together) + ",)" meta += [" unique_together = %s" % tup] return meta
1600c692f85190cb86bc75b17e7b7d34dbba3642f0b648ff246673d161e3dc55
from django.apps import AppConfig from django.urls import get_resolver, get_urlconf from django.utils.translation import gettext_lazy as _ from .utils import _active, register_callback class AdminDocsConfig(AppConfig): name = "django.contrib.admindocs" verbose_name = _("Administrative Documentation") def ready(self): urlconf = get_urlconf() urlresolver = get_resolver(urlconf) register_callback(urlresolver, _active.local_value)
8d0c8e351db6129d7e01a33121812734dc60a1439c151b1433568ef49aafe1a0
"Misc. utility functions/classes for admin documentation generator." import functools import re from email.errors import HeaderParseError from email.parser import HeaderParser from inspect import cleandoc from asgiref.local import Local from django.urls import reverse from django.urls.resolvers import URLPattern from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe try: import docutils.core import docutils.nodes import docutils.parsers.rst.roles except ImportError: docutils_is_available = False else: docutils_is_available = True def get_view_name(view_func): if hasattr(view_func, "view_class"): klass = view_func.view_class return f"{klass.__module__}.{klass.__qualname__}" mod_name = view_func.__module__ view_name = getattr(view_func, "__qualname__", view_func.__class__.__name__) return mod_name + "." + view_name def parse_docstring(docstring): """ Parse out the parts of a docstring. Return (title, body, metadata). """ if not docstring: return "", "", {} docstring = cleandoc(docstring) parts = re.split(r"\n{2,}", docstring) title = parts[0] if len(parts) == 1: body = "" metadata = {} else: parser = HeaderParser() try: metadata = parser.parsestr(parts[-1]) except HeaderParseError: metadata = {} body = "\n\n".join(parts[1:]) else: metadata = dict(metadata.items()) if metadata: body = "\n\n".join(parts[1:-1]) else: body = "\n\n".join(parts[1:]) return title, body, metadata def parse_rst(text, default_reference_context, thing_being_parsed=None): """ Convert the string from reST to an XHTML fragment. """ overrides = { "doctitle_xform": True, "initial_header_level": 3, "default_reference_context": default_reference_context, "link_base": reverse("django-admindocs-docroot").rstrip("/"), "raw_enabled": False, "file_insertion_enabled": False, } thing_being_parsed = thing_being_parsed and "<%s>" % thing_being_parsed # Wrap ``text`` in some reST that sets the default role to ``cmsreference``, # then restores it. source = """ .. default-role:: cmsreference %s .. default-role:: """ parts = docutils.core.publish_parts( source % text, source_path=thing_being_parsed, destination_path=None, writer_name="html", settings_overrides=overrides, ) return mark_safe(parts["fragment"]) # # reST roles # ROLES = { "model": "%s/models/%s/", "view": "%s/views/%s/", "template": "%s/templates/%s/", "filter": "%s/filters/#%s", "tag": "%s/tags/#%s", } def create_reference_role(rolename, urlbase): def _role(name, rawtext, text, lineno, inliner, options=None, content=None): if options is None: options = {} node = docutils.nodes.reference( rawtext, text, refuri=( urlbase % ( inliner.document.settings.link_base, text.lower(), ) ), **options, ) return [node], [] docutils.parsers.rst.roles.register_canonical_role(rolename, _role) def default_reference_role( name, rawtext, text, lineno, inliner, options=None, content=None ): if options is None: options = {} context = inliner.document.settings.default_reference_context node = docutils.nodes.reference( rawtext, text, refuri=( ROLES[context] % ( inliner.document.settings.link_base, text.lower(), ) ), **options, ) return [node], [] if docutils_is_available: docutils.parsers.rst.roles.register_canonical_role( "cmsreference", default_reference_role ) for name, urlbase in ROLES.items(): create_reference_role(name, urlbase) # Match the beginning of a named, unnamed, or non-capturing groups. named_group_matcher = _lazy_re_compile(r"\(\?P(<\w+>)") unnamed_group_matcher = _lazy_re_compile(r"\(") non_capturing_group_matcher = _lazy_re_compile(r"\(\?\:") def replace_metacharacters(pattern): """Remove unescaped metacharacters from the pattern.""" return re.sub( r"((?:^|(?<!\\))(?:\\\\)*)(\\?)([?*+^$]|\\[bBAZ])", lambda m: m[1] + m[3] if m[2] else m[1], pattern, ) def _get_group_start_end(start, end, pattern): # Handle nested parentheses, e.g. '^(?P<a>(x|y))/b' or '^b/((x|y)\w+)$'. unmatched_open_brackets, prev_char = 1, None for idx, val in enumerate(pattern[end:]): # Check for unescaped `(` and `)`. They mark the start and end of a # nested group. if val == "(" and prev_char != "\\": unmatched_open_brackets += 1 elif val == ")" and prev_char != "\\": unmatched_open_brackets -= 1 prev_char = val # If brackets are balanced, the end of the string for the current named # capture group pattern has been reached. if unmatched_open_brackets == 0: return start, end + idx + 1 def _find_groups(pattern, group_matcher): prev_end = None for match in group_matcher.finditer(pattern): if indices := _get_group_start_end(match.start(0), match.end(0), pattern): start, end = indices if prev_end and start > prev_end or not prev_end: yield start, end, match prev_end = end def replace_named_groups(pattern): r""" Find named groups in `pattern` and replace them with the group name. E.g., 1. ^(?P<a>\w+)/b/(\w+)$ ==> ^<a>/b/(\w+)$ 2. ^(?P<a>\w+)/b/(?P<c>\w+)/$ ==> ^<a>/b/<c>/$ 3. ^(?P<a>\w+)/b/(\w+) ==> ^<a>/b/(\w+) 4. ^(?P<a>\w+)/b/(?P<c>\w+) ==> ^<a>/b/<c> """ group_pattern_and_name = [ (pattern[start:end], match[1]) for start, end, match in _find_groups(pattern, named_group_matcher) ] for group_pattern, group_name in group_pattern_and_name: pattern = pattern.replace(group_pattern, group_name) return pattern def replace_unnamed_groups(pattern): r""" Find unnamed groups in `pattern` and replace them with '<var>'. E.g., 1. ^(?P<a>\w+)/b/(\w+)$ ==> ^(?P<a>\w+)/b/<var>$ 2. ^(?P<a>\w+)/b/((x|y)\w+)$ ==> ^(?P<a>\w+)/b/<var>$ 3. ^(?P<a>\w+)/b/(\w+) ==> ^(?P<a>\w+)/b/<var> 4. ^(?P<a>\w+)/b/((x|y)\w+) ==> ^(?P<a>\w+)/b/<var> """ final_pattern, prev_end = "", None for start, end, _ in _find_groups(pattern, unnamed_group_matcher): if prev_end: final_pattern += pattern[prev_end:start] final_pattern += pattern[:start] + "<var>" prev_end = end return final_pattern + pattern[prev_end:] def remove_non_capturing_groups(pattern): r""" Find non-capturing groups in the given `pattern` and remove them, e.g. 1. (?P<a>\w+)/b/(?:\w+)c(?:\w+) => (?P<a>\\w+)/b/c 2. ^(?:\w+(?:\w+))a => ^a 3. ^a(?:\w+)/b(?:\w+) => ^a/b """ group_start_end_indices = _find_groups(pattern, non_capturing_group_matcher) final_pattern, prev_end = "", None for start, end, _ in group_start_end_indices: final_pattern += pattern[prev_end:start] prev_end = end return final_pattern + pattern[prev_end:] # Callback strings are cached in a dictionary for every urlconf. # The active calback_strs are stored by thread id to make them thread local. _callback_strs = set() _active = Local() _active.local_value = _callback_strs def _is_callback(name, urlresolver=None): if urlresolver and not urlresolver._populated: register_callback(urlresolver, _active.local_value) return name in _active.local_value @functools.lru_cache(maxsize=None) def lookup_str(urlpattern): """ A string that identifies the view (e.g. 'path.to.view_function' or 'path.to.ClassBasedView'). """ callback = urlpattern.callback if isinstance(callback, functools.partial): callback = callback.func if hasattr(callback, "view_class"): callback = callback.view_class elif not hasattr(callback, "__name__"): return callback.__module__ + "." + callback.__class__.__name__ return callback.__module__ + "." + callback.__qualname__ def register_callback(urlresolver, thread): for url_pattern in reversed(urlresolver.url_patterns): if isinstance(url_pattern, URLPattern): thread.add(lookup_str(url_pattern)) else: # url_pattern is a URLResolver. _active.url_pattern_value = _callback_strs register_callback(url_pattern, _active.url_pattern_value) thread.update(_active.url_pattern_value) urlresolver._populated = True
cadf92119ecfa83d9a34bec390a32a02e824f19d2219de9429368cc78cfccbac
import inspect from importlib import import_module from inspect import cleandoc from pathlib import Path from django.apps import apps from django.contrib import admin from django.contrib.admin.views.decorators import staff_member_required from django.contrib.admindocs import utils from django.contrib.admindocs.utils import ( remove_non_capturing_groups, replace_metacharacters, replace_named_groups, replace_unnamed_groups, ) from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.db import models from django.http import Http404 from django.template.engine import Engine from django.urls import get_mod_func, get_resolver, get_urlconf from django.utils._os import safe_join from django.utils.decorators import method_decorator from django.utils.functional import cached_property from django.utils.inspect import ( func_accepts_kwargs, func_accepts_var_args, get_func_full_args, method_has_no_args, ) from django.utils.translation import gettext as _ from django.views.generic import TemplateView from .utils import _is_callback, get_view_name # Exclude methods starting with these strings from documentation MODEL_METHODS_EXCLUDE = ("_", "add_", "delete", "save", "set_") class BaseAdminDocsView(TemplateView): """ Base view for admindocs views. """ @method_decorator(staff_member_required) def dispatch(self, request, *args, **kwargs): if not utils.docutils_is_available: # Display an error message for people without docutils self.template_name = "admin_doc/missing_docutils.html" return self.render_to_response(admin.site.each_context(request)) return super().dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): return super().get_context_data( **{ **kwargs, **admin.site.each_context(self.request), } ) class BookmarkletsView(BaseAdminDocsView): template_name = "admin_doc/bookmarklets.html" class TemplateTagIndexView(BaseAdminDocsView): template_name = "admin_doc/template_tag_index.html" def get_context_data(self, **kwargs): tags = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [("", lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for tag_name, tag_func in library.tags.items(): title, body, metadata = utils.parse_docstring(tag_func.__doc__) title = title and utils.parse_rst( title, "tag", _("tag:") + tag_name ) body = body and utils.parse_rst(body, "tag", _("tag:") + tag_name) for key in metadata: metadata[key] = utils.parse_rst( metadata[key], "tag", _("tag:") + tag_name ) tag_library = module_name.split(".")[-1] tags.append( { "name": tag_name, "title": title, "body": body, "meta": metadata, "library": tag_library, } ) return super().get_context_data(**{**kwargs, "tags": tags}) class TemplateFilterIndexView(BaseAdminDocsView): template_name = "admin_doc/template_filter_index.html" def get_context_data(self, **kwargs): filters = [] try: engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: app_libs = sorted(engine.template_libraries.items()) builtin_libs = [("", lib) for lib in engine.template_builtins] for module_name, library in builtin_libs + app_libs: for filter_name, filter_func in library.filters.items(): title, body, metadata = utils.parse_docstring(filter_func.__doc__) title = title and utils.parse_rst( title, "filter", _("filter:") + filter_name ) body = body and utils.parse_rst( body, "filter", _("filter:") + filter_name ) for key in metadata: metadata[key] = utils.parse_rst( metadata[key], "filter", _("filter:") + filter_name ) tag_library = module_name.split(".")[-1] filters.append( { "name": filter_name, "title": title, "body": body, "meta": metadata, "library": tag_library, } ) return super().get_context_data(**{**kwargs, "filters": filters}) class ViewIndexView(BaseAdminDocsView): template_name = "admin_doc/view_index.html" def get_context_data(self, **kwargs): views = [] url_resolver = get_resolver(get_urlconf()) try: view_functions = extract_views_from_urlpatterns(url_resolver.url_patterns) except ImproperlyConfigured: view_functions = [] for (func, regex, namespace, name) in view_functions: views.append( { "full_name": get_view_name(func), "url": simplify_regex(regex), "url_name": ":".join((namespace or []) + (name and [name] or [])), "namespace": ":".join(namespace or []), "name": name, } ) return super().get_context_data(**{**kwargs, "views": views}) class ViewDetailView(BaseAdminDocsView): template_name = "admin_doc/view_detail.html" @staticmethod def _get_view_func(view): if _is_callback(view): mod, func = get_mod_func(view) try: # Separate the module and function, e.g. # 'mymodule.views.myview' -> 'mymodule.views', 'myview'). return getattr(import_module(mod), func) except ImportError: # Import may fail because view contains a class name, e.g. # 'mymodule.views.ViewContainer.my_view', so mod takes the form # 'mymodule.views.ViewContainer'. Parse it again to separate # the module and class. mod, klass = get_mod_func(mod) return getattr(getattr(import_module(mod), klass), func) def get_context_data(self, **kwargs): view = self.kwargs["view"] view_func = self._get_view_func(view) if view_func is None: raise Http404 title, body, metadata = utils.parse_docstring(view_func.__doc__) title = title and utils.parse_rst(title, "view", _("view:") + view) body = body and utils.parse_rst(body, "view", _("view:") + view) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], "model", _("view:") + view) return super().get_context_data( **{ **kwargs, "name": view, "summary": title, "body": body, "meta": metadata, } ) class ModelIndexView(BaseAdminDocsView): template_name = "admin_doc/model_index.html" def get_context_data(self, **kwargs): m_list = [m._meta for m in apps.get_models()] return super().get_context_data(**{**kwargs, "models": m_list}) class ModelDetailView(BaseAdminDocsView): template_name = "admin_doc/model_detail.html" def get_context_data(self, **kwargs): model_name = self.kwargs["model_name"] # Get the model class. try: app_config = apps.get_app_config(self.kwargs["app_label"]) except LookupError: raise Http404(_("App %(app_label)r not found") % self.kwargs) try: model = app_config.get_model(model_name) except LookupError: raise Http404( _("Model %(model_name)r not found in app %(app_label)r") % self.kwargs ) opts = model._meta title, body, metadata = utils.parse_docstring(model.__doc__) title = title and utils.parse_rst(title, "model", _("model:") + model_name) body = body and utils.parse_rst(body, "model", _("model:") + model_name) # Gather fields/field descriptions. fields = [] for field in opts.fields: # ForeignKey is a special case since the field will actually be a # descriptor that returns the other object if isinstance(field, models.ForeignKey): data_type = field.remote_field.model.__name__ app_label = field.remote_field.model._meta.app_label verbose = utils.parse_rst( ( _("the related `%(app_label)s.%(data_type)s` object") % { "app_label": app_label, "data_type": data_type, } ), "model", _("model:") + data_type, ) else: data_type = get_readable_field_data_type(field) verbose = field.verbose_name fields.append( { "name": field.name, "data_type": data_type, "verbose": verbose or "", "help_text": field.help_text, } ) # Gather many-to-many fields. for field in opts.many_to_many: data_type = field.remote_field.model.__name__ app_label = field.remote_field.model._meta.app_label verbose = _("related `%(app_label)s.%(object_name)s` objects") % { "app_label": app_label, "object_name": data_type, } fields.append( { "name": "%s.all" % field.name, "data_type": "List", "verbose": utils.parse_rst( _("all %s") % verbose, "model", _("model:") + opts.model_name ), } ) fields.append( { "name": "%s.count" % field.name, "data_type": "Integer", "verbose": utils.parse_rst( _("number of %s") % verbose, "model", _("model:") + opts.model_name, ), } ) methods = [] # Gather model methods. for func_name, func in model.__dict__.items(): if inspect.isfunction(func) or isinstance( func, (cached_property, property) ): try: for exclude in MODEL_METHODS_EXCLUDE: if func_name.startswith(exclude): raise StopIteration except StopIteration: continue verbose = func.__doc__ verbose = verbose and ( utils.parse_rst( cleandoc(verbose), "model", _("model:") + opts.model_name ) ) # Show properties, cached_properties, and methods without # arguments as fields. Otherwise, show as a 'method with # arguments'. if isinstance(func, (cached_property, property)): fields.append( { "name": func_name, "data_type": get_return_data_type(func_name), "verbose": verbose or "", } ) elif ( method_has_no_args(func) and not func_accepts_kwargs(func) and not func_accepts_var_args(func) ): fields.append( { "name": func_name, "data_type": get_return_data_type(func_name), "verbose": verbose or "", } ) else: arguments = get_func_full_args(func) # Join arguments with ', ' and in case of default value, # join it with '='. Use repr() so that strings will be # correctly displayed. print_arguments = ", ".join( [ "=".join([arg_el[0], *map(repr, arg_el[1:])]) for arg_el in arguments ] ) methods.append( { "name": func_name, "arguments": print_arguments, "verbose": verbose or "", } ) # Gather related objects for rel in opts.related_objects: verbose = _("related `%(app_label)s.%(object_name)s` objects") % { "app_label": rel.related_model._meta.app_label, "object_name": rel.related_model._meta.object_name, } accessor = rel.get_accessor_name() fields.append( { "name": "%s.all" % accessor, "data_type": "List", "verbose": utils.parse_rst( _("all %s") % verbose, "model", _("model:") + opts.model_name ), } ) fields.append( { "name": "%s.count" % accessor, "data_type": "Integer", "verbose": utils.parse_rst( _("number of %s") % verbose, "model", _("model:") + opts.model_name, ), } ) return super().get_context_data( **{ **kwargs, "name": opts.label, "summary": title, "description": body, "fields": fields, "methods": methods, } ) class TemplateDetailView(BaseAdminDocsView): template_name = "admin_doc/template_detail.html" def get_context_data(self, **kwargs): template = self.kwargs["template"] templates = [] try: default_engine = Engine.get_default() except ImproperlyConfigured: # Non-trivial TEMPLATES settings aren't supported (#24125). pass else: # This doesn't account for template loaders (#24128). for index, directory in enumerate(default_engine.dirs): template_file = Path(safe_join(directory, template)) if template_file.exists(): template_contents = template_file.read_text() else: template_contents = "" templates.append( { "file": template_file, "exists": template_file.exists(), "contents": template_contents, "order": index, } ) return super().get_context_data( **{ **kwargs, "name": template, "templates": templates, } ) #################### # Helper functions # #################### def get_return_data_type(func_name): """Return a somewhat-helpful data type given a function name""" if func_name.startswith("get_"): if func_name.endswith("_list"): return "List" elif func_name.endswith("_count"): return "Integer" return "" def get_readable_field_data_type(field): """ Return the description for a given field type, if it exists. Fields' descriptions can contain format strings, which will be interpolated with the values of field.__dict__ before being output. """ return field.description % field.__dict__ def extract_views_from_urlpatterns(urlpatterns, base="", namespace=None): """ Return a list of views from a list of urlpatterns. Each object in the returned list is a four-tuple: (view_func, regex, namespace, name) """ views = [] for p in urlpatterns: if hasattr(p, "url_patterns"): try: patterns = p.url_patterns except ImportError: continue views.extend( extract_views_from_urlpatterns( patterns, base + str(p.pattern), (namespace or []) + (p.namespace and [p.namespace] or []), ) ) elif hasattr(p, "callback"): try: views.append((p.callback, base + str(p.pattern), namespace, p.name)) except ViewDoesNotExist: continue else: raise TypeError(_("%s does not appear to be a urlpattern object") % p) return views def simplify_regex(pattern): r""" Clean up urlpattern regexes into something more readable by humans. For example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$" into "/<sport_slug>/athletes/<athlete_slug>/". """ pattern = remove_non_capturing_groups(pattern) pattern = replace_named_groups(pattern) pattern = replace_unnamed_groups(pattern) pattern = replace_metacharacters(pattern) if not pattern.startswith("/"): pattern = "/" + pattern return pattern
8c533332de92c02eda080fad5d2aec06504f096421c63dd7bb9574e2ec314e4c
from django.db import NotSupportedError from django.db.models import Func, Index from django.utils.functional import cached_property __all__ = [ "BloomIndex", "BrinIndex", "BTreeIndex", "GinIndex", "GistIndex", "HashIndex", "SpGistIndex", ] class PostgresIndex(Index): @cached_property def max_name_length(self): # Allow an index name longer than 30 characters when the suffix is # longer than the usual 3 character limit. The 30 character limit for # cross-database compatibility isn't applicable to PostgreSQL-specific # indexes. return Index.max_name_length - len(Index.suffix) + len(self.suffix) def create_sql(self, model, schema_editor, using="", **kwargs): self.check_supported(schema_editor) statement = super().create_sql( model, schema_editor, using=" USING %s" % (using or self.suffix), **kwargs ) with_params = self.get_with_params() if with_params: statement.parts["extra"] = " WITH (%s)%s" % ( ", ".join(with_params), statement.parts["extra"], ) return statement def check_supported(self, schema_editor): pass def get_with_params(self): return [] class BloomIndex(PostgresIndex): suffix = "bloom" def __init__(self, *expressions, length=None, columns=(), **kwargs): super().__init__(*expressions, **kwargs) if len(self.fields) > 32: raise ValueError("Bloom indexes support a maximum of 32 fields.") if not isinstance(columns, (list, tuple)): raise ValueError("BloomIndex.columns must be a list or tuple.") if len(columns) > len(self.fields): raise ValueError("BloomIndex.columns cannot have more values than fields.") if not all(0 < col <= 4095 for col in columns): raise ValueError( "BloomIndex.columns must contain integers from 1 to 4095.", ) if length is not None and not 0 < length <= 4096: raise ValueError( "BloomIndex.length must be None or an integer from 1 to 4096.", ) self.length = length self.columns = columns def deconstruct(self): path, args, kwargs = super().deconstruct() if self.length is not None: kwargs["length"] = self.length if self.columns: kwargs["columns"] = self.columns return path, args, kwargs def get_with_params(self): with_params = [] if self.length is not None: with_params.append("length = %d" % self.length) if self.columns: with_params.extend( "col%d = %d" % (i, v) for i, v in enumerate(self.columns, start=1) ) return with_params class BrinIndex(PostgresIndex): suffix = "brin" def __init__( self, *expressions, autosummarize=None, pages_per_range=None, **kwargs ): if pages_per_range is not None and pages_per_range <= 0: raise ValueError("pages_per_range must be None or a positive integer") self.autosummarize = autosummarize self.pages_per_range = pages_per_range super().__init__(*expressions, **kwargs) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.autosummarize is not None: kwargs["autosummarize"] = self.autosummarize if self.pages_per_range is not None: kwargs["pages_per_range"] = self.pages_per_range return path, args, kwargs def get_with_params(self): with_params = [] if self.autosummarize is not None: with_params.append( "autosummarize = %s" % ("on" if self.autosummarize else "off") ) if self.pages_per_range is not None: with_params.append("pages_per_range = %d" % self.pages_per_range) return with_params class BTreeIndex(PostgresIndex): suffix = "btree" def __init__(self, *expressions, fillfactor=None, **kwargs): self.fillfactor = fillfactor super().__init__(*expressions, **kwargs) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.fillfactor is not None: kwargs["fillfactor"] = self.fillfactor return path, args, kwargs def get_with_params(self): with_params = [] if self.fillfactor is not None: with_params.append("fillfactor = %d" % self.fillfactor) return with_params class GinIndex(PostgresIndex): suffix = "gin" def __init__( self, *expressions, fastupdate=None, gin_pending_list_limit=None, **kwargs ): self.fastupdate = fastupdate self.gin_pending_list_limit = gin_pending_list_limit super().__init__(*expressions, **kwargs) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.fastupdate is not None: kwargs["fastupdate"] = self.fastupdate if self.gin_pending_list_limit is not None: kwargs["gin_pending_list_limit"] = self.gin_pending_list_limit return path, args, kwargs def get_with_params(self): with_params = [] if self.gin_pending_list_limit is not None: with_params.append( "gin_pending_list_limit = %d" % self.gin_pending_list_limit ) if self.fastupdate is not None: with_params.append("fastupdate = %s" % ("on" if self.fastupdate else "off")) return with_params class GistIndex(PostgresIndex): suffix = "gist" def __init__(self, *expressions, buffering=None, fillfactor=None, **kwargs): self.buffering = buffering self.fillfactor = fillfactor super().__init__(*expressions, **kwargs) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.buffering is not None: kwargs["buffering"] = self.buffering if self.fillfactor is not None: kwargs["fillfactor"] = self.fillfactor return path, args, kwargs def get_with_params(self): with_params = [] if self.buffering is not None: with_params.append("buffering = %s" % ("on" if self.buffering else "off")) if self.fillfactor is not None: with_params.append("fillfactor = %d" % self.fillfactor) return with_params class HashIndex(PostgresIndex): suffix = "hash" def __init__(self, *expressions, fillfactor=None, **kwargs): self.fillfactor = fillfactor super().__init__(*expressions, **kwargs) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.fillfactor is not None: kwargs["fillfactor"] = self.fillfactor return path, args, kwargs def get_with_params(self): with_params = [] if self.fillfactor is not None: with_params.append("fillfactor = %d" % self.fillfactor) return with_params class SpGistIndex(PostgresIndex): suffix = "spgist" def __init__(self, *expressions, fillfactor=None, **kwargs): self.fillfactor = fillfactor super().__init__(*expressions, **kwargs) def deconstruct(self): path, args, kwargs = super().deconstruct() if self.fillfactor is not None: kwargs["fillfactor"] = self.fillfactor return path, args, kwargs def get_with_params(self): with_params = [] if self.fillfactor is not None: with_params.append("fillfactor = %d" % self.fillfactor) return with_params def check_supported(self, schema_editor): if ( self.include and not schema_editor.connection.features.supports_covering_spgist_indexes ): raise NotSupportedError("Covering SP-GiST indexes require PostgreSQL 14+.") class OpClass(Func): template = "%(expressions)s %(name)s" def __init__(self, expression, name): super().__init__(expression, name=name)
f50fc204ff276caa9098084d15a0d7aabb82bfd10a27c9172f1720d59594d5b3
from django.contrib.postgres.signals import ( get_citext_oids, get_hstore_oids, register_type_handlers, ) from django.db import NotSupportedError, router from django.db.migrations import AddConstraint, AddIndex, RemoveIndex from django.db.migrations.operations.base import Operation from django.db.models.constraints import CheckConstraint class CreateExtension(Operation): reversible = True def __init__(self, name): self.name = name def state_forwards(self, app_label, state): pass def database_forwards(self, app_label, schema_editor, from_state, to_state): if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate( schema_editor.connection.alias, app_label ): return if not self.extension_exists(schema_editor, self.name): schema_editor.execute( "CREATE EXTENSION IF NOT EXISTS %s" % schema_editor.quote_name(self.name) ) # Clear cached, stale oids. get_hstore_oids.cache_clear() get_citext_oids.cache_clear() # Registering new type handlers cannot be done before the extension is # installed, otherwise a subsequent data migration would use the same # connection. register_type_handlers(schema_editor.connection) def database_backwards(self, app_label, schema_editor, from_state, to_state): if not router.allow_migrate(schema_editor.connection.alias, app_label): return if self.extension_exists(schema_editor, self.name): schema_editor.execute( "DROP EXTENSION IF EXISTS %s" % schema_editor.quote_name(self.name) ) # Clear cached, stale oids. get_hstore_oids.cache_clear() get_citext_oids.cache_clear() def extension_exists(self, schema_editor, extension): with schema_editor.connection.cursor() as cursor: cursor.execute( "SELECT 1 FROM pg_extension WHERE extname = %s", [extension], ) return bool(cursor.fetchone()) def describe(self): return "Creates extension %s" % self.name @property def migration_name_fragment(self): return "create_extension_%s" % self.name class BloomExtension(CreateExtension): def __init__(self): self.name = "bloom" class BtreeGinExtension(CreateExtension): def __init__(self): self.name = "btree_gin" class BtreeGistExtension(CreateExtension): def __init__(self): self.name = "btree_gist" class CITextExtension(CreateExtension): def __init__(self): self.name = "citext" class CryptoExtension(CreateExtension): def __init__(self): self.name = "pgcrypto" class HStoreExtension(CreateExtension): def __init__(self): self.name = "hstore" class TrigramExtension(CreateExtension): def __init__(self): self.name = "pg_trgm" class UnaccentExtension(CreateExtension): def __init__(self): self.name = "unaccent" class NotInTransactionMixin: def _ensure_not_in_transaction(self, schema_editor): if schema_editor.connection.in_atomic_block: raise NotSupportedError( "The %s operation cannot be executed inside a transaction " "(set atomic = False on the migration)." % self.__class__.__name__ ) class AddIndexConcurrently(NotInTransactionMixin, AddIndex): """Create an index using PostgreSQL's CREATE INDEX CONCURRENTLY syntax.""" atomic = False def describe(self): return "Concurrently create index %s on field(s) %s of model %s" % ( self.index.name, ", ".join(self.index.fields), self.model_name, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): self._ensure_not_in_transaction(schema_editor) model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.add_index(model, self.index, concurrently=True) def database_backwards(self, app_label, schema_editor, from_state, to_state): self._ensure_not_in_transaction(schema_editor) model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.remove_index(model, self.index, concurrently=True) class RemoveIndexConcurrently(NotInTransactionMixin, RemoveIndex): """Remove an index using PostgreSQL's DROP INDEX CONCURRENTLY syntax.""" atomic = False def describe(self): return "Concurrently remove index %s from %s" % (self.name, self.model_name) def database_forwards(self, app_label, schema_editor, from_state, to_state): self._ensure_not_in_transaction(schema_editor) model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): from_model_state = from_state.models[app_label, self.model_name_lower] index = from_model_state.get_index_by_name(self.name) schema_editor.remove_index(model, index, concurrently=True) def database_backwards(self, app_label, schema_editor, from_state, to_state): self._ensure_not_in_transaction(schema_editor) model = to_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): to_model_state = to_state.models[app_label, self.model_name_lower] index = to_model_state.get_index_by_name(self.name) schema_editor.add_index(model, index, concurrently=True) class CollationOperation(Operation): def __init__(self, name, locale, *, provider="libc", deterministic=True): self.name = name self.locale = locale self.provider = provider self.deterministic = deterministic def state_forwards(self, app_label, state): pass def deconstruct(self): kwargs = {"name": self.name, "locale": self.locale} if self.provider and self.provider != "libc": kwargs["provider"] = self.provider if self.deterministic is False: kwargs["deterministic"] = self.deterministic return ( self.__class__.__qualname__, [], kwargs, ) def create_collation(self, schema_editor): args = {"locale": schema_editor.quote_name(self.locale)} if self.provider != "libc": args["provider"] = schema_editor.quote_name(self.provider) if self.deterministic is False: args["deterministic"] = "false" schema_editor.execute( "CREATE COLLATION %(name)s (%(args)s)" % { "name": schema_editor.quote_name(self.name), "args": ", ".join( f"{option}={value}" for option, value in args.items() ), } ) def remove_collation(self, schema_editor): schema_editor.execute( "DROP COLLATION %s" % schema_editor.quote_name(self.name), ) class CreateCollation(CollationOperation): """Create a collation.""" def database_forwards(self, app_label, schema_editor, from_state, to_state): if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate( schema_editor.connection.alias, app_label ): return self.create_collation(schema_editor) def database_backwards(self, app_label, schema_editor, from_state, to_state): if not router.allow_migrate(schema_editor.connection.alias, app_label): return self.remove_collation(schema_editor) def describe(self): return f"Create collation {self.name}" @property def migration_name_fragment(self): return "create_collation_%s" % self.name.lower() class RemoveCollation(CollationOperation): """Remove a collation.""" def database_forwards(self, app_label, schema_editor, from_state, to_state): if schema_editor.connection.vendor != "postgresql" or not router.allow_migrate( schema_editor.connection.alias, app_label ): return self.remove_collation(schema_editor) def database_backwards(self, app_label, schema_editor, from_state, to_state): if not router.allow_migrate(schema_editor.connection.alias, app_label): return self.create_collation(schema_editor) def describe(self): return f"Remove collation {self.name}" @property def migration_name_fragment(self): return "remove_collation_%s" % self.name.lower() class AddConstraintNotValid(AddConstraint): """ Add a table constraint without enforcing validation, using PostgreSQL's NOT VALID syntax. """ def __init__(self, model_name, constraint): if not isinstance(constraint, CheckConstraint): raise TypeError( "AddConstraintNotValid.constraint must be a check constraint." ) super().__init__(model_name, constraint) def describe(self): return "Create not valid constraint %s on model %s" % ( self.constraint.name, self.model_name, ) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): constraint_sql = self.constraint.create_sql(model, schema_editor) if constraint_sql: # Constraint.create_sql returns interpolated SQL which makes # params=None a necessity to avoid escaping attempts on # execution. schema_editor.execute(str(constraint_sql) + " NOT VALID", params=None) @property def migration_name_fragment(self): return super().migration_name_fragment + "_not_valid" class ValidateConstraint(Operation): """Validate a table NOT VALID constraint.""" def __init__(self, model_name, name): self.model_name = model_name self.name = name def describe(self): return "Validate constraint %s on model %s" % (self.name, self.model_name) def database_forwards(self, app_label, schema_editor, from_state, to_state): model = from_state.apps.get_model(app_label, self.model_name) if self.allow_migrate_model(schema_editor.connection.alias, model): schema_editor.execute( "ALTER TABLE %s VALIDATE CONSTRAINT %s" % ( schema_editor.quote_name(model._meta.db_table), schema_editor.quote_name(self.name), ) ) def database_backwards(self, app_label, schema_editor, from_state, to_state): # PostgreSQL does not provide a way to make a constraint invalid. pass def state_forwards(self, app_label, state): pass @property def migration_name_fragment(self): return "%s_validate_%s" % (self.model_name.lower(), self.name.lower()) def deconstruct(self): return ( self.__class__.__name__, [], { "model_name": self.model_name, "name": self.name, }, )
501bc9fac8aa121193cc893b7b02db67eb8eac8efb4d76a6c3341c3f69497bd5
import warnings from django.contrib.postgres.indexes import OpClass from django.core.exceptions import ValidationError from django.db import DEFAULT_DB_ALIAS, NotSupportedError from django.db.backends.ddl_references import Expressions, Statement, Table from django.db.models import BaseConstraint, Deferrable, F, Q from django.db.models.expressions import Exists, ExpressionList from django.db.models.indexes import IndexExpression from django.db.models.lookups import PostgresOperatorLookup from django.db.models.sql import Query from django.utils.deprecation import RemovedInDjango50Warning __all__ = ["ExclusionConstraint"] class ExclusionConstraintExpression(IndexExpression): template = "%(expressions)s WITH %(operator)s" class ExclusionConstraint(BaseConstraint): template = ( "CONSTRAINT %(name)s EXCLUDE USING %(index_type)s " "(%(expressions)s)%(include)s%(where)s%(deferrable)s" ) def __init__( self, *, name, expressions, index_type=None, condition=None, deferrable=None, include=None, opclasses=(), violation_error_message=None, ): if index_type and index_type.lower() not in {"gist", "spgist"}: raise ValueError( "Exclusion constraints only support GiST or SP-GiST indexes." ) if not expressions: raise ValueError( "At least one expression is required to define an exclusion " "constraint." ) if not all( isinstance(expr, (list, tuple)) and len(expr) == 2 for expr in expressions ): raise ValueError("The expressions must be a list of 2-tuples.") if not isinstance(condition, (type(None), Q)): raise ValueError("ExclusionConstraint.condition must be a Q instance.") if condition and deferrable: raise ValueError("ExclusionConstraint with conditions cannot be deferred.") if not isinstance(deferrable, (type(None), Deferrable)): raise ValueError( "ExclusionConstraint.deferrable must be a Deferrable instance." ) if not isinstance(include, (type(None), list, tuple)): raise ValueError("ExclusionConstraint.include must be a list or tuple.") if not isinstance(opclasses, (list, tuple)): raise ValueError("ExclusionConstraint.opclasses must be a list or tuple.") if opclasses and len(expressions) != len(opclasses): raise ValueError( "ExclusionConstraint.expressions and " "ExclusionConstraint.opclasses must have the same number of " "elements." ) self.expressions = expressions self.index_type = index_type or "GIST" self.condition = condition self.deferrable = deferrable self.include = tuple(include) if include else () self.opclasses = opclasses if self.opclasses: warnings.warn( "The opclasses argument is deprecated in favor of using " "django.contrib.postgres.indexes.OpClass in " "ExclusionConstraint.expressions.", category=RemovedInDjango50Warning, stacklevel=2, ) super().__init__(name=name, violation_error_message=violation_error_message) def _get_expressions(self, schema_editor, query): expressions = [] for idx, (expression, operator) in enumerate(self.expressions): if isinstance(expression, str): expression = F(expression) try: expression = OpClass(expression, self.opclasses[idx]) except IndexError: pass expression = ExclusionConstraintExpression(expression, operator=operator) expression.set_wrapper_classes(schema_editor.connection) expressions.append(expression) return ExpressionList(*expressions).resolve_expression(query) def _get_condition_sql(self, compiler, schema_editor, query): if self.condition is None: return None where = query.build_where(self.condition) sql, params = where.as_sql(compiler, schema_editor.connection) return sql % tuple(schema_editor.quote_value(p) for p in params) def constraint_sql(self, model, schema_editor): query = Query(model, alias_cols=False) compiler = query.get_compiler(connection=schema_editor.connection) expressions = self._get_expressions(schema_editor, query) table = model._meta.db_table condition = self._get_condition_sql(compiler, schema_editor, query) include = [ model._meta.get_field(field_name).column for field_name in self.include ] return Statement( self.template, table=Table(table, schema_editor.quote_name), name=schema_editor.quote_name(self.name), index_type=self.index_type, expressions=Expressions( table, expressions, compiler, schema_editor.quote_value ), where=" WHERE (%s)" % condition if condition else "", include=schema_editor._index_include_sql(model, include), deferrable=schema_editor._deferrable_constraint_sql(self.deferrable), ) def create_sql(self, model, schema_editor): self.check_supported(schema_editor) return Statement( "ALTER TABLE %(table)s ADD %(constraint)s", table=Table(model._meta.db_table, schema_editor.quote_name), constraint=self.constraint_sql(model, schema_editor), ) def remove_sql(self, model, schema_editor): return schema_editor._delete_constraint_sql( schema_editor.sql_delete_check, model, schema_editor.quote_name(self.name), ) def check_supported(self, schema_editor): if ( self.include and self.index_type.lower() == "spgist" and not schema_editor.connection.features.supports_covering_spgist_indexes ): raise NotSupportedError( "Covering exclusion constraints using an SP-GiST index " "require PostgreSQL 14+." ) def deconstruct(self): path, args, kwargs = super().deconstruct() kwargs["expressions"] = self.expressions if self.condition is not None: kwargs["condition"] = self.condition if self.index_type.lower() != "gist": kwargs["index_type"] = self.index_type if self.deferrable: kwargs["deferrable"] = self.deferrable if self.include: kwargs["include"] = self.include if self.opclasses: kwargs["opclasses"] = self.opclasses return path, args, kwargs def __eq__(self, other): if isinstance(other, self.__class__): return ( self.name == other.name and self.index_type == other.index_type and self.expressions == other.expressions and self.condition == other.condition and self.deferrable == other.deferrable and self.include == other.include and self.opclasses == other.opclasses ) return super().__eq__(other) def __repr__(self): return "<%s: index_type=%s expressions=%s name=%s%s%s%s%s>" % ( self.__class__.__qualname__, repr(self.index_type), repr(self.expressions), repr(self.name), "" if self.condition is None else " condition=%s" % self.condition, "" if self.deferrable is None else " deferrable=%r" % self.deferrable, "" if not self.include else " include=%s" % repr(self.include), "" if not self.opclasses else " opclasses=%s" % repr(self.opclasses), ) def validate(self, model, instance, exclude=None, using=DEFAULT_DB_ALIAS): queryset = model._default_manager.using(using) replacement_map = instance._get_field_value_map( meta=model._meta, exclude=exclude ) lookups = [] for idx, (expression, operator) in enumerate(self.expressions): if isinstance(expression, str): expression = F(expression) if isinstance(expression, F): if exclude and expression.name in exclude: return rhs_expression = replacement_map.get(expression.name, expression) else: rhs_expression = expression.replace_references(replacement_map) if exclude: for expr in rhs_expression.flatten(): if isinstance(expr, F) and expr.name in exclude: return # Remove OpClass because it only has sense during the constraint # creation. if isinstance(expression, OpClass): expression = expression.get_source_expressions()[0] if isinstance(rhs_expression, OpClass): rhs_expression = rhs_expression.get_source_expressions()[0] lookup = PostgresOperatorLookup(lhs=expression, rhs=rhs_expression) lookup.postgres_operator = operator lookups.append(lookup) queryset = queryset.filter(*lookups) model_class_pk = instance._get_pk_val(model._meta) if not instance._state.adding and model_class_pk is not None: queryset = queryset.exclude(pk=model_class_pk) if not self.condition: if queryset.exists(): raise ValidationError(self.get_violation_error_message()) else: if (self.condition & Exists(queryset.filter(self.condition))).check( replacement_map, using=using ): raise ValidationError(self.get_violation_error_message())
73c4fc578f5cc93324e8a2e76bc7db50b3abdda32392ac9ee82e653001687d45
from inspect import getattr_static, unwrap from django.contrib.sites.shortcuts import get_current_site from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.http import Http404, HttpResponse from django.template import TemplateDoesNotExist, loader from django.utils import feedgenerator from django.utils.encoding import iri_to_uri from django.utils.html import escape from django.utils.http import http_date from django.utils.timezone import get_default_timezone, is_naive, make_aware from django.utils.translation import get_language def add_domain(domain, url, secure=False): protocol = "https" if secure else "http" if url.startswith("//"): # Support network-path reference (see #16753) - RSS requires a protocol url = "%s:%s" % (protocol, url) elif not url.startswith(("http://", "https://", "mailto:")): url = iri_to_uri("%s://%s%s" % (protocol, domain, url)) return url class FeedDoesNotExist(ObjectDoesNotExist): pass class Feed: feed_type = feedgenerator.DefaultFeed title_template = None description_template = None language = None def __call__(self, request, *args, **kwargs): try: obj = self.get_object(request, *args, **kwargs) except ObjectDoesNotExist: raise Http404("Feed object does not exist.") feedgen = self.get_feed(obj, request) response = HttpResponse(content_type=feedgen.content_type) if hasattr(self, "item_pubdate") or hasattr(self, "item_updateddate"): # if item_pubdate or item_updateddate is defined for the feed, set # header so as ConditionalGetMiddleware is able to send 304 NOT MODIFIED response.headers["Last-Modified"] = http_date( feedgen.latest_post_date().timestamp() ) feedgen.write(response, "utf-8") return response def item_title(self, item): # Titles should be double escaped by default (see #6533) return escape(str(item)) def item_description(self, item): return str(item) def item_link(self, item): try: return item.get_absolute_url() except AttributeError: raise ImproperlyConfigured( "Give your %s class a get_absolute_url() method, or define an " "item_link() method in your Feed class." % item.__class__.__name__ ) def item_enclosures(self, item): enc_url = self._get_dynamic_attr("item_enclosure_url", item) if enc_url: enc = feedgenerator.Enclosure( url=str(enc_url), length=str(self._get_dynamic_attr("item_enclosure_length", item)), mime_type=str(self._get_dynamic_attr("item_enclosure_mime_type", item)), ) return [enc] return [] def _get_dynamic_attr(self, attname, obj, default=None): try: attr = getattr(self, attname) except AttributeError: return default if callable(attr): # Check co_argcount rather than try/excepting the function and # catching the TypeError, because something inside the function # may raise the TypeError. This technique is more accurate. func = unwrap(attr) try: code = func.__code__ except AttributeError: func = unwrap(attr.__call__) code = func.__code__ # If function doesn't have arguments and it is not a static method, # it was decorated without using @functools.wraps. if not code.co_argcount and not isinstance( getattr_static(self, func.__name__, None), staticmethod ): raise ImproperlyConfigured( f"Feed method {attname!r} decorated by {func.__name__!r} needs to " f"use @functools.wraps." ) if code.co_argcount == 2: # one argument is 'self' return attr(obj) else: return attr() return attr def feed_extra_kwargs(self, obj): """ Return an extra keyword arguments dictionary that is used when initializing the feed generator. """ return {} def item_extra_kwargs(self, item): """ Return an extra keyword arguments dictionary that is used with the `add_item` call of the feed generator. """ return {} def get_object(self, request, *args, **kwargs): return None def get_context_data(self, **kwargs): """ Return a dictionary to use as extra context if either ``self.description_template`` or ``self.item_template`` are used. Default implementation preserves the old behavior of using {'obj': item, 'site': current_site} as the context. """ return {"obj": kwargs.get("item"), "site": kwargs.get("site")} def get_feed(self, obj, request): """ Return a feedgenerator.DefaultFeed object, fully populated, for this feed. Raise FeedDoesNotExist for invalid parameters. """ current_site = get_current_site(request) link = self._get_dynamic_attr("link", obj) link = add_domain(current_site.domain, link, request.is_secure()) feed = self.feed_type( title=self._get_dynamic_attr("title", obj), subtitle=self._get_dynamic_attr("subtitle", obj), link=link, description=self._get_dynamic_attr("description", obj), language=self.language or get_language(), feed_url=add_domain( current_site.domain, self._get_dynamic_attr("feed_url", obj) or request.path, request.is_secure(), ), author_name=self._get_dynamic_attr("author_name", obj), author_link=self._get_dynamic_attr("author_link", obj), author_email=self._get_dynamic_attr("author_email", obj), categories=self._get_dynamic_attr("categories", obj), feed_copyright=self._get_dynamic_attr("feed_copyright", obj), feed_guid=self._get_dynamic_attr("feed_guid", obj), ttl=self._get_dynamic_attr("ttl", obj), **self.feed_extra_kwargs(obj), ) title_tmp = None if self.title_template is not None: try: title_tmp = loader.get_template(self.title_template) except TemplateDoesNotExist: pass description_tmp = None if self.description_template is not None: try: description_tmp = loader.get_template(self.description_template) except TemplateDoesNotExist: pass for item in self._get_dynamic_attr("items", obj): context = self.get_context_data( item=item, site=current_site, obj=obj, request=request ) if title_tmp is not None: title = title_tmp.render(context, request) else: title = self._get_dynamic_attr("item_title", item) if description_tmp is not None: description = description_tmp.render(context, request) else: description = self._get_dynamic_attr("item_description", item) link = add_domain( current_site.domain, self._get_dynamic_attr("item_link", item), request.is_secure(), ) enclosures = self._get_dynamic_attr("item_enclosures", item) author_name = self._get_dynamic_attr("item_author_name", item) if author_name is not None: author_email = self._get_dynamic_attr("item_author_email", item) author_link = self._get_dynamic_attr("item_author_link", item) else: author_email = author_link = None tz = get_default_timezone() pubdate = self._get_dynamic_attr("item_pubdate", item) if pubdate and is_naive(pubdate): pubdate = make_aware(pubdate, tz) updateddate = self._get_dynamic_attr("item_updateddate", item) if updateddate and is_naive(updateddate): updateddate = make_aware(updateddate, tz) feed.add_item( title=title, link=link, description=description, unique_id=self._get_dynamic_attr("item_guid", item, link), unique_id_is_permalink=self._get_dynamic_attr( "item_guid_is_permalink", item ), enclosures=enclosures, pubdate=pubdate, updateddate=updateddate, author_name=author_name, author_email=author_email, author_link=author_link, comments=self._get_dynamic_attr("item_comments", item), categories=self._get_dynamic_attr("item_categories", item), item_copyright=self._get_dynamic_attr("item_copyright", item), **self.item_extra_kwargs(item), ) return feed
d20852541712c548237e2e0758e2b5ffb0244a8e92e2ae98b0733e77c9926ccd
from functools import wraps from urllib.parse import urlparse from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.core.exceptions import PermissionDenied from django.shortcuts import resolve_url def user_passes_test( test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME ): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func) def _wrapper_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if (not login_scheme or login_scheme == current_scheme) and ( not login_netloc or login_netloc == current_netloc ): path = request.get_full_path() from django.contrib.auth.views import redirect_to_login return redirect_to_login(path, resolved_login_url, redirect_field_name) return _wrapper_view return decorator def login_required( function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None ): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name, ) if function: return actual_decorator(function) return actual_decorator def permission_required(perm, login_url=None, raise_exception=False): """ Decorator for views that checks whether a user has a particular permission enabled, redirecting to the log-in page if necessary. If the raise_exception parameter is given the PermissionDenied exception is raised. """ def check_perms(user): if isinstance(perm, str): perms = (perm,) else: perms = perm # First check if the user has the permission (even anon users) if user.has_perms(perms): return True # In case the 403 handler should be called raise the exception if raise_exception: raise PermissionDenied # As the last resort, show the login form return False return user_passes_test(check_perms, login_url=login_url)
4a3f49a2c4bb9b0e260acedb6dc753fd53fa5ddfced48d5f9c54d205d6e5244e
import base64 import binascii import functools import hashlib import importlib import math import warnings from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.dispatch import receiver from django.utils.crypto import ( RANDOM_STRING_CHARS, constant_time_compare, get_random_string, md5, pbkdf2, ) from django.utils.deprecation import RemovedInDjango50Warning from django.utils.module_loading import import_string from django.utils.translation import gettext_noop as _ UNUSABLE_PASSWORD_PREFIX = "!" # This will never be a valid encoded hash UNUSABLE_PASSWORD_SUFFIX_LENGTH = ( 40 # number of random chars to add after UNUSABLE_PASSWORD_PREFIX ) def is_password_usable(encoded): """ Return True if this password wasn't generated by User.set_unusable_password(), i.e. make_password(None). """ return encoded is None or not encoded.startswith(UNUSABLE_PASSWORD_PREFIX) def check_password(password, encoded, setter=None, preferred="default"): """ Return a boolean of whether the raw password matches the three part encoded digest. If setter is specified, it'll be called when you need to regenerate the password. """ if password is None or not is_password_usable(encoded): return False preferred = get_hasher(preferred) try: hasher = identify_hasher(encoded) except ValueError: # encoded is gibberish or uses a hasher that's no longer installed. return False hasher_changed = hasher.algorithm != preferred.algorithm must_update = hasher_changed or preferred.must_update(encoded) is_correct = hasher.verify(password, encoded) # If the hasher didn't change (we don't protect against enumeration if it # does) and the password should get updated, try to close the timing gap # between the work factor of the current encoded password and the default # work factor. if not is_correct and not hasher_changed and must_update: hasher.harden_runtime(password, encoded) if setter and is_correct and must_update: setter(password) return is_correct def make_password(password, salt=None, hasher="default"): """ Turn a plain-text password into a hash for database storage Same as encode() but generate a new random salt. If password is None then return a concatenation of UNUSABLE_PASSWORD_PREFIX and a random string, which disallows logins. Additional random string reduces chances of gaining access to staff or superuser accounts. See ticket #20079 for more info. """ if password is None: return UNUSABLE_PASSWORD_PREFIX + get_random_string( UNUSABLE_PASSWORD_SUFFIX_LENGTH ) if not isinstance(password, (bytes, str)): raise TypeError( "Password must be a string or bytes, got %s." % type(password).__qualname__ ) hasher = get_hasher(hasher) salt = salt or hasher.salt() return hasher.encode(password, salt) @functools.lru_cache def get_hashers(): hashers = [] for hasher_path in settings.PASSWORD_HASHERS: hasher_cls = import_string(hasher_path) hasher = hasher_cls() if not getattr(hasher, "algorithm"): raise ImproperlyConfigured( "hasher doesn't specify an algorithm name: %s" % hasher_path ) hashers.append(hasher) return hashers @functools.lru_cache def get_hashers_by_algorithm(): return {hasher.algorithm: hasher for hasher in get_hashers()} @receiver(setting_changed) def reset_hashers(*, setting, **kwargs): if setting == "PASSWORD_HASHERS": get_hashers.cache_clear() get_hashers_by_algorithm.cache_clear() def get_hasher(algorithm="default"): """ Return an instance of a loaded password hasher. If algorithm is 'default', return the default hasher. Lazily import hashers specified in the project's settings file if needed. """ if hasattr(algorithm, "algorithm"): return algorithm elif algorithm == "default": return get_hashers()[0] else: hashers = get_hashers_by_algorithm() try: return hashers[algorithm] except KeyError: raise ValueError( "Unknown password hashing algorithm '%s'. " "Did you specify it in the PASSWORD_HASHERS " "setting?" % algorithm ) def identify_hasher(encoded): """ Return an instance of a loaded password hasher. Identify hasher algorithm by examining encoded hash, and call get_hasher() to return hasher. Raise ValueError if algorithm cannot be identified, or if hasher is not loaded. """ # Ancient versions of Django created plain MD5 passwords and accepted # MD5 passwords with an empty salt. if (len(encoded) == 32 and "$" not in encoded) or ( len(encoded) == 37 and encoded.startswith("md5$$") ): algorithm = "unsalted_md5" # Ancient versions of Django accepted SHA1 passwords with an empty salt. elif len(encoded) == 46 and encoded.startswith("sha1$$"): algorithm = "unsalted_sha1" else: algorithm = encoded.split("$", 1)[0] return get_hasher(algorithm) def mask_hash(hash, show=6, char="*"): """ Return the given hash, with only the first ``show`` number shown. The rest are masked with ``char`` for security reasons. """ masked = hash[:show] masked += char * len(hash[show:]) return masked def must_update_salt(salt, expected_entropy): # Each character in the salt provides log_2(len(alphabet)) bits of entropy. return len(salt) * math.log2(len(RANDOM_STRING_CHARS)) < expected_entropy class BasePasswordHasher: """ Abstract base class for password hashers When creating your own hasher, you need to override algorithm, verify(), encode() and safe_summary(). PasswordHasher objects are immutable. """ algorithm = None library = None salt_entropy = 128 def _load_library(self): if self.library is not None: if isinstance(self.library, (tuple, list)): name, mod_path = self.library else: mod_path = self.library try: module = importlib.import_module(mod_path) except ImportError as e: raise ValueError( "Couldn't load %r algorithm library: %s" % (self.__class__.__name__, e) ) return module raise ValueError( "Hasher %r doesn't specify a library attribute" % self.__class__.__name__ ) def salt(self): """ Generate a cryptographically secure nonce salt in ASCII with an entropy of at least `salt_entropy` bits. """ # Each character in the salt provides # log_2(len(alphabet)) bits of entropy. char_count = math.ceil(self.salt_entropy / math.log2(len(RANDOM_STRING_CHARS))) return get_random_string(char_count, allowed_chars=RANDOM_STRING_CHARS) def verify(self, password, encoded): """Check if the given password is correct.""" raise NotImplementedError( "subclasses of BasePasswordHasher must provide a verify() method" ) def _check_encode_args(self, password, salt): if password is None: raise TypeError("password must be provided.") if not salt or "$" in salt: raise ValueError("salt must be provided and cannot contain $.") def encode(self, password, salt): """ Create an encoded database value. The result is normally formatted as "algorithm$salt$hash" and must be fewer than 128 characters. """ raise NotImplementedError( "subclasses of BasePasswordHasher must provide an encode() method" ) def decode(self, encoded): """ Return a decoded database value. The result is a dictionary and should contain `algorithm`, `hash`, and `salt`. Extra keys can be algorithm specific like `iterations` or `work_factor`. """ raise NotImplementedError( "subclasses of BasePasswordHasher must provide a decode() method." ) def safe_summary(self, encoded): """ Return a summary of safe values. The result is a dictionary and will be used where the password field must be displayed to construct a safe representation of the password. """ raise NotImplementedError( "subclasses of BasePasswordHasher must provide a safe_summary() method" ) def must_update(self, encoded): return False def harden_runtime(self, password, encoded): """ Bridge the runtime gap between the work factor supplied in `encoded` and the work factor suggested by this hasher. Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and `self.iterations` is 30000, this method should run password through another 10000 iterations of PBKDF2. Similar approaches should exist for any hasher that has a work factor. If not, this method should be defined as a no-op to silence the warning. """ warnings.warn( "subclasses of BasePasswordHasher should provide a harden_runtime() method" ) class PBKDF2PasswordHasher(BasePasswordHasher): """ Secure password hashing using the PBKDF2 algorithm (recommended) Configured to use PBKDF2 + HMAC + SHA256. The result is a 64 byte binary string. Iterations may be changed safely but you must rename the algorithm if you change SHA256. """ algorithm = "pbkdf2_sha256" iterations = 480000 digest = hashlib.sha256 def encode(self, password, salt, iterations=None): self._check_encode_args(password, salt) iterations = iterations or self.iterations hash = pbkdf2(password, salt, iterations, digest=self.digest) hash = base64.b64encode(hash).decode("ascii").strip() return "%s$%d$%s$%s" % (self.algorithm, iterations, salt, hash) def decode(self, encoded): algorithm, iterations, salt, hash = encoded.split("$", 3) assert algorithm == self.algorithm return { "algorithm": algorithm, "hash": hash, "iterations": int(iterations), "salt": salt, } def verify(self, password, encoded): decoded = self.decode(encoded) encoded_2 = self.encode(password, decoded["salt"], decoded["iterations"]) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("iterations"): decoded["iterations"], _("salt"): mask_hash(decoded["salt"]), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) update_salt = must_update_salt(decoded["salt"], self.salt_entropy) return (decoded["iterations"] != self.iterations) or update_salt def harden_runtime(self, password, encoded): decoded = self.decode(encoded) extra_iterations = self.iterations - decoded["iterations"] if extra_iterations > 0: self.encode(password, decoded["salt"], extra_iterations) class PBKDF2SHA1PasswordHasher(PBKDF2PasswordHasher): """ Alternate PBKDF2 hasher which uses SHA1, the default PRF recommended by PKCS #5. This is compatible with other implementations of PBKDF2, such as openssl's PKCS5_PBKDF2_HMAC_SHA1(). """ algorithm = "pbkdf2_sha1" digest = hashlib.sha1 class Argon2PasswordHasher(BasePasswordHasher): """ Secure password hashing using the argon2 algorithm. This is the winner of the Password Hashing Competition 2013-2015 (https://password-hashing.net). It requires the argon2-cffi library which depends on native C code and might cause portability issues. """ algorithm = "argon2" library = "argon2" time_cost = 2 memory_cost = 102400 parallelism = 8 def encode(self, password, salt): argon2 = self._load_library() params = self.params() data = argon2.low_level.hash_secret( password.encode(), salt.encode(), time_cost=params.time_cost, memory_cost=params.memory_cost, parallelism=params.parallelism, hash_len=params.hash_len, type=params.type, ) return self.algorithm + data.decode("ascii") def decode(self, encoded): argon2 = self._load_library() algorithm, rest = encoded.split("$", 1) assert algorithm == self.algorithm params = argon2.extract_parameters("$" + rest) variety, *_, b64salt, hash = rest.split("$") # Add padding. b64salt += "=" * (-len(b64salt) % 4) salt = base64.b64decode(b64salt).decode("latin1") return { "algorithm": algorithm, "hash": hash, "memory_cost": params.memory_cost, "parallelism": params.parallelism, "salt": salt, "time_cost": params.time_cost, "variety": variety, "version": params.version, "params": params, } def verify(self, password, encoded): argon2 = self._load_library() algorithm, rest = encoded.split("$", 1) assert algorithm == self.algorithm try: return argon2.PasswordHasher().verify("$" + rest, password) except argon2.exceptions.VerificationError: return False def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("variety"): decoded["variety"], _("version"): decoded["version"], _("memory cost"): decoded["memory_cost"], _("time cost"): decoded["time_cost"], _("parallelism"): decoded["parallelism"], _("salt"): mask_hash(decoded["salt"]), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) current_params = decoded["params"] new_params = self.params() # Set salt_len to the salt_len of the current parameters because salt # is explicitly passed to argon2. new_params.salt_len = current_params.salt_len update_salt = must_update_salt(decoded["salt"], self.salt_entropy) return (current_params != new_params) or update_salt def harden_runtime(self, password, encoded): # The runtime for Argon2 is too complicated to implement a sensible # hardening algorithm. pass def params(self): argon2 = self._load_library() # salt_len is a noop, because we provide our own salt. return argon2.Parameters( type=argon2.low_level.Type.ID, version=argon2.low_level.ARGON2_VERSION, salt_len=argon2.DEFAULT_RANDOM_SALT_LENGTH, hash_len=argon2.DEFAULT_HASH_LENGTH, time_cost=self.time_cost, memory_cost=self.memory_cost, parallelism=self.parallelism, ) class BCryptSHA256PasswordHasher(BasePasswordHasher): """ Secure password hashing using the bcrypt algorithm (recommended) This is considered by many to be the most secure algorithm but you must first install the bcrypt library. Please be warned that this library depends on native C code and might cause portability issues. """ algorithm = "bcrypt_sha256" digest = hashlib.sha256 library = ("bcrypt", "bcrypt") rounds = 12 def salt(self): bcrypt = self._load_library() return bcrypt.gensalt(self.rounds) def encode(self, password, salt): bcrypt = self._load_library() password = password.encode() # Hash the password prior to using bcrypt to prevent password # truncation as described in #20138. if self.digest is not None: # Use binascii.hexlify() because a hex encoded bytestring is str. password = binascii.hexlify(self.digest(password).digest()) data = bcrypt.hashpw(password, salt) return "%s$%s" % (self.algorithm, data.decode("ascii")) def decode(self, encoded): algorithm, empty, algostr, work_factor, data = encoded.split("$", 4) assert algorithm == self.algorithm return { "algorithm": algorithm, "algostr": algostr, "checksum": data[22:], "salt": data[:22], "work_factor": int(work_factor), } def verify(self, password, encoded): algorithm, data = encoded.split("$", 1) assert algorithm == self.algorithm encoded_2 = self.encode(password, data.encode("ascii")) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("work factor"): decoded["work_factor"], _("salt"): mask_hash(decoded["salt"]), _("checksum"): mask_hash(decoded["checksum"]), } def must_update(self, encoded): decoded = self.decode(encoded) return decoded["work_factor"] != self.rounds def harden_runtime(self, password, encoded): _, data = encoded.split("$", 1) salt = data[:29] # Length of the salt in bcrypt. rounds = data.split("$")[2] # work factor is logarithmic, adding one doubles the load. diff = 2 ** (self.rounds - int(rounds)) - 1 while diff > 0: self.encode(password, salt.encode("ascii")) diff -= 1 class BCryptPasswordHasher(BCryptSHA256PasswordHasher): """ Secure password hashing using the bcrypt algorithm This is considered by many to be the most secure algorithm but you must first install the bcrypt library. Please be warned that this library depends on native C code and might cause portability issues. This hasher does not first hash the password which means it is subject to bcrypt's 72 bytes password truncation. Most use cases should prefer the BCryptSHA256PasswordHasher. """ algorithm = "bcrypt" digest = None class ScryptPasswordHasher(BasePasswordHasher): """ Secure password hashing using the Scrypt algorithm. """ algorithm = "scrypt" block_size = 8 maxmem = 0 parallelism = 1 work_factor = 2**14 def encode(self, password, salt, n=None, r=None, p=None): self._check_encode_args(password, salt) n = n or self.work_factor r = r or self.block_size p = p or self.parallelism hash_ = hashlib.scrypt( password.encode(), salt=salt.encode(), n=n, r=r, p=p, maxmem=self.maxmem, dklen=64, ) hash_ = base64.b64encode(hash_).decode("ascii").strip() return "%s$%d$%s$%d$%d$%s" % (self.algorithm, n, salt, r, p, hash_) def decode(self, encoded): algorithm, work_factor, salt, block_size, parallelism, hash_ = encoded.split( "$", 6 ) assert algorithm == self.algorithm return { "algorithm": algorithm, "work_factor": int(work_factor), "salt": salt, "block_size": int(block_size), "parallelism": int(parallelism), "hash": hash_, } def verify(self, password, encoded): decoded = self.decode(encoded) encoded_2 = self.encode( password, decoded["salt"], decoded["work_factor"], decoded["block_size"], decoded["parallelism"], ) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("work factor"): decoded["work_factor"], _("block size"): decoded["block_size"], _("parallelism"): decoded["parallelism"], _("salt"): mask_hash(decoded["salt"]), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) return ( decoded["work_factor"] != self.work_factor or decoded["block_size"] != self.block_size or decoded["parallelism"] != self.parallelism ) def harden_runtime(self, password, encoded): # The runtime for Scrypt is too complicated to implement a sensible # hardening algorithm. pass class SHA1PasswordHasher(BasePasswordHasher): """ The SHA1 password hashing algorithm (not recommended) """ algorithm = "sha1" def encode(self, password, salt): self._check_encode_args(password, salt) hash = hashlib.sha1((salt + password).encode()).hexdigest() return "%s$%s$%s" % (self.algorithm, salt, hash) def decode(self, encoded): algorithm, salt, hash = encoded.split("$", 2) assert algorithm == self.algorithm return { "algorithm": algorithm, "hash": hash, "salt": salt, } def verify(self, password, encoded): decoded = self.decode(encoded) encoded_2 = self.encode(password, decoded["salt"]) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("salt"): mask_hash(decoded["salt"], show=2), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) return must_update_salt(decoded["salt"], self.salt_entropy) def harden_runtime(self, password, encoded): pass class MD5PasswordHasher(BasePasswordHasher): """ The Salted MD5 password hashing algorithm (not recommended) """ algorithm = "md5" def encode(self, password, salt): self._check_encode_args(password, salt) hash = md5((salt + password).encode()).hexdigest() return "%s$%s$%s" % (self.algorithm, salt, hash) def decode(self, encoded): algorithm, salt, hash = encoded.split("$", 2) assert algorithm == self.algorithm return { "algorithm": algorithm, "hash": hash, "salt": salt, } def verify(self, password, encoded): decoded = self.decode(encoded) encoded_2 = self.encode(password, decoded["salt"]) return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("salt"): mask_hash(decoded["salt"], show=2), _("hash"): mask_hash(decoded["hash"]), } def must_update(self, encoded): decoded = self.decode(encoded) return must_update_salt(decoded["salt"], self.salt_entropy) def harden_runtime(self, password, encoded): pass class UnsaltedSHA1PasswordHasher(BasePasswordHasher): """ Very insecure algorithm that you should *never* use; store SHA1 hashes with an empty salt. This class is implemented because Django used to accept such password hashes. Some older Django installs still have these values lingering around so we need to handle and upgrade them properly. """ algorithm = "unsalted_sha1" def salt(self): return "" def encode(self, password, salt): if salt != "": raise ValueError("salt must be empty.") hash = hashlib.sha1(password.encode()).hexdigest() return "sha1$$%s" % hash def decode(self, encoded): assert encoded.startswith("sha1$$") return { "algorithm": self.algorithm, "hash": encoded[6:], "salt": None, } def verify(self, password, encoded): encoded_2 = self.encode(password, "") return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("hash"): mask_hash(decoded["hash"]), } def harden_runtime(self, password, encoded): pass class UnsaltedMD5PasswordHasher(BasePasswordHasher): """ Incredibly insecure algorithm that you should *never* use; stores unsalted MD5 hashes without the algorithm prefix, also accepts MD5 hashes with an empty salt. This class is implemented because Django used to store passwords this way and to accept such password hashes. Some older Django installs still have these values lingering around so we need to handle and upgrade them properly. """ algorithm = "unsalted_md5" def salt(self): return "" def encode(self, password, salt): if salt != "": raise ValueError("salt must be empty.") return md5(password.encode()).hexdigest() def decode(self, encoded): return { "algorithm": self.algorithm, "hash": encoded, "salt": None, } def verify(self, password, encoded): if len(encoded) == 37 and encoded.startswith("md5$$"): encoded = encoded[5:] encoded_2 = self.encode(password, "") return constant_time_compare(encoded, encoded_2) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("hash"): mask_hash(decoded["hash"], show=3), } def harden_runtime(self, password, encoded): pass # RemovedInDjango50Warning. class CryptPasswordHasher(BasePasswordHasher): """ Password hashing using UNIX crypt (not recommended) The crypt module is not supported on all platforms. """ algorithm = "crypt" library = "crypt" def __init__(self, *args, **kwargs): warnings.warn( "django.contrib.auth.hashers.CryptPasswordHasher is deprecated.", RemovedInDjango50Warning, stacklevel=2, ) super().__init__(*args, **kwargs) def salt(self): return get_random_string(2) def encode(self, password, salt): crypt = self._load_library() if len(salt) != 2: raise ValueError("salt must be of length 2.") hash = crypt.crypt(password, salt) if hash is None: # A platform like OpenBSD with a dummy crypt module. raise TypeError("hash must be provided.") # we don't need to store the salt, but Django used to do this return "%s$%s$%s" % (self.algorithm, "", hash) def decode(self, encoded): algorithm, salt, hash = encoded.split("$", 2) assert algorithm == self.algorithm return { "algorithm": algorithm, "hash": hash, "salt": salt, } def verify(self, password, encoded): crypt = self._load_library() decoded = self.decode(encoded) data = crypt.crypt(password, decoded["hash"]) return constant_time_compare(decoded["hash"], data) def safe_summary(self, encoded): decoded = self.decode(encoded) return { _("algorithm"): decoded["algorithm"], _("salt"): decoded["salt"], _("hash"): mask_hash(decoded["hash"], show=3), } def harden_runtime(self, password, encoded): pass
ba96baa2bdc4bcd0bc67c43f971747cdac30834ac87aef061f13d46a4d80716b
from django.core.exceptions import FieldDoesNotExist from django.db import IntegrityError, connection, migrations, models, transaction from django.db.migrations.migration import Migration from django.db.migrations.operations.fields import FieldOperation from django.db.migrations.state import ModelState, ProjectState from django.db.models.functions import Abs from django.db.transaction import atomic from django.test import SimpleTestCase, override_settings, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import FoodManager, FoodQuerySet, UnicodeModel from .test_base import OperationTestBase class Mixin: pass class OperationTests(OperationTestBase): """ Tests running the operations and making sure they do what they say they do. Each test looks at their state changing, and then their database operation - both forwards and backwards. """ def test_create_model(self): """ Tests the CreateModel operation. Most other tests use this operation as part of setup, so check failures here first. """ operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], ) self.assertEqual(operation.describe(), "Create model Pony") self.assertEqual(operation.migration_name_fragment, "pony") # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony") self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2) # Test the database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["fields", "name"]) # And default manager not in set operation = migrations.CreateModel( "Foo", fields=[], managers=[("objects", models.Manager())] ) definition = operation.deconstruct() self.assertNotIn("managers", definition[2]) def test_create_model_with_duplicate_field_name(self): with self.assertRaisesMessage( ValueError, "Found duplicate value pink in CreateModel fields argument." ): migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.TextField()), ("pink", models.IntegerField(default=1)), ], ) def test_create_model_with_duplicate_base(self): message = "Found duplicate value test_crmo.pony in CreateModel bases argument." with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( "test_crmo.Pony", "test_crmo.Pony", ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( "test_crmo.Pony", "test_crmo.pony", ), ) message = ( "Found duplicate value migrations.unicodemodel in CreateModel bases " "argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, UnicodeModel, ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, "migrations.unicodemodel", ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, "migrations.UnicodeModel", ), ) message = ( "Found duplicate value <class 'django.db.models.base.Model'> in " "CreateModel bases argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( models.Model, models.Model, ), ) message = ( "Found duplicate value <class 'migrations.test_operations.Mixin'> in " "CreateModel bases argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( Mixin, Mixin, ), ) def test_create_model_with_duplicate_manager_name(self): with self.assertRaisesMessage( ValueError, "Found duplicate value objects in CreateModel managers argument.", ): migrations.CreateModel( "Pony", fields=[], managers=[ ("objects", models.Manager()), ("objects", models.Manager()), ], ) def test_create_model_with_unique_after(self): """ Tests the CreateModel operation directly followed by an AlterUniqueTogether (bug #22844 - sqlite remake issues) """ operation1 = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], ) operation2 = migrations.CreateModel( "Rider", [ ("id", models.AutoField(primary_key=True)), ("number", models.IntegerField(default=1)), ("pony", models.ForeignKey("test_crmoua.Pony", models.CASCADE)), ], ) operation3 = migrations.AlterUniqueTogether( "Rider", [ ("number", "pony"), ], ) # Test the database alteration project_state = ProjectState() self.assertTableNotExists("test_crmoua_pony") self.assertTableNotExists("test_crmoua_rider") with connection.schema_editor() as editor: new_state = project_state.clone() operation1.state_forwards("test_crmoua", new_state) operation1.database_forwards( "test_crmoua", editor, project_state, new_state ) project_state, new_state = new_state, new_state.clone() operation2.state_forwards("test_crmoua", new_state) operation2.database_forwards( "test_crmoua", editor, project_state, new_state ) project_state, new_state = new_state, new_state.clone() operation3.state_forwards("test_crmoua", new_state) operation3.database_forwards( "test_crmoua", editor, project_state, new_state ) self.assertTableExists("test_crmoua_pony") self.assertTableExists("test_crmoua_rider") def test_create_model_m2m(self): """ Test the creation of a model with a ManyToMany field and the auto-created "through" model. """ project_state = self.set_up_test_model("test_crmomm") operation = migrations.CreateModel( "Stable", [ ("id", models.AutoField(primary_key=True)), ("ponies", models.ManyToManyField("Pony", related_name="stables")), ], ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_crmomm", new_state) # Test the database alteration self.assertTableNotExists("test_crmomm_stable_ponies") with connection.schema_editor() as editor: operation.database_forwards("test_crmomm", editor, project_state, new_state) self.assertTableExists("test_crmomm_stable") self.assertTableExists("test_crmomm_stable_ponies") self.assertColumnNotExists("test_crmomm_stable", "ponies") # Make sure the M2M field actually works with atomic(): Pony = new_state.apps.get_model("test_crmomm", "Pony") Stable = new_state.apps.get_model("test_crmomm", "Stable") stable = Stable.objects.create() p1 = Pony.objects.create(pink=False, weight=4.55) p2 = Pony.objects.create(pink=True, weight=5.43) stable.ponies.add(p1, p2) self.assertEqual(stable.ponies.count(), 2) stable.ponies.all().delete() # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crmomm", editor, new_state, project_state ) self.assertTableNotExists("test_crmomm_stable") self.assertTableNotExists("test_crmomm_stable_ponies") @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys") def test_create_fk_models_to_pk_field_db_collation(self): """Creation of models with a FK to a PK with db_collation.""" collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") app_label = "test_cfkmtopkfdbc" operations = [ migrations.CreateModel( "Pony", [ ( "id", models.CharField( primary_key=True, max_length=10, db_collation=collation, ), ), ], ) ] project_state = self.apply_operations(app_label, ProjectState(), operations) # ForeignKey. new_state = project_state.clone() operation = migrations.CreateModel( "Rider", [ ("id", models.AutoField(primary_key=True)), ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # OneToOneField. new_state = project_state.clone() operation = migrations.CreateModel( "ShetlandPony", [ ( "pony", models.OneToOneField("Pony", models.CASCADE, primary_key=True), ), ("cuteness", models.IntegerField(default=1)), ], ) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_shetlandpony", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) def test_create_model_inheritance(self): """ Tests the CreateModel operation on a multi-table inheritance setup. """ project_state = self.set_up_test_model("test_crmoih") # Test the state alteration operation = migrations.CreateModel( "ShetlandPony", [ ( "pony_ptr", models.OneToOneField( "test_crmoih.Pony", models.CASCADE, auto_created=True, primary_key=True, to_field="id", serialize=False, ), ), ("cuteness", models.IntegerField(default=1)), ], ) new_state = project_state.clone() operation.state_forwards("test_crmoih", new_state) self.assertIn(("test_crmoih", "shetlandpony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crmoih_shetlandpony") with connection.schema_editor() as editor: operation.database_forwards("test_crmoih", editor, project_state, new_state) self.assertTableExists("test_crmoih_shetlandpony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crmoih", editor, new_state, project_state ) self.assertTableNotExists("test_crmoih_shetlandpony") def test_create_proxy_model(self): """ CreateModel ignores proxy models. """ project_state = self.set_up_test_model("test_crprmo") # Test the state alteration operation = migrations.CreateModel( "ProxyPony", [], options={"proxy": True}, bases=("test_crprmo.Pony",), ) self.assertEqual(operation.describe(), "Create proxy model ProxyPony") new_state = project_state.clone() operation.state_forwards("test_crprmo", new_state) self.assertIn(("test_crprmo", "proxypony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crprmo", editor, project_state, new_state) self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crprmo", editor, new_state, project_state ) self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["bases", "fields", "name", "options"]) def test_create_unmanaged_model(self): """ CreateModel ignores unmanaged models. """ project_state = self.set_up_test_model("test_crummo") # Test the state alteration operation = migrations.CreateModel( "UnmanagedPony", [], options={"proxy": True}, bases=("test_crummo.Pony",), ) self.assertEqual(operation.describe(), "Create proxy model UnmanagedPony") new_state = project_state.clone() operation.state_forwards("test_crummo", new_state) self.assertIn(("test_crummo", "unmanagedpony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crummo", editor, project_state, new_state) self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crummo", editor, new_state, project_state ) self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") @skipUnlessDBFeature("supports_table_check_constraints") def test_create_model_with_constraint(self): where = models.Q(pink__gt=2) check_constraint = models.CheckConstraint( check=where, name="test_constraint_pony_pink_gt_2" ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ], options={"constraints": [check_constraint]}, ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) # Test database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") with connection.cursor() as cursor: with self.assertRaises(IntegrityError): cursor.execute("INSERT INTO test_crmo_pony (id, pink) VALUES (1, 1)") # Test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(definition[2]["options"]["constraints"], [check_constraint]) @skipUnlessDBFeature("supports_table_check_constraints") def test_create_model_with_boolean_expression_in_check_constraint(self): app_label = "test_crmobechc" rawsql_constraint = models.CheckConstraint( check=models.expressions.RawSQL( "price < %s", (1000,), output_field=models.BooleanField() ), name=f"{app_label}_price_lt_1000_raw", ) wrapper_constraint = models.CheckConstraint( check=models.expressions.ExpressionWrapper( models.Q(price__gt=500) | models.Q(price__lt=500), output_field=models.BooleanField(), ), name=f"{app_label}_price_neq_500_wrap", ) operation = migrations.CreateModel( "Product", [ ("id", models.AutoField(primary_key=True)), ("price", models.IntegerField(null=True)), ], options={"constraints": [rawsql_constraint, wrapper_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Add table. self.assertTableNotExists(app_label) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertTableExists(f"{app_label}_product") insert_sql = f"INSERT INTO {app_label}_product (id, price) VALUES (%d, %d)" with connection.cursor() as cursor: with self.assertRaises(IntegrityError): cursor.execute(insert_sql % (1, 1000)) cursor.execute(insert_sql % (1, 999)) with self.assertRaises(IntegrityError): cursor.execute(insert_sql % (2, 500)) cursor.execute(insert_sql % (2, 499)) def test_create_model_with_partial_unique_constraint(self): partial_unique_constraint = models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ("weight", models.FloatField()), ], options={"constraints": [partial_unique_constraint]}, ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) # Test database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") # Test constraint works Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [partial_unique_constraint] ) def test_create_model_with_deferred_unique_constraint(self): deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferrable_pink_constraint", deferrable=models.Deferrable.DEFERRED, ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ], options={"constraints": [deferred_unique_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) self.assertTableNotExists("test_crmo_pony") # Create table. with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1) obj.pink = 3 obj.save() else: Pony.objects.create(pink=1) # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [deferred_unique_constraint], ) @skipUnlessDBFeature("supports_covering_indexes") def test_create_model_with_covering_unique_constraint(self): covering_unique_constraint = models.UniqueConstraint( fields=["pink"], include=["weight"], name="test_constraint_pony_pink_covering_weight", ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ("weight", models.FloatField()), ], options={"constraints": [covering_unique_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) self.assertTableNotExists("test_crmo_pony") # Create table. with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1, weight=4.0) with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=7.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [covering_unique_constraint], ) def test_create_model_managers(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_cmoma") # Test the state alteration operation = migrations.CreateModel( "Food", fields=[ ("id", models.AutoField(primary_key=True)), ], managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) self.assertEqual(operation.describe(), "Create model Food") new_state = project_state.clone() operation.state_forwards("test_cmoma", new_state) self.assertIn(("test_cmoma", "food"), new_state.models) managers = new_state.models["test_cmoma", "food"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) def test_delete_model(self): """ Tests the DeleteModel operation. """ project_state = self.set_up_test_model("test_dlmo") # Test the state alteration operation = migrations.DeleteModel("Pony") self.assertEqual(operation.describe(), "Delete model Pony") self.assertEqual(operation.migration_name_fragment, "delete_pony") new_state = project_state.clone() operation.state_forwards("test_dlmo", new_state) self.assertNotIn(("test_dlmo", "pony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_dlmo", editor, project_state, new_state) self.assertTableNotExists("test_dlmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_dlmo", editor, new_state, project_state) self.assertTableExists("test_dlmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "DeleteModel") self.assertEqual(definition[1], []) self.assertEqual(list(definition[2]), ["name"]) def test_delete_proxy_model(self): """ Tests the DeleteModel operation ignores proxy models. """ project_state = self.set_up_test_model("test_dlprmo", proxy_model=True) # Test the state alteration operation = migrations.DeleteModel("ProxyPony") new_state = project_state.clone() operation.state_forwards("test_dlprmo", new_state) self.assertIn(("test_dlprmo", "proxypony"), project_state.models) self.assertNotIn(("test_dlprmo", "proxypony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") with connection.schema_editor() as editor: operation.database_forwards("test_dlprmo", editor, project_state, new_state) self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dlprmo", editor, new_state, project_state ) self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") def test_delete_mti_model(self): project_state = self.set_up_test_model("test_dlmtimo", mti_model=True) # Test the state alteration operation = migrations.DeleteModel("ShetlandPony") new_state = project_state.clone() operation.state_forwards("test_dlmtimo", new_state) self.assertIn(("test_dlmtimo", "shetlandpony"), project_state.models) self.assertNotIn(("test_dlmtimo", "shetlandpony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlmtimo_pony") self.assertTableExists("test_dlmtimo_shetlandpony") self.assertColumnExists("test_dlmtimo_shetlandpony", "pony_ptr_id") with connection.schema_editor() as editor: operation.database_forwards( "test_dlmtimo", editor, project_state, new_state ) self.assertTableExists("test_dlmtimo_pony") self.assertTableNotExists("test_dlmtimo_shetlandpony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dlmtimo", editor, new_state, project_state ) self.assertTableExists("test_dlmtimo_pony") self.assertTableExists("test_dlmtimo_shetlandpony") self.assertColumnExists("test_dlmtimo_shetlandpony", "pony_ptr_id") def test_rename_model(self): """ Tests the RenameModel operation. """ project_state = self.set_up_test_model("test_rnmo", related_model=True) # Test the state alteration operation = migrations.RenameModel("Pony", "Horse") self.assertEqual(operation.describe(), "Rename model Pony to Horse") self.assertEqual(operation.migration_name_fragment, "rename_pony_horse") # Test initial state and database self.assertIn(("test_rnmo", "pony"), project_state.models) self.assertNotIn(("test_rnmo", "horse"), project_state.models) self.assertTableExists("test_rnmo_pony") self.assertTableNotExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # Migrate forwards new_state = project_state.clone() atomic_rename = connection.features.supports_atomic_references_rename new_state = self.apply_operations( "test_rnmo", new_state, [operation], atomic=atomic_rename ) # Test new state and database self.assertNotIn(("test_rnmo", "pony"), new_state.models) self.assertIn(("test_rnmo", "horse"), new_state.models) # RenameModel also repoints all incoming FKs and M2Ms self.assertEqual( new_state.models["test_rnmo", "rider"].fields["pony"].remote_field.model, "test_rnmo.Horse", ) self.assertTableNotExists("test_rnmo_pony") self.assertTableExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # Migrate backwards original_state = self.unapply_operations( "test_rnmo", project_state, [operation], atomic=atomic_rename ) # Test original state and database self.assertIn(("test_rnmo", "pony"), original_state.models) self.assertNotIn(("test_rnmo", "horse"), original_state.models) self.assertEqual( original_state.models["test_rnmo", "rider"] .fields["pony"] .remote_field.model, "Pony", ) self.assertTableExists("test_rnmo_pony") self.assertTableNotExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RenameModel") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"old_name": "Pony", "new_name": "Horse"}) def test_rename_model_state_forwards(self): """ RenameModel operations shouldn't trigger the caching of rendered apps on state without prior apps. """ state = ProjectState() state.add_model(ModelState("migrations", "Foo", [])) operation = migrations.RenameModel("Foo", "Bar") operation.state_forwards("migrations", state) self.assertNotIn("apps", state.__dict__) self.assertNotIn(("migrations", "foo"), state.models) self.assertIn(("migrations", "bar"), state.models) # Now with apps cached. apps = state.apps operation = migrations.RenameModel("Bar", "Foo") operation.state_forwards("migrations", state) self.assertIs(state.apps, apps) self.assertNotIn(("migrations", "bar"), state.models) self.assertIn(("migrations", "foo"), state.models) def test_rename_model_with_self_referential_fk(self): """ Tests the RenameModel operation on model with self referential FK. """ project_state = self.set_up_test_model("test_rmwsrf", related_model=True) # Test the state alteration operation = migrations.RenameModel("Rider", "HorseRider") self.assertEqual(operation.describe(), "Rename model Rider to HorseRider") new_state = project_state.clone() operation.state_forwards("test_rmwsrf", new_state) self.assertNotIn(("test_rmwsrf", "rider"), new_state.models) self.assertIn(("test_rmwsrf", "horserider"), new_state.models) # Remember, RenameModel also repoints all incoming FKs and M2Ms self.assertEqual( "self", new_state.models["test_rmwsrf", "horserider"] .fields["friend"] .remote_field.model, ) HorseRider = new_state.apps.get_model("test_rmwsrf", "horserider") self.assertIs( HorseRider._meta.get_field("horserider").remote_field.model, HorseRider ) # Test the database alteration self.assertTableExists("test_rmwsrf_rider") self.assertTableNotExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKNotExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id") ) atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_forwards("test_rmwsrf", editor, project_state, new_state) self.assertTableNotExists("test_rmwsrf_rider") self.assertTableExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKNotExists( "test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKExists( "test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_horserider", "id"), ) # And test reversal with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_backwards( "test_rmwsrf", editor, new_state, project_state ) self.assertTableExists("test_rmwsrf_rider") self.assertTableNotExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKNotExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id") ) def test_rename_model_with_superclass_fk(self): """ Tests the RenameModel operation on a model which has a superclass that has a foreign key. """ project_state = self.set_up_test_model( "test_rmwsc", related_model=True, mti_model=True ) # Test the state alteration operation = migrations.RenameModel("ShetlandPony", "LittleHorse") self.assertEqual( operation.describe(), "Rename model ShetlandPony to LittleHorse" ) new_state = project_state.clone() operation.state_forwards("test_rmwsc", new_state) self.assertNotIn(("test_rmwsc", "shetlandpony"), new_state.models) self.assertIn(("test_rmwsc", "littlehorse"), new_state.models) # RenameModel shouldn't repoint the superclass's relations, only local ones self.assertEqual( project_state.models["test_rmwsc", "rider"] .fields["pony"] .remote_field.model, new_state.models["test_rmwsc", "rider"].fields["pony"].remote_field.model, ) # Before running the migration we have a table for Shetland Pony, not # Little Horse. self.assertTableExists("test_rmwsc_shetlandpony") self.assertTableNotExists("test_rmwsc_littlehorse") if connection.features.supports_foreign_keys: # and the foreign key on rider points to pony, not shetland pony self.assertFKExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id") ) self.assertFKNotExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_shetlandpony", "id") ) with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: operation.database_forwards("test_rmwsc", editor, project_state, new_state) # Now we have a little horse table, not shetland pony self.assertTableNotExists("test_rmwsc_shetlandpony") self.assertTableExists("test_rmwsc_littlehorse") if connection.features.supports_foreign_keys: # but the Foreign keys still point at pony, not little horse self.assertFKExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id") ) self.assertFKNotExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_littlehorse", "id") ) def test_rename_model_with_self_referential_m2m(self): app_label = "test_rename_model_with_self_referential_m2m" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "ReflexivePony", fields=[ ("id", models.AutoField(primary_key=True)), ("ponies", models.ManyToManyField("self")), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("ReflexivePony", "ReflexivePony2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "ReflexivePony2") pony = Pony.objects.create() pony.ponies.add(pony) def test_rename_model_with_m2m(self): app_label = "test_rename_model_with_m2m" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("Pony", "Pony2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony2") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) self.assertEqual(Pony.objects.count(), 2) self.assertEqual(Rider.objects.count(), 2) self.assertEqual( Pony._meta.get_field("riders").remote_field.through.objects.count(), 2 ) def test_rename_model_with_db_table_noop(self): app_label = "test_rmwdbtn" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], options={"db_table": "rider"}, ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey("%s.Rider" % app_label, models.CASCADE), ), ], ), ], ) new_state = project_state.clone() operation = migrations.RenameModel("Rider", "Runner") operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( app_label, editor, new_state, project_state ) def test_rename_m2m_target_model(self): app_label = "test_rename_m2m_target_model" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("Rider", "Rider2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider2") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) self.assertEqual(Pony.objects.count(), 2) self.assertEqual(Rider.objects.count(), 2) self.assertEqual( Pony._meta.get_field("riders").remote_field.through.objects.count(), 2 ) def test_rename_m2m_through_model(self): app_label = "test_rename_through" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "test_rename_through.Rider", models.CASCADE ), ), ( "pony", models.ForeignKey( "test_rename_through.Pony", models.CASCADE ), ), ], ), migrations.AddField( "Pony", "riders", models.ManyToManyField( "test_rename_through.Rider", through="test_rename_through.PonyRider", ), ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") PonyRider = project_state.apps.get_model(app_label, "PonyRider") pony = Pony.objects.create() rider = Rider.objects.create() PonyRider.objects.create(pony=pony, rider=rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("PonyRider", "PonyRider2"), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") PonyRider = project_state.apps.get_model(app_label, "PonyRider2") pony = Pony.objects.first() rider = Rider.objects.create() PonyRider.objects.create(pony=pony, rider=rider) self.assertEqual(Pony.objects.count(), 1) self.assertEqual(Rider.objects.count(), 2) self.assertEqual(PonyRider.objects.count(), 2) self.assertEqual(pony.riders.count(), 2) def test_rename_m2m_model_after_rename_field(self): """RenameModel renames a many-to-many column after a RenameField.""" app_label = "test_rename_multiple" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=20)), ], ), migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey( "test_rename_multiple.Pony", models.CASCADE ), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), migrations.RenameField( model_name="pony", old_name="name", new_name="fancy_name" ), migrations.RenameModel(old_name="Rider", new_name="Jockey"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony") Jockey = project_state.apps.get_model(app_label, "Jockey") PonyRider = project_state.apps.get_model(app_label, "PonyRider") # No "no such column" error means the column was renamed correctly. pony = Pony.objects.create(fancy_name="a good name") jockey = Jockey.objects.create(pony=pony) ponyrider = PonyRider.objects.create() ponyrider.riders.add(jockey) def test_add_field(self): """ Tests the AddField operation. """ # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=5), ) self.assertEqual(operation.describe(), "Add field height to Pony") self.assertEqual(operation.migration_name_fragment, "pony_height") project_state, new_state = self.make_test_state("test_adfl", operation) self.assertEqual(len(new_state.models["test_adfl", "pony"].fields), 4) field = new_state.models["test_adfl", "pony"].fields["height"] self.assertEqual(field.default, 5) # Test the database alteration self.assertColumnNotExists("test_adfl_pony", "height") with connection.schema_editor() as editor: operation.database_forwards("test_adfl", editor, project_state, new_state) self.assertColumnExists("test_adfl_pony", "height") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_adfl", editor, new_state, project_state) self.assertColumnNotExists("test_adfl_pony", "height") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddField") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"]) def test_add_charfield(self): """ Tests the AddField operation on TextField. """ project_state = self.set_up_test_model("test_adchfl") Pony = project_state.apps.get_model("test_adchfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adchfl", project_state, [ migrations.AddField( "Pony", "text", models.CharField(max_length=10, default="some text"), ), migrations.AddField( "Pony", "empty", models.CharField(max_length=10, default=""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.CharField(max_length=10, default="42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.CharField(max_length=10, default='"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adchfl", "Pony") pony = Pony.objects.get(pk=pony.pk) self.assertEqual(pony.text, "some text") self.assertEqual(pony.empty, "") self.assertEqual(pony.digits, "42") self.assertEqual(pony.quotes, '"\'"') def test_add_textfield(self): """ Tests the AddField operation on TextField. """ project_state = self.set_up_test_model("test_adtxtfl") Pony = project_state.apps.get_model("test_adtxtfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adtxtfl", project_state, [ migrations.AddField( "Pony", "text", models.TextField(default="some text"), ), migrations.AddField( "Pony", "empty", models.TextField(default=""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.TextField(default="42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.TextField(default='"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adtxtfl", "Pony") pony = Pony.objects.get(pk=pony.pk) self.assertEqual(pony.text, "some text") self.assertEqual(pony.empty, "") self.assertEqual(pony.digits, "42") self.assertEqual(pony.quotes, '"\'"') def test_add_binaryfield(self): """ Tests the AddField operation on TextField/BinaryField. """ project_state = self.set_up_test_model("test_adbinfl") Pony = project_state.apps.get_model("test_adbinfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adbinfl", project_state, [ migrations.AddField( "Pony", "blob", models.BinaryField(default=b"some text"), ), migrations.AddField( "Pony", "empty", models.BinaryField(default=b""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.BinaryField(default=b"42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.BinaryField(default=b'"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adbinfl", "Pony") pony = Pony.objects.get(pk=pony.pk) # SQLite returns buffer/memoryview, cast to bytes for checking. self.assertEqual(bytes(pony.blob), b"some text") self.assertEqual(bytes(pony.empty), b"") self.assertEqual(bytes(pony.digits), b"42") self.assertEqual(bytes(pony.quotes), b'"\'"') def test_column_name_quoting(self): """ Column names that are SQL keywords shouldn't cause problems when used in migrations (#22168). """ project_state = self.set_up_test_model("test_regr22168") operation = migrations.AddField( "Pony", "order", models.IntegerField(default=0), ) new_state = project_state.clone() operation.state_forwards("test_regr22168", new_state) with connection.schema_editor() as editor: operation.database_forwards( "test_regr22168", editor, project_state, new_state ) self.assertColumnExists("test_regr22168_pony", "order") def test_add_field_preserve_default(self): """ Tests the AddField operation's state alteration when preserve_default = False. """ project_state = self.set_up_test_model("test_adflpd") # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=4), preserve_default=False, ) new_state = project_state.clone() operation.state_forwards("test_adflpd", new_state) self.assertEqual(len(new_state.models["test_adflpd", "pony"].fields), 4) field = new_state.models["test_adflpd", "pony"].fields["height"] self.assertEqual(field.default, models.NOT_PROVIDED) # Test the database alteration project_state.apps.get_model("test_adflpd", "pony").objects.create( weight=4, ) self.assertColumnNotExists("test_adflpd_pony", "height") with connection.schema_editor() as editor: operation.database_forwards("test_adflpd", editor, project_state, new_state) self.assertColumnExists("test_adflpd_pony", "height") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddField") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["field", "model_name", "name", "preserve_default"] ) def test_add_field_m2m(self): """ Tests the AddField operation with a ManyToManyField. """ project_state = self.set_up_test_model("test_adflmm", second_model=True) # Test the state alteration operation = migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies") ) new_state = project_state.clone() operation.state_forwards("test_adflmm", new_state) self.assertEqual(len(new_state.models["test_adflmm", "pony"].fields), 4) # Test the database alteration self.assertTableNotExists("test_adflmm_pony_stables") with connection.schema_editor() as editor: operation.database_forwards("test_adflmm", editor, project_state, new_state) self.assertTableExists("test_adflmm_pony_stables") self.assertColumnNotExists("test_adflmm_pony", "stables") # Make sure the M2M field actually works with atomic(): Pony = new_state.apps.get_model("test_adflmm", "Pony") p = Pony.objects.create(pink=False, weight=4.55) p.stables.create() self.assertEqual(p.stables.count(), 1) p.stables.all().delete() # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_adflmm", editor, new_state, project_state ) self.assertTableNotExists("test_adflmm_pony_stables") def test_alter_field_m2m(self): project_state = self.set_up_test_model("test_alflmm", second_model=True) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") self.assertFalse(Pony._meta.get_field("stables").blank) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AlterField( "Pony", "stables", models.ManyToManyField( to="Stable", related_name="ponies", blank=True ), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") self.assertTrue(Pony._meta.get_field("stables").blank) def test_repoint_field_m2m(self): project_state = self.set_up_test_model( "test_alflmm", second_model=True, third_model=True ) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AddField( "Pony", "places", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AlterField( "Pony", "places", models.ManyToManyField(to="Van", related_name="ponies"), ) ], ) # Ensure the new field actually works Pony = project_state.apps.get_model("test_alflmm", "Pony") p = Pony.objects.create(pink=False, weight=4.55) p.places.create() self.assertEqual(p.places.count(), 1) p.places.all().delete() def test_remove_field_m2m(self): project_state = self.set_up_test_model("test_rmflmm", second_model=True) project_state = self.apply_operations( "test_rmflmm", project_state, operations=[ migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) self.assertTableExists("test_rmflmm_pony_stables") with_field_state = project_state.clone() operations = [migrations.RemoveField("Pony", "stables")] project_state = self.apply_operations( "test_rmflmm", project_state, operations=operations ) self.assertTableNotExists("test_rmflmm_pony_stables") # And test reversal self.unapply_operations("test_rmflmm", with_field_state, operations=operations) self.assertTableExists("test_rmflmm_pony_stables") def test_remove_field_m2m_with_through(self): project_state = self.set_up_test_model("test_rmflmmwt", second_model=True) self.assertTableNotExists("test_rmflmmwt_ponystables") project_state = self.apply_operations( "test_rmflmmwt", project_state, operations=[ migrations.CreateModel( "PonyStables", fields=[ ( "pony", models.ForeignKey("test_rmflmmwt.Pony", models.CASCADE), ), ( "stable", models.ForeignKey("test_rmflmmwt.Stable", models.CASCADE), ), ], ), migrations.AddField( "Pony", "stables", models.ManyToManyField( "Stable", related_name="ponies", through="test_rmflmmwt.PonyStables", ), ), ], ) self.assertTableExists("test_rmflmmwt_ponystables") operations = [ migrations.RemoveField("Pony", "stables"), migrations.DeleteModel("PonyStables"), ] self.apply_operations("test_rmflmmwt", project_state, operations=operations) def test_remove_field(self): """ Tests the RemoveField operation. """ project_state = self.set_up_test_model("test_rmfl") # Test the state alteration operation = migrations.RemoveField("Pony", "pink") self.assertEqual(operation.describe(), "Remove field pink from Pony") self.assertEqual(operation.migration_name_fragment, "remove_pony_pink") new_state = project_state.clone() operation.state_forwards("test_rmfl", new_state) self.assertEqual(len(new_state.models["test_rmfl", "pony"].fields), 2) # Test the database alteration self.assertColumnExists("test_rmfl_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_rmfl", editor, project_state, new_state) self.assertColumnNotExists("test_rmfl_pony", "pink") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_rmfl", editor, new_state, project_state) self.assertColumnExists("test_rmfl_pony", "pink") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveField") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": "pink"}) def test_remove_fk(self): """ Tests the RemoveField operation on a foreign key. """ project_state = self.set_up_test_model("test_rfk", related_model=True) self.assertColumnExists("test_rfk_rider", "pony_id") operation = migrations.RemoveField("Rider", "pony") new_state = project_state.clone() operation.state_forwards("test_rfk", new_state) with connection.schema_editor() as editor: operation.database_forwards("test_rfk", editor, project_state, new_state) self.assertColumnNotExists("test_rfk_rider", "pony_id") with connection.schema_editor() as editor: operation.database_backwards("test_rfk", editor, new_state, project_state) self.assertColumnExists("test_rfk_rider", "pony_id") def test_alter_model_table(self): """ Tests the AlterModelTable operation. """ project_state = self.set_up_test_model("test_almota") # Test the state alteration operation = migrations.AlterModelTable("Pony", "test_almota_pony_2") self.assertEqual( operation.describe(), "Rename table for Pony to test_almota_pony_2" ) self.assertEqual(operation.migration_name_fragment, "alter_pony_table") new_state = project_state.clone() operation.state_forwards("test_almota", new_state) self.assertEqual( new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony_2", ) # Test the database alteration self.assertTableExists("test_almota_pony") self.assertTableNotExists("test_almota_pony_2") with connection.schema_editor() as editor: operation.database_forwards("test_almota", editor, project_state, new_state) self.assertTableNotExists("test_almota_pony") self.assertTableExists("test_almota_pony_2") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_almota", editor, new_state, project_state ) self.assertTableExists("test_almota_pony") self.assertTableNotExists("test_almota_pony_2") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelTable") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"name": "Pony", "table": "test_almota_pony_2"}) def test_alter_model_table_none(self): """ Tests the AlterModelTable operation if the table name is set to None. """ operation = migrations.AlterModelTable("Pony", None) self.assertEqual(operation.describe(), "Rename table for Pony to (default)") def test_alter_model_table_noop(self): """ Tests the AlterModelTable operation if the table name is not changed. """ project_state = self.set_up_test_model("test_almota") # Test the state alteration operation = migrations.AlterModelTable("Pony", "test_almota_pony") new_state = project_state.clone() operation.state_forwards("test_almota", new_state) self.assertEqual( new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony", ) # Test the database alteration self.assertTableExists("test_almota_pony") with connection.schema_editor() as editor: operation.database_forwards("test_almota", editor, project_state, new_state) self.assertTableExists("test_almota_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_almota", editor, new_state, project_state ) self.assertTableExists("test_almota_pony") def test_alter_model_table_m2m(self): """ AlterModelTable should rename auto-generated M2M tables. """ app_label = "test_talflmltlm2m" pony_db_table = "pony_foo" project_state = self.set_up_test_model( app_label, second_model=True, db_table=pony_db_table ) # Add the M2M field first_state = project_state.clone() operation = migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable") ) operation.state_forwards(app_label, first_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, first_state) original_m2m_table = "%s_%s" % (pony_db_table, "stables") new_m2m_table = "%s_%s" % (app_label, "pony_stables") self.assertTableExists(original_m2m_table) self.assertTableNotExists(new_m2m_table) # Rename the Pony db_table which should also rename the m2m table. second_state = first_state.clone() operation = migrations.AlterModelTable(name="pony", table=None) operation.state_forwards(app_label, second_state) atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_forwards(app_label, editor, first_state, second_state) self.assertTableExists(new_m2m_table) self.assertTableNotExists(original_m2m_table) # And test reversal with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_backwards(app_label, editor, second_state, first_state) self.assertTableExists(original_m2m_table) self.assertTableNotExists(new_m2m_table) def test_alter_field(self): """ Tests the AlterField operation. """ project_state = self.set_up_test_model("test_alfl") # Test the state alteration operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) self.assertEqual(operation.describe(), "Alter field pink on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_pink") new_state = project_state.clone() operation.state_forwards("test_alfl", new_state) self.assertIs( project_state.models["test_alfl", "pony"].fields["pink"].null, False ) self.assertIs(new_state.models["test_alfl", "pony"].fields["pink"].null, True) # Test the database alteration self.assertColumnNotNull("test_alfl_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_alfl", editor, project_state, new_state) self.assertColumnNull("test_alfl_pony", "pink") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_alfl", editor, new_state, project_state) self.assertColumnNotNull("test_alfl_pony", "pink") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterField") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"]) def test_alter_field_add_db_column_noop(self): """ AlterField operation is a noop when adding only a db_column and the column name is not changed. """ app_label = "test_afadbn" project_state = self.set_up_test_model(app_label, related_model=True) pony_table = "%s_pony" % app_label new_state = project_state.clone() operation = migrations.AlterField( "Pony", "weight", models.FloatField(db_column="weight") ) operation.state_forwards(app_label, new_state) self.assertIsNone( project_state.models[app_label, "pony"].fields["weight"].db_column, ) self.assertEqual( new_state.models[app_label, "pony"].fields["weight"].db_column, "weight", ) self.assertColumnExists(pony_table, "weight") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnExists(pony_table, "weight") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( app_label, editor, new_state, project_state ) self.assertColumnExists(pony_table, "weight") rider_table = "%s_rider" % app_label new_state = project_state.clone() operation = migrations.AlterField( "Rider", "pony", models.ForeignKey("Pony", models.CASCADE, db_column="pony_id"), ) operation.state_forwards(app_label, new_state) self.assertIsNone( project_state.models[app_label, "rider"].fields["pony"].db_column, ) self.assertIs( new_state.models[app_label, "rider"].fields["pony"].db_column, "pony_id", ) self.assertColumnExists(rider_table, "pony_id") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnExists(rider_table, "pony_id") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, new_state, project_state) self.assertColumnExists(rider_table, "pony_id") def test_alter_field_pk(self): """ The AlterField operation on primary keys (things like PostgreSQL's SERIAL weirdness). """ project_state = self.set_up_test_model("test_alflpk") # Test the state alteration operation = migrations.AlterField( "Pony", "id", models.IntegerField(primary_key=True) ) new_state = project_state.clone() operation.state_forwards("test_alflpk", new_state) self.assertIsInstance( project_state.models["test_alflpk", "pony"].fields["id"], models.AutoField, ) self.assertIsInstance( new_state.models["test_alflpk", "pony"].fields["id"], models.IntegerField, ) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_alflpk", editor, project_state, new_state) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflpk", editor, new_state, project_state ) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_pk_fk(self): """ Tests the AlterField operation on primary keys changes any FKs pointing to it. """ project_state = self.set_up_test_model("test_alflpkfk", related_model=True) project_state = self.apply_operations( "test_alflpkfk", project_state, [ migrations.CreateModel( "Stable", fields=[ ("ponies", models.ManyToManyField("Pony")), ], ), migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable"), ), ], ) # Test the state alteration operation = migrations.AlterField( "Pony", "id", models.FloatField(primary_key=True) ) new_state = project_state.clone() operation.state_forwards("test_alflpkfk", new_state) self.assertIsInstance( project_state.models["test_alflpkfk", "pony"].fields["id"], models.AutoField, ) self.assertIsInstance( new_state.models["test_alflpkfk", "pony"].fields["id"], models.FloatField, ) def assertIdTypeEqualsFkType(): with connection.cursor() as cursor: id_type, id_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_pony" ) if c.name == "id" ][0] fk_type, fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_rider" ) if c.name == "pony_id" ][0] m2m_fk_type, m2m_fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_pony_stables", ) if c.name == "pony_id" ][0] remote_m2m_fk_type, remote_m2m_fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_stable_ponies", ) if c.name == "pony_id" ][0] self.assertEqual(id_type, fk_type) self.assertEqual(id_type, m2m_fk_type) self.assertEqual(id_type, remote_m2m_fk_type) self.assertEqual(id_null, fk_null) self.assertEqual(id_null, m2m_fk_null) self.assertEqual(id_null, remote_m2m_fk_null) assertIdTypeEqualsFkType() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alflpkfk", editor, project_state, new_state ) assertIdTypeEqualsFkType() if connection.features.supports_foreign_keys: self.assertFKExists( "test_alflpkfk_pony_stables", ["pony_id"], ("test_alflpkfk_pony", "id"), ) self.assertFKExists( "test_alflpkfk_stable_ponies", ["pony_id"], ("test_alflpkfk_pony", "id"), ) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflpkfk", editor, new_state, project_state ) assertIdTypeEqualsFkType() if connection.features.supports_foreign_keys: self.assertFKExists( "test_alflpkfk_pony_stables", ["pony_id"], ("test_alflpkfk_pony", "id"), ) self.assertFKExists( "test_alflpkfk_stable_ponies", ["pony_id"], ("test_alflpkfk_pony", "id"), ) @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys") def test_alter_field_pk_fk_db_collation(self): """ AlterField operation of db_collation on primary keys changes any FKs pointing to it. """ collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") app_label = "test_alflpkfkdbc" project_state = self.apply_operations( app_label, ProjectState(), [ migrations.CreateModel( "Pony", [ ("id", models.CharField(primary_key=True, max_length=10)), ], ), migrations.CreateModel( "Rider", [ ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ), migrations.CreateModel( "Stable", [ ("ponies", models.ManyToManyField("Pony")), ], ), ], ) # State alteration. operation = migrations.AlterField( "Pony", "id", models.CharField( primary_key=True, max_length=10, db_collation=collation, ), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Database alteration. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_pony", "id", collation) self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation) self.assertColumnCollation(f"{app_label}_stable_ponies", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) def test_alter_field_pk_mti_fk(self): app_label = "test_alflpkmtifk" project_state = self.set_up_test_model(app_label, mti_model=True) project_state = self.apply_operations( app_label, project_state, [ migrations.CreateModel( "ShetlandRider", fields=[ ( "pony", models.ForeignKey( f"{app_label}.ShetlandPony", models.CASCADE ), ), ], ), ], ) operation = migrations.AlterField( "Pony", "id", models.BigAutoField(primary_key=True), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertIsInstance( new_state.models[app_label, "pony"].fields["id"], models.BigAutoField, ) def _get_column_id_type(cursor, table, column): return [ c.type_code for c in connection.introspection.get_table_description( cursor, f"{app_label}_{table}", ) if c.name == column ][0] def assertIdTypeEqualsMTIFkType(): with connection.cursor() as cursor: parent_id_type = _get_column_id_type(cursor, "pony", "id") child_id_type = _get_column_id_type( cursor, "shetlandpony", "pony_ptr_id" ) mti_id_type = _get_column_id_type(cursor, "shetlandrider", "pony_id") self.assertEqual(parent_id_type, child_id_type) self.assertEqual(parent_id_type, mti_id_type) assertIdTypeEqualsMTIFkType() # Alter primary key. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_shetlandrider", ["pony_id"], (f"{app_label}_shetlandpony", "pony_ptr_id"), ) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_shetlandrider", ["pony_id"], (f"{app_label}_shetlandpony", "pony_ptr_id"), ) def test_alter_field_pk_mti_and_fk_to_base(self): app_label = "test_alflpkmtiftb" project_state = self.set_up_test_model( app_label, mti_model=True, related_model=True, ) operation = migrations.AlterField( "Pony", "id", models.BigAutoField(primary_key=True), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertIsInstance( new_state.models[app_label, "pony"].fields["id"], models.BigAutoField, ) def _get_column_id_type(cursor, table, column): return [ c.type_code for c in connection.introspection.get_table_description( cursor, f"{app_label}_{table}", ) if c.name == column ][0] def assertIdTypeEqualsMTIFkType(): with connection.cursor() as cursor: parent_id_type = _get_column_id_type(cursor, "pony", "id") fk_id_type = _get_column_id_type(cursor, "rider", "pony_id") child_id_type = _get_column_id_type( cursor, "shetlandpony", "pony_ptr_id" ) self.assertEqual(parent_id_type, child_id_type) self.assertEqual(parent_id_type, fk_id_type) assertIdTypeEqualsMTIFkType() # Alter primary key. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_rider", ["pony_id"], (f"{app_label}_pony", "id"), ) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_rider", ["pony_id"], (f"{app_label}_pony", "id"), ) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_reloads_state_on_fk_with_to_field_target_type_change(self): app_label = "test_alflrsfkwtflttc" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("code", models.IntegerField(unique=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="code" ), ), ], ), ], ) operation = migrations.AlterField( "Rider", "code", models.CharField(max_length=100, unique=True), ) self.apply_operations(app_label, project_state, operations=[operation]) id_type, id_null = [ (c.type_code, c.null_ok) for c in self.get_table_description("%s_rider" % app_label) if c.name == "code" ][0] fk_type, fk_null = [ (c.type_code, c.null_ok) for c in self.get_table_description("%s_pony" % app_label) if c.name == "rider_id" ][0] self.assertEqual(id_type, fk_type) self.assertEqual(id_null, fk_null) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_reloads_state_fk_with_to_field_related_name_target_type_change( self, ): app_label = "test_alflrsfkwtflrnttc" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("code", models.PositiveIntegerField(unique=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="code", related_name="+", ), ), ], ), ], ) operation = migrations.AlterField( "Rider", "code", models.CharField(max_length=100, unique=True), ) self.apply_operations(app_label, project_state, operations=[operation]) def test_alter_field_reloads_state_on_fk_target_changes(self): """ If AlterField doesn't reload state appropriately, the second AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_alter_field_reloads_state_on_fk_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey("%s.Rider" % app_label, models.CASCADE), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey("%s.Pony" % app_label, models.CASCADE), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.AlterField( "Rider", "id", models.CharField(primary_key=True, max_length=99) ), migrations.AlterField( "Pony", "id", models.CharField(primary_key=True, max_length=99) ), ], ) def test_alter_field_reloads_state_on_fk_with_to_field_target_changes(self): """ If AlterField doesn't reload state appropriately, the second AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_alter_field_reloads_state_on_fk_with_to_field_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ("slug", models.CharField(unique=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="slug" ), ), ("slug", models.CharField(unique=True, max_length=100)), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey( "%s.Pony" % app_label, models.CASCADE, to_field="slug" ), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.AlterField( "Rider", "slug", models.CharField(unique=True, max_length=99) ), migrations.AlterField( "Pony", "slug", models.CharField(unique=True, max_length=99) ), ], ) def test_rename_field_reloads_state_on_fk_target_changes(self): """ If RenameField doesn't reload state appropriately, the AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_rename_field_reloads_state_on_fk_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey("%s.Rider" % app_label, models.CASCADE), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey("%s.Pony" % app_label, models.CASCADE), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameField("Rider", "id", "id2"), migrations.AlterField( "Pony", "id", models.CharField(primary_key=True, max_length=99) ), ], atomic=connection.features.supports_atomic_references_rename, ) def test_rename_field(self): """ Tests the RenameField operation. """ project_state = self.set_up_test_model( "test_rnfl", unique_together=True, index_together=True ) # Test the state alteration operation = migrations.RenameField("Pony", "pink", "blue") self.assertEqual(operation.describe(), "Rename field pink on Pony to blue") self.assertEqual(operation.migration_name_fragment, "rename_pink_pony_blue") new_state = project_state.clone() operation.state_forwards("test_rnfl", new_state) self.assertIn("blue", new_state.models["test_rnfl", "pony"].fields) self.assertNotIn("pink", new_state.models["test_rnfl", "pony"].fields) # Make sure the unique_together has the renamed column too self.assertIn( "blue", new_state.models["test_rnfl", "pony"].options["unique_together"][0] ) self.assertNotIn( "pink", new_state.models["test_rnfl", "pony"].options["unique_together"][0] ) # Make sure the index_together has the renamed column too self.assertIn( "blue", new_state.models["test_rnfl", "pony"].options["index_together"][0] ) self.assertNotIn( "pink", new_state.models["test_rnfl", "pony"].options["index_together"][0] ) # Test the database alteration self.assertColumnExists("test_rnfl_pony", "pink") self.assertColumnNotExists("test_rnfl_pony", "blue") with connection.schema_editor() as editor: operation.database_forwards("test_rnfl", editor, project_state, new_state) self.assertColumnExists("test_rnfl_pony", "blue") self.assertColumnNotExists("test_rnfl_pony", "pink") # Ensure the unique constraint has been ported over with connection.cursor() as cursor: cursor.execute("INSERT INTO test_rnfl_pony (blue, weight) VALUES (1, 1)") with self.assertRaises(IntegrityError): with atomic(): cursor.execute( "INSERT INTO test_rnfl_pony (blue, weight) VALUES (1, 1)" ) cursor.execute("DELETE FROM test_rnfl_pony") # Ensure the index constraint has been ported over self.assertIndexExists("test_rnfl_pony", ["weight", "blue"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_rnfl", editor, new_state, project_state) self.assertColumnExists("test_rnfl_pony", "pink") self.assertColumnNotExists("test_rnfl_pony", "blue") # Ensure the index constraint has been reset self.assertIndexExists("test_rnfl_pony", ["weight", "pink"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RenameField") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "old_name": "pink", "new_name": "blue"}, ) def test_rename_field_with_db_column(self): project_state = self.apply_operations( "test_rfwdbc", ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField(db_column="db_field")), ( "fk_field", models.ForeignKey( "Pony", models.CASCADE, db_column="db_fk_field", ), ), ], ), ], ) new_state = project_state.clone() operation = migrations.RenameField("Pony", "field", "renamed_field") operation.state_forwards("test_rfwdbc", new_state) self.assertIn("renamed_field", new_state.models["test_rfwdbc", "pony"].fields) self.assertNotIn("field", new_state.models["test_rfwdbc", "pony"].fields) self.assertColumnExists("test_rfwdbc_pony", "db_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards( "test_rfwdbc", editor, project_state, new_state ) self.assertColumnExists("test_rfwdbc_pony", "db_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( "test_rfwdbc", editor, new_state, project_state ) self.assertColumnExists("test_rfwdbc_pony", "db_field") new_state = project_state.clone() operation = migrations.RenameField("Pony", "fk_field", "renamed_fk_field") operation.state_forwards("test_rfwdbc", new_state) self.assertIn( "renamed_fk_field", new_state.models["test_rfwdbc", "pony"].fields ) self.assertNotIn("fk_field", new_state.models["test_rfwdbc", "pony"].fields) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards( "test_rfwdbc", editor, project_state, new_state ) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( "test_rfwdbc", editor, new_state, project_state ) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") def test_rename_field_case(self): project_state = self.apply_operations( "test_rfmx", ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField()), ], ), ], ) new_state = project_state.clone() operation = migrations.RenameField("Pony", "field", "FiElD") operation.state_forwards("test_rfmx", new_state) self.assertIn("FiElD", new_state.models["test_rfmx", "pony"].fields) self.assertColumnExists("test_rfmx_pony", "field") with connection.schema_editor() as editor: operation.database_forwards("test_rfmx", editor, project_state, new_state) self.assertColumnExists( "test_rfmx_pony", connection.introspection.identifier_converter("FiElD"), ) with connection.schema_editor() as editor: operation.database_backwards("test_rfmx", editor, new_state, project_state) self.assertColumnExists("test_rfmx_pony", "field") def test_rename_missing_field(self): state = ProjectState() state.add_model(ModelState("app", "model", [])) with self.assertRaisesMessage( FieldDoesNotExist, "app.model has no field named 'field'" ): migrations.RenameField("model", "field", "new_field").state_forwards( "app", state ) def test_rename_referenced_field_state_forward(self): state = ProjectState() state.add_model( ModelState( "app", "Model", [ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField(unique=True)), ], ) ) state.add_model( ModelState( "app", "OtherModel", [ ("id", models.AutoField(primary_key=True)), ( "fk", models.ForeignKey("Model", models.CASCADE, to_field="field"), ), ( "fo", models.ForeignObject( "Model", models.CASCADE, from_fields=("fk",), to_fields=("field",), ), ), ], ) ) operation = migrations.RenameField("Model", "field", "renamed") new_state = state.clone() operation.state_forwards("app", new_state) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].remote_field.field_name, "renamed", ) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].from_fields, ["self"] ) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].to_fields, ("renamed",) ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].from_fields, ("fk",) ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",) ) operation = migrations.RenameField("OtherModel", "fk", "renamed_fk") new_state = state.clone() operation.state_forwards("app", new_state) self.assertEqual( new_state.models["app", "othermodel"] .fields["renamed_fk"] .remote_field.field_name, "renamed", ) self.assertEqual( new_state.models["app", "othermodel"].fields["renamed_fk"].from_fields, ("self",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["renamed_fk"].to_fields, ("renamed",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].from_fields, ("renamed_fk",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",) ) def test_alter_unique_together(self): """ Tests the AlterUniqueTogether operation. """ project_state = self.set_up_test_model("test_alunto") # Test the state alteration operation = migrations.AlterUniqueTogether("Pony", [("pink", "weight")]) self.assertEqual( operation.describe(), "Alter unique_together for Pony (1 constraint(s))" ) self.assertEqual( operation.migration_name_fragment, "alter_pony_unique_together", ) new_state = project_state.clone() operation.state_forwards("test_alunto", new_state) self.assertEqual( len( project_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 0, ) self.assertEqual( len( new_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 1, ) # Make sure we can insert duplicate rows with connection.cursor() as cursor: cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("DELETE FROM test_alunto_pony") # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alunto", editor, project_state, new_state ) cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") with self.assertRaises(IntegrityError): with atomic(): cursor.execute( "INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)" ) cursor.execute("DELETE FROM test_alunto_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alunto", editor, new_state, project_state ) cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("DELETE FROM test_alunto_pony") # Test flat unique_together operation = migrations.AlterUniqueTogether("Pony", ("pink", "weight")) operation.state_forwards("test_alunto", new_state) self.assertEqual( len( new_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 1, ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterUniqueTogether") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "unique_together": {("pink", "weight")}} ) def test_alter_unique_together_remove(self): operation = migrations.AlterUniqueTogether("Pony", None) self.assertEqual( operation.describe(), "Alter unique_together for Pony (0 constraint(s))" ) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_unique_together_on_pk_field(self): app_label = "test_rutopkf" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[("id", models.AutoField(primary_key=True))], options={"unique_together": {("id",)}}, ), ], ) table_name = f"{app_label}_pony" pk_constraint_name = f"{table_name}_pkey" unique_together_constraint_name = f"{table_name}_id_fb61f881_uniq" self.assertConstraintExists(table_name, pk_constraint_name, value=False) self.assertConstraintExists( table_name, unique_together_constraint_name, value=False ) new_state = project_state.clone() operation = migrations.AlterUniqueTogether("Pony", set()) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertConstraintExists(table_name, pk_constraint_name, value=False) self.assertConstraintNotExists(table_name, unique_together_constraint_name) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_remove_unique_together_on_unique_field(self): app_label = "test_rutouf" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=30, unique=True)), ], options={"unique_together": {("name",)}}, ), ], ) table_name = f"{app_label}_pony" unique_constraint_name = f"{table_name}_name_key" unique_together_constraint_name = f"{table_name}_name_694f3b9f_uniq" self.assertConstraintExists(table_name, unique_constraint_name, value=False) self.assertConstraintExists( table_name, unique_together_constraint_name, value=False ) new_state = project_state.clone() operation = migrations.AlterUniqueTogether("Pony", set()) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertConstraintExists(table_name, unique_constraint_name, value=False) self.assertConstraintNotExists(table_name, unique_together_constraint_name) def test_add_index(self): """ Test the AddIndex operation. """ project_state = self.set_up_test_model("test_adin") msg = ( "Indexes passed to AddIndex operations require a name argument. " "<Index: fields=['pink']> doesn't have one." ) with self.assertRaisesMessage(ValueError, msg): migrations.AddIndex("Pony", models.Index(fields=["pink"])) index = models.Index(fields=["pink"], name="test_adin_pony_pink_idx") operation = migrations.AddIndex("Pony", index) self.assertEqual( operation.describe(), "Create index test_adin_pony_pink_idx on field(s) pink of model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_adin_pony_pink_idx", ) new_state = project_state.clone() operation.state_forwards("test_adin", new_state) # Test the database alteration self.assertEqual( len(new_state.models["test_adin", "pony"].options["indexes"]), 1 ) self.assertIndexNotExists("test_adin_pony", ["pink"]) with connection.schema_editor() as editor: operation.database_forwards("test_adin", editor, project_state, new_state) self.assertIndexExists("test_adin_pony", ["pink"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_adin", editor, new_state, project_state) self.assertIndexNotExists("test_adin_pony", ["pink"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "index": index}) def test_remove_index(self): """ Test the RemoveIndex operation. """ project_state = self.set_up_test_model("test_rmin", multicol_index=True) self.assertTableExists("test_rmin_pony") self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) operation = migrations.RemoveIndex("Pony", "pony_test_idx") self.assertEqual(operation.describe(), "Remove index pony_test_idx from Pony") self.assertEqual( operation.migration_name_fragment, "remove_pony_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards("test_rmin", new_state) # Test the state alteration self.assertEqual( len(new_state.models["test_rmin", "pony"].options["indexes"]), 0 ) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_rmin", editor, project_state, new_state) self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_rmin", editor, new_state, project_state) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": "pony_test_idx"}) # Also test a field dropped with index - sqlite remake issue operations = [ migrations.RemoveIndex("Pony", "pony_test_idx"), migrations.RemoveField("Pony", "pink"), ] self.assertColumnExists("test_rmin_pony", "pink") self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # Test database alteration new_state = project_state.clone() self.apply_operations("test_rmin", new_state, operations=operations) self.assertColumnNotExists("test_rmin_pony", "pink") self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"]) # And test reversal self.unapply_operations("test_rmin", project_state, operations=operations) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) def test_rename_index(self): app_label = "test_rnin" project_state = self.set_up_test_model(app_label, index=True) table_name = app_label + "_pony" self.assertIndexNameExists(table_name, "pony_pink_idx") self.assertIndexNameNotExists(table_name, "new_pony_test_idx") operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_name="pony_pink_idx" ) self.assertEqual( operation.describe(), "Rename index pony_pink_idx on Pony to new_pony_test_idx", ) self.assertEqual( operation.migration_name_fragment, "rename_pony_pink_idx_new_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Rename index. expected_queries = 1 if connection.features.can_rename_index else 2 with connection.schema_editor() as editor, self.assertNumQueries( expected_queries ): operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, "pony_pink_idx") self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reversal. with connection.schema_editor() as editor, self.assertNumQueries( expected_queries ): operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "pony_pink_idx") self.assertIndexNameNotExists(table_name, "new_pony_test_idx") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RenameIndex") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "old_name": "pony_pink_idx", "new_name": "new_pony_test_idx", }, ) def test_rename_index_arguments(self): msg = "RenameIndex.old_name and old_fields are mutually exclusive." with self.assertRaisesMessage(ValueError, msg): migrations.RenameIndex( "Pony", new_name="new_idx_name", old_name="old_idx_name", old_fields=("weight", "pink"), ) msg = "RenameIndex requires one of old_name and old_fields arguments to be set." with self.assertRaisesMessage(ValueError, msg): migrations.RenameIndex("Pony", new_name="new_idx_name") def test_rename_index_unnamed_index(self): app_label = "test_rninui" project_state = self.set_up_test_model(app_label, index_together=True) table_name = app_label + "_pony" self.assertIndexNameNotExists(table_name, "new_pony_test_idx") operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink") ) self.assertEqual( operation.describe(), "Rename unnamed index for ('weight', 'pink') on Pony to new_pony_test_idx", ) self.assertEqual( operation.migration_name_fragment, "rename_pony_weight_pink_new_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Rename index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reverse is a no-op. with connection.schema_editor() as editor, self.assertNumQueries(0): operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reapply, RenameIndex operation is a noop when the old and new name # match. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RenameIndex") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "new_name": "new_pony_test_idx", "old_fields": ("weight", "pink"), }, ) def test_rename_index_unknown_unnamed_index(self): app_label = "test_rninuui" project_state = self.set_up_test_model(app_label) operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink") ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) msg = "Found wrong number (0) of indexes for test_rninuui_pony(weight, pink)." with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): operation.database_forwards(app_label, editor, project_state, new_state) def test_add_index_state_forwards(self): project_state = self.set_up_test_model("test_adinsf") index = models.Index(fields=["pink"], name="test_adinsf_pony_pink_idx") old_model = project_state.apps.get_model("test_adinsf", "Pony") new_state = project_state.clone() operation = migrations.AddIndex("Pony", index) operation.state_forwards("test_adinsf", new_state) new_model = new_state.apps.get_model("test_adinsf", "Pony") self.assertIsNot(old_model, new_model) def test_remove_index_state_forwards(self): project_state = self.set_up_test_model("test_rminsf") index = models.Index(fields=["pink"], name="test_rminsf_pony_pink_idx") migrations.AddIndex("Pony", index).state_forwards("test_rminsf", project_state) old_model = project_state.apps.get_model("test_rminsf", "Pony") new_state = project_state.clone() operation = migrations.RemoveIndex("Pony", "test_rminsf_pony_pink_idx") operation.state_forwards("test_rminsf", new_state) new_model = new_state.apps.get_model("test_rminsf", "Pony") self.assertIsNot(old_model, new_model) def test_rename_index_state_forwards(self): app_label = "test_rnidsf" project_state = self.set_up_test_model(app_label, index=True) old_model = project_state.apps.get_model(app_label, "Pony") new_state = project_state.clone() operation = migrations.RenameIndex( "Pony", new_name="new_pony_pink_idx", old_name="pony_pink_idx" ) operation.state_forwards(app_label, new_state) new_model = new_state.apps.get_model(app_label, "Pony") self.assertIsNot(old_model, new_model) self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx") def test_rename_index_state_forwards_unnamed_index(self): app_label = "test_rnidsfui" project_state = self.set_up_test_model(app_label, index_together=True) old_model = project_state.apps.get_model(app_label, "Pony") new_state = project_state.clone() operation = migrations.RenameIndex( "Pony", new_name="new_pony_pink_idx", old_fields=("weight", "pink") ) operation.state_forwards(app_label, new_state) new_model = new_state.apps.get_model(app_label, "Pony") self.assertIsNot(old_model, new_model) self.assertEqual(new_model._meta.index_together, tuple()) self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx") @skipUnlessDBFeature("supports_expression_indexes") def test_add_func_index(self): app_label = "test_addfuncin" index_name = f"{app_label}_pony_abs_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) index = models.Index(Abs("weight"), name=index_name) operation = migrations.AddIndex("Pony", index) self.assertEqual( operation.describe(), "Create index test_addfuncin_pony_abs_idx on Abs(F(weight)) on model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_addfuncin_pony_abs_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 1) self.assertIndexNameNotExists(table_name, index_name) # Add index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, index_name) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameNotExists(table_name, index_name) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "index": index}) @skipUnlessDBFeature("supports_expression_indexes") def test_remove_func_index(self): app_label = "test_rmfuncin" index_name = f"{app_label}_pony_abs_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, indexes=[ models.Index(Abs("weight"), name=index_name), ], ) self.assertTableExists(table_name) self.assertIndexNameExists(table_name, index_name) operation = migrations.RemoveIndex("Pony", index_name) self.assertEqual( operation.describe(), "Remove index test_rmfuncin_pony_abs_idx from Pony", ) self.assertEqual( operation.migration_name_fragment, "remove_pony_test_rmfuncin_pony_abs_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 0) # Remove index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, index_name) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, index_name) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": index_name}) @skipUnlessDBFeature("supports_expression_indexes") def test_alter_field_with_func_index(self): app_label = "test_alfuncin" index_name = f"{app_label}_pony_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, indexes=[models.Index(Abs("pink"), name=index_name)], ) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, index_name) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, index_name) def test_alter_field_with_index(self): """ Test AlterField operation with an index to ensure indexes created via Meta.indexes don't get dropped with sqlite3 remake. """ project_state = self.set_up_test_model("test_alflin", index=True) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards("test_alflin", new_state) # Test the database alteration self.assertColumnNotNull("test_alflin_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_alflin", editor, project_state, new_state) # Index hasn't been dropped self.assertIndexExists("test_alflin_pony", ["pink"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflin", editor, new_state, project_state ) # Ensure the index is still there self.assertIndexExists("test_alflin_pony", ["pink"]) def test_alter_index_together(self): """ Tests the AlterIndexTogether operation. """ project_state = self.set_up_test_model("test_alinto") # Test the state alteration operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")]) self.assertEqual( operation.describe(), "Alter index_together for Pony (1 constraint(s))" ) self.assertEqual( operation.migration_name_fragment, "alter_pony_index_together", ) new_state = project_state.clone() operation.state_forwards("test_alinto", new_state) self.assertEqual( len( project_state.models["test_alinto", "pony"].options.get( "index_together", set() ) ), 0, ) self.assertEqual( len( new_state.models["test_alinto", "pony"].options.get( "index_together", set() ) ), 1, ) # Make sure there's no matching index self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"]) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_alinto", editor, project_state, new_state) self.assertIndexExists("test_alinto_pony", ["pink", "weight"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alinto", editor, new_state, project_state ) self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterIndexTogether") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "index_together": {("pink", "weight")}} ) def test_alter_index_together_remove(self): operation = migrations.AlterIndexTogether("Pony", None) self.assertEqual( operation.describe(), "Alter index_together for Pony (0 constraint(s))" ) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_alter_index_together_remove_with_unique_together(self): app_label = "test_alintoremove_wunto" table_name = "%s_pony" % app_label project_state = self.set_up_test_model(app_label, unique_together=True) self.assertUniqueConstraintExists(table_name, ["pink", "weight"]) # Add index together. new_state = project_state.clone() operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")]) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexExists(table_name, ["pink", "weight"]) # Remove index together. project_state = new_state new_state = project_state.clone() operation = migrations.AlterIndexTogether("Pony", set()) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNotExists(table_name, ["pink", "weight"]) self.assertUniqueConstraintExists(table_name, ["pink", "weight"]) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_constraint(self): project_state = self.set_up_test_model("test_addconstraint") gt_check = models.Q(pink__gt=2) gt_constraint = models.CheckConstraint( check=gt_check, name="test_add_constraint_pony_pink_gt_2" ) gt_operation = migrations.AddConstraint("Pony", gt_constraint) self.assertEqual( gt_operation.describe(), "Create constraint test_add_constraint_pony_pink_gt_2 on model Pony", ) self.assertEqual( gt_operation.migration_name_fragment, "pony_test_add_constraint_pony_pink_gt_2", ) # Test the state alteration new_state = project_state.clone() gt_operation.state_forwards("test_addconstraint", new_state) self.assertEqual( len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 1, ) Pony = new_state.apps.get_model("test_addconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test the database alteration with connection.schema_editor() as editor: gt_operation.database_forwards( "test_addconstraint", editor, project_state, new_state ) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=1.0) # Add another one. lt_check = models.Q(pink__lt=100) lt_constraint = models.CheckConstraint( check=lt_check, name="test_add_constraint_pony_pink_lt_100" ) lt_operation = migrations.AddConstraint("Pony", lt_constraint) lt_operation.state_forwards("test_addconstraint", new_state) self.assertEqual( len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 2, ) Pony = new_state.apps.get_model("test_addconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 2) with connection.schema_editor() as editor: lt_operation.database_forwards( "test_addconstraint", editor, project_state, new_state ) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=100, weight=1.0) # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_addconstraint", editor, new_state, project_state ) Pony.objects.create(pink=1, weight=1.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": gt_constraint} ) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_constraint_percent_escaping(self): app_label = "add_constraint_string_quoting" operations = [ migrations.CreateModel( "Author", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ("surname", models.CharField(max_length=100, default="")), ("rebate", models.CharField(max_length=100)), ], ), ] from_state = self.apply_operations(app_label, ProjectState(), operations) # "%" generated in startswith lookup should be escaped in a way that is # considered a leading wildcard. check = models.Q(name__startswith="Albert") constraint = models.CheckConstraint(check=check, name="name_constraint") operation = migrations.AddConstraint("Author", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Author = to_state.apps.get_model(app_label, "Author") with self.assertRaises(IntegrityError), transaction.atomic(): Author.objects.create(name="Artur") # Literal "%" should be escaped in a way that is not a considered a # wildcard. check = models.Q(rebate__endswith="%") constraint = models.CheckConstraint(check=check, name="rebate_constraint") operation = migrations.AddConstraint("Author", constraint) from_state = to_state to_state = from_state.clone() operation.state_forwards(app_label, to_state) Author = to_state.apps.get_model(app_label, "Author") with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Author = to_state.apps.get_model(app_label, "Author") with self.assertRaises(IntegrityError), transaction.atomic(): Author.objects.create(name="Albert", rebate="10$") author = Author.objects.create(name="Albert", rebate="10%") self.assertEqual(Author.objects.get(), author) # Right-hand-side baked "%" literals should not be used for parameters # interpolation. check = ~models.Q(surname__startswith=models.F("name")) constraint = models.CheckConstraint(check=check, name="name_constraint_rhs") operation = migrations.AddConstraint("Author", constraint) from_state = to_state to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Author = to_state.apps.get_model(app_label, "Author") with self.assertRaises(IntegrityError), transaction.atomic(): Author.objects.create(name="Albert", surname="Alberto") @skipUnlessDBFeature("supports_table_check_constraints") def test_add_or_constraint(self): app_label = "test_addorconstraint" constraint_name = "add_constraint_or" from_state = self.set_up_test_model(app_label) check = models.Q(pink__gt=2, weight__gt=2) | models.Q(weight__lt=0) constraint = models.CheckConstraint(check=check, name=constraint_name) operation = migrations.AddConstraint("Pony", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Pony = to_state.apps.get_model(app_label, "Pony") with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=2, weight=3.0) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=3, weight=1.0) Pony.objects.bulk_create( [ Pony(pink=3, weight=-1.0), Pony(pink=1, weight=-1.0), Pony(pink=3, weight=3.0), ] ) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_constraint_combinable(self): app_label = "test_addconstraint_combinable" operations = [ migrations.CreateModel( "Book", fields=[ ("id", models.AutoField(primary_key=True)), ("read", models.PositiveIntegerField()), ("unread", models.PositiveIntegerField()), ], ), ] from_state = self.apply_operations(app_label, ProjectState(), operations) constraint = models.CheckConstraint( check=models.Q(read=(100 - models.F("unread"))), name="test_addconstraint_combinable_sum_100", ) operation = migrations.AddConstraint("Book", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Book = to_state.apps.get_model(app_label, "Book") with self.assertRaises(IntegrityError), transaction.atomic(): Book.objects.create(read=70, unread=10) Book.objects.create(read=70, unread=30) @skipUnlessDBFeature("supports_table_check_constraints") def test_remove_constraint(self): project_state = self.set_up_test_model( "test_removeconstraint", constraints=[ models.CheckConstraint( check=models.Q(pink__gt=2), name="test_remove_constraint_pony_pink_gt_2", ), models.CheckConstraint( check=models.Q(pink__lt=100), name="test_remove_constraint_pony_pink_lt_100", ), ], ) gt_operation = migrations.RemoveConstraint( "Pony", "test_remove_constraint_pony_pink_gt_2" ) self.assertEqual( gt_operation.describe(), "Remove constraint test_remove_constraint_pony_pink_gt_2 from model Pony", ) self.assertEqual( gt_operation.migration_name_fragment, "remove_pony_test_remove_constraint_pony_pink_gt_2", ) # Test state alteration new_state = project_state.clone() gt_operation.state_forwards("test_removeconstraint", new_state) self.assertEqual( len( new_state.models["test_removeconstraint", "pony"].options["constraints"] ), 1, ) Pony = new_state.apps.get_model("test_removeconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test database alteration with connection.schema_editor() as editor: gt_operation.database_forwards( "test_removeconstraint", editor, project_state, new_state ) Pony.objects.create(pink=1, weight=1.0).delete() with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=100, weight=1.0) # Remove the other one. lt_operation = migrations.RemoveConstraint( "Pony", "test_remove_constraint_pony_pink_lt_100" ) lt_operation.state_forwards("test_removeconstraint", new_state) self.assertEqual( len( new_state.models["test_removeconstraint", "pony"].options["constraints"] ), 0, ) Pony = new_state.apps.get_model("test_removeconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor: lt_operation.database_forwards( "test_removeconstraint", editor, project_state, new_state ) Pony.objects.create(pink=100, weight=1.0).delete() # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_removeconstraint", editor, new_state, project_state ) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=1.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "name": "test_remove_constraint_pony_pink_gt_2"}, ) def test_add_partial_unique_constraint(self): project_state = self.set_up_test_model("test_addpartialuniqueconstraint") partial_unique_constraint = models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ) operation = migrations.AddConstraint("Pony", partial_unique_constraint) self.assertEqual( operation.describe(), "Create constraint test_constraint_pony_pink_for_weight_gt_5_uniq " "on model Pony", ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_addpartialuniqueconstraint", new_state) self.assertEqual( len( new_state.models["test_addpartialuniqueconstraint", "pony"].options[ "constraints" ] ), 1, ) Pony = new_state.apps.get_model("test_addpartialuniqueconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_addpartialuniqueconstraint", editor, project_state, new_state ) # Test constraint works Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_addpartialuniqueconstraint", editor, new_state, project_state ) # Test constraint doesn't work Pony.objects.create(pink=1, weight=7.0) # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": partial_unique_constraint}, ) def test_remove_partial_unique_constraint(self): project_state = self.set_up_test_model( "test_removepartialuniqueconstraint", constraints=[ models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ), ], ) gt_operation = migrations.RemoveConstraint( "Pony", "test_constraint_pony_pink_for_weight_gt_5_uniq" ) self.assertEqual( gt_operation.describe(), "Remove constraint test_constraint_pony_pink_for_weight_gt_5_uniq from " "model Pony", ) # Test state alteration new_state = project_state.clone() gt_operation.state_forwards("test_removepartialuniqueconstraint", new_state) self.assertEqual( len( new_state.models["test_removepartialuniqueconstraint", "pony"].options[ "constraints" ] ), 0, ) Pony = new_state.apps.get_model("test_removepartialuniqueconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 0) # Test database alteration with connection.schema_editor() as editor: gt_operation.database_forwards( "test_removepartialuniqueconstraint", editor, project_state, new_state ) # Test constraint doesn't work Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) Pony.objects.create(pink=1, weight=7.0).delete() # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_removepartialuniqueconstraint", editor, new_state, project_state ) # Test constraint works if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "test_constraint_pony_pink_for_weight_gt_5_uniq", }, ) def test_add_deferred_unique_constraint(self): app_label = "test_adddeferred_uc" project_state = self.set_up_test_model(app_label) deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferred_pink_constraint_add", deferrable=models.Deferrable.DEFERRED, ) operation = migrations.AddConstraint("Pony", deferred_unique_constraint) self.assertEqual( operation.describe(), "Create constraint deferred_pink_constraint_add on model Pony", ) # Add constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 3 obj.save() else: self.assertEqual(len(ctx), 0) Pony.objects.create(pink=1, weight=4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": deferred_unique_constraint}, ) def test_remove_deferred_unique_constraint(self): app_label = "test_removedeferred_uc" deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferred_pink_constraint_rm", deferrable=models.Deferrable.DEFERRED, ) project_state = self.set_up_test_model( app_label, constraints=[deferred_unique_constraint] ) operation = migrations.RemoveConstraint("Pony", deferred_unique_constraint.name) self.assertEqual( operation.describe(), "Remove constraint deferred_pink_constraint_rm from model Pony", ) # Remove constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0).delete() if not connection.features.supports_deferrable_unique_constraints: self.assertEqual(len(ctx), 0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 3 obj.save() else: Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "deferred_pink_constraint_rm", }, ) def test_add_covering_unique_constraint(self): app_label = "test_addcovering_uc" project_state = self.set_up_test_model(app_label) covering_unique_constraint = models.UniqueConstraint( fields=["pink"], name="covering_pink_constraint_add", include=["weight"], ) operation = migrations.AddConstraint("Pony", covering_unique_constraint) self.assertEqual( operation.describe(), "Create constraint covering_pink_constraint_add on model Pony", ) # Add constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_covering_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=4.0) else: self.assertEqual(len(ctx), 0) Pony.objects.create(pink=1, weight=4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": covering_unique_constraint}, ) def test_remove_covering_unique_constraint(self): app_label = "test_removecovering_uc" covering_unique_constraint = models.UniqueConstraint( fields=["pink"], name="covering_pink_constraint_rm", include=["weight"], ) project_state = self.set_up_test_model( app_label, constraints=[covering_unique_constraint] ) operation = migrations.RemoveConstraint("Pony", covering_unique_constraint.name) self.assertEqual( operation.describe(), "Remove constraint covering_pink_constraint_rm from model Pony", ) # Remove constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0).delete() if not connection.features.supports_covering_indexes: self.assertEqual(len(ctx), 0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_covering_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=4.0) else: Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "covering_pink_constraint_rm", }, ) def test_alter_field_with_func_unique_constraint(self): app_label = "test_alfuncuc" constraint_name = f"{app_label}_pony_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, constraints=[ models.UniqueConstraint("pink", "weight", name=constraint_name) ], ) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) def test_add_func_unique_constraint(self): app_label = "test_adfuncuc" constraint_name = f"{app_label}_pony_abs_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) constraint = models.UniqueConstraint(Abs("weight"), name=constraint_name) operation = migrations.AddConstraint("Pony", constraint) self.assertEqual( operation.describe(), "Create constraint test_adfuncuc_pony_abs_uq on model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_adfuncuc_pony_abs_uq", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) self.assertIndexNameNotExists(table_name, constraint_name) # Add constraint. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) Pony = new_state.apps.get_model(app_label, "Pony") Pony.objects.create(weight=4.0) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with self.assertRaises(IntegrityError): Pony.objects.create(weight=-4.0) else: self.assertIndexNameNotExists(table_name, constraint_name) Pony.objects.create(weight=-4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameNotExists(table_name, constraint_name) # Constraint doesn't work. Pony.objects.create(weight=-4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": constraint}, ) def test_remove_func_unique_constraint(self): app_label = "test_rmfuncuc" constraint_name = f"{app_label}_pony_abs_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, constraints=[ models.UniqueConstraint(Abs("weight"), name=constraint_name), ], ) self.assertTableExists(table_name) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) operation = migrations.RemoveConstraint("Pony", constraint_name) self.assertEqual( operation.describe(), "Remove constraint test_rmfuncuc_pony_abs_uq from model Pony", ) self.assertEqual( operation.migration_name_fragment, "remove_pony_test_rmfuncuc_pony_abs_uq", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) # Remove constraint. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, constraint_name) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=-4.0).delete() # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with self.assertRaises(IntegrityError): Pony.objects.create(weight=-4.0) else: self.assertIndexNameNotExists(table_name, constraint_name) Pony.objects.create(weight=-4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": constraint_name}) def test_alter_model_options(self): """ Tests the AlterModelOptions operation. """ project_state = self.set_up_test_model("test_almoop") # Test the state alteration (no DB alteration to test) operation = migrations.AlterModelOptions( "Pony", {"permissions": [("can_groom", "Can groom")]} ) self.assertEqual(operation.describe(), "Change Meta options on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_options") new_state = project_state.clone() operation.state_forwards("test_almoop", new_state) self.assertEqual( len( project_state.models["test_almoop", "pony"].options.get( "permissions", [] ) ), 0, ) self.assertEqual( len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 1, ) self.assertEqual( new_state.models["test_almoop", "pony"].options["permissions"][0][0], "can_groom", ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelOptions") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "options": {"permissions": [("can_groom", "Can groom")]}}, ) def test_alter_model_options_emptying(self): """ The AlterModelOptions operation removes keys from the dict (#23121) """ project_state = self.set_up_test_model("test_almoop", options=True) # Test the state alteration (no DB alteration to test) operation = migrations.AlterModelOptions("Pony", {}) self.assertEqual(operation.describe(), "Change Meta options on Pony") new_state = project_state.clone() operation.state_forwards("test_almoop", new_state) self.assertEqual( len( project_state.models["test_almoop", "pony"].options.get( "permissions", [] ) ), 1, ) self.assertEqual( len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 0, ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelOptions") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"name": "Pony", "options": {}}) def test_alter_order_with_respect_to(self): """ Tests the AlterOrderWithRespectTo operation. """ project_state = self.set_up_test_model("test_alorwrtto", related_model=True) # Test the state alteration operation = migrations.AlterOrderWithRespectTo("Rider", "pony") self.assertEqual( operation.describe(), "Set order_with_respect_to on Rider to pony" ) self.assertEqual( operation.migration_name_fragment, "alter_rider_order_with_respect_to", ) new_state = project_state.clone() operation.state_forwards("test_alorwrtto", new_state) self.assertIsNone( project_state.models["test_alorwrtto", "rider"].options.get( "order_with_respect_to", None ) ) self.assertEqual( new_state.models["test_alorwrtto", "rider"].options.get( "order_with_respect_to", None ), "pony", ) # Make sure there's no matching index self.assertColumnNotExists("test_alorwrtto_rider", "_order") # Create some rows before alteration rendered_state = project_state.apps pony = rendered_state.get_model("test_alorwrtto", "Pony").objects.create( weight=50 ) rider1 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create( pony=pony ) rider1.friend = rider1 rider1.save() rider2 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create( pony=pony ) rider2.friend = rider2 rider2.save() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alorwrtto", editor, project_state, new_state ) self.assertColumnExists("test_alorwrtto_rider", "_order") # Check for correct value in rows updated_riders = new_state.apps.get_model( "test_alorwrtto", "Rider" ).objects.all() self.assertEqual(updated_riders[0]._order, 0) self.assertEqual(updated_riders[1]._order, 0) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alorwrtto", editor, new_state, project_state ) self.assertColumnNotExists("test_alorwrtto_rider", "_order") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterOrderWithRespectTo") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Rider", "order_with_respect_to": "pony"} ) def test_alter_model_managers(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_almoma") # Test the state alteration operation = migrations.AlterModelManagers( "Pony", managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) self.assertEqual(operation.describe(), "Change managers on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_managers") managers = project_state.models["test_almoma", "pony"].managers self.assertEqual(managers, []) new_state = project_state.clone() operation.state_forwards("test_almoma", new_state) self.assertIn(("test_almoma", "pony"), new_state.models) managers = new_state.models["test_almoma", "pony"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) rendered_state = new_state.apps model = rendered_state.get_model("test_almoma", "pony") self.assertIsInstance(model.food_qs, models.Manager) self.assertIsInstance(model.food_mgr, FoodManager) self.assertIsInstance(model.food_mgr_kwargs, FoodManager) def test_alter_model_managers_emptying(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_almomae", manager_model=True) # Test the state alteration operation = migrations.AlterModelManagers("Food", managers=[]) self.assertEqual(operation.describe(), "Change managers on Food") self.assertIn(("test_almomae", "food"), project_state.models) managers = project_state.models["test_almomae", "food"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) new_state = project_state.clone() operation.state_forwards("test_almomae", new_state) managers = new_state.models["test_almomae", "food"].managers self.assertEqual(managers, []) def test_alter_fk(self): """ Creating and then altering an FK works correctly and deals with the pending SQL (#23091) """ project_state = self.set_up_test_model("test_alfk") # Test adding and then altering the FK in one go create_operation = migrations.CreateModel( name="Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ) create_state = project_state.clone() create_operation.state_forwards("test_alfk", create_state) alter_operation = migrations.AlterField( model_name="Rider", name="pony", field=models.ForeignKey("Pony", models.CASCADE, editable=False), ) alter_state = create_state.clone() alter_operation.state_forwards("test_alfk", alter_state) with connection.schema_editor() as editor: create_operation.database_forwards( "test_alfk", editor, project_state, create_state ) alter_operation.database_forwards( "test_alfk", editor, create_state, alter_state ) def test_alter_fk_non_fk(self): """ Altering an FK to a non-FK works (#23244) """ # Test the state alteration operation = migrations.AlterField( model_name="Rider", name="pony", field=models.FloatField(), ) project_state, new_state = self.make_test_state( "test_afknfk", operation, related_model=True ) # Test the database alteration self.assertColumnExists("test_afknfk_rider", "pony_id") self.assertColumnNotExists("test_afknfk_rider", "pony") with connection.schema_editor() as editor: operation.database_forwards("test_afknfk", editor, project_state, new_state) self.assertColumnExists("test_afknfk_rider", "pony") self.assertColumnNotExists("test_afknfk_rider", "pony_id") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_afknfk", editor, new_state, project_state ) self.assertColumnExists("test_afknfk_rider", "pony_id") self.assertColumnNotExists("test_afknfk_rider", "pony") def test_run_sql(self): """ Tests the RunSQL operation. """ project_state = self.set_up_test_model("test_runsql") # Create the operation operation = migrations.RunSQL( # Use a multi-line string with a comment to test splitting on # SQLite and MySQL respectively. "CREATE TABLE i_love_ponies (id int, special_thing varchar(15));\n" "INSERT INTO i_love_ponies (id, special_thing) " "VALUES (1, 'i love ponies'); -- this is magic!\n" "INSERT INTO i_love_ponies (id, special_thing) " "VALUES (2, 'i love django');\n" "UPDATE i_love_ponies SET special_thing = 'Ponies' " "WHERE special_thing LIKE '%%ponies';" "UPDATE i_love_ponies SET special_thing = 'Django' " "WHERE special_thing LIKE '%django';", # Run delete queries to test for parameter substitution failure # reported in #23426 "DELETE FROM i_love_ponies WHERE special_thing LIKE '%Django%';" "DELETE FROM i_love_ponies WHERE special_thing LIKE '%%Ponies%%';" "DROP TABLE i_love_ponies", state_operations=[ migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))] ) ], ) self.assertEqual(operation.describe(), "Raw SQL operation") # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_runsql", new_state) self.assertEqual( len(new_state.models["test_runsql", "somethingelse"].fields), 1 ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") # Test SQL collection with connection.schema_editor(collect_sql=True) as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) self.assertIn("LIKE '%%ponies';", "\n".join(editor.collected_sql)) operation.database_backwards( "test_runsql", editor, project_state, new_state ) self.assertIn("LIKE '%%Ponies%%';", "\n".join(editor.collected_sql)) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) self.assertTableExists("i_love_ponies") # Make sure all the SQL was processed with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 2) cursor.execute( "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Django'" ) self.assertEqual(cursor.fetchall()[0][0], 1) cursor.execute( "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Ponies'" ) self.assertEqual(cursor.fetchall()[0][0], 1) # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_runsql", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunSQL") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["reverse_sql", "sql", "state_operations"] ) # And elidable reduction self.assertIs(False, operation.reduce(operation, [])) elidable_operation = migrations.RunSQL("SELECT 1 FROM void;", elidable=True) self.assertEqual(elidable_operation.reduce(operation, []), [operation]) def test_run_sql_params(self): """ #23426 - RunSQL should accept parameters. """ project_state = self.set_up_test_model("test_runsql") # Create the operation operation = migrations.RunSQL( ["CREATE TABLE i_love_ponies (id int, special_thing varchar(15));"], ["DROP TABLE i_love_ponies"], ) param_operation = migrations.RunSQL( # forwards ( "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 'Django');", [ "INSERT INTO i_love_ponies (id, special_thing) VALUES (2, %s);", ["Ponies"], ], ( "INSERT INTO i_love_ponies (id, special_thing) VALUES (%s, %s);", ( 3, "Python", ), ), ), # backwards [ "DELETE FROM i_love_ponies WHERE special_thing = 'Django';", ["DELETE FROM i_love_ponies WHERE special_thing = 'Ponies';", None], ( "DELETE FROM i_love_ponies WHERE id = %s OR special_thing = %s;", [3, "Python"], ), ], ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") new_state = project_state.clone() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) # Test parameter passing with connection.schema_editor() as editor: param_operation.database_forwards( "test_runsql", editor, project_state, new_state ) # Make sure all the SQL was processed with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 3) with connection.schema_editor() as editor: param_operation.database_backwards( "test_runsql", editor, new_state, project_state ) with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 0) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_runsql", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") def test_run_sql_params_invalid(self): """ #23426 - RunSQL should fail when a list of statements with an incorrect number of tuples is given. """ project_state = self.set_up_test_model("test_runsql") new_state = project_state.clone() operation = migrations.RunSQL( # forwards [["INSERT INTO foo (bar) VALUES ('buz');"]], # backwards (("DELETE FROM foo WHERE bar = 'buz';", "invalid", "parameter count"),), ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 1"): operation.database_forwards( "test_runsql", editor, project_state, new_state ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 3"): operation.database_backwards( "test_runsql", editor, new_state, project_state ) def test_run_sql_noop(self): """ #24098 - Tests no-op RunSQL operations. """ operation = migrations.RunSQL(migrations.RunSQL.noop, migrations.RunSQL.noop) with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, None, None) operation.database_backwards("test_runsql", editor, None, None) def test_run_sql_add_missing_semicolon_on_collect_sql(self): project_state = self.set_up_test_model("test_runsql") new_state = project_state.clone() tests = [ "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1);\n", "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1)\n", ] for sql in tests: with self.subTest(sql=sql): operation = migrations.RunSQL(sql, migrations.RunPython.noop) with connection.schema_editor(collect_sql=True) as editor: operation.database_forwards( "test_runsql", editor, project_state, new_state ) collected_sql = "\n".join(editor.collected_sql) self.assertEqual(collected_sql.count(";"), 1) def test_run_python(self): """ Tests the RunPython operation """ project_state = self.set_up_test_model("test_runpython", mti_model=True) # Create the operation def inner_method(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") Pony.objects.create(pink=1, weight=3.55) Pony.objects.create(weight=5) def inner_method_reverse(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") Pony.objects.filter(pink=1, weight=3.55).delete() Pony.objects.filter(weight=5).delete() operation = migrations.RunPython( inner_method, reverse_code=inner_method_reverse ) self.assertEqual(operation.describe(), "Raw Python operation") # Test the state alteration does nothing new_state = project_state.clone() operation.state_forwards("test_runpython", new_state) self.assertEqual(new_state, project_state) # Test the database alteration self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0 ) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2 ) # Now test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0 ) # Now test we can't use a string with self.assertRaisesMessage( ValueError, "RunPython must be supplied with a callable" ): migrations.RunPython("print 'ahahaha'") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["code", "reverse_code"]) # Also test reversal fails, with an operation identical to above but # without reverse_code set. no_reverse_operation = migrations.RunPython(inner_method) self.assertFalse(no_reverse_operation.reversible) with connection.schema_editor() as editor: no_reverse_operation.database_forwards( "test_runpython", editor, project_state, new_state ) with self.assertRaises(NotImplementedError): no_reverse_operation.database_backwards( "test_runpython", editor, new_state, project_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2 ) def create_ponies(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") pony1 = Pony.objects.create(pink=1, weight=3.55) self.assertIsNot(pony1.pk, None) pony2 = Pony.objects.create(weight=5) self.assertIsNot(pony2.pk, None) self.assertNotEqual(pony1.pk, pony2.pk) operation = migrations.RunPython(create_ponies) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 4 ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["code"]) def create_shetlandponies(models, schema_editor): ShetlandPony = models.get_model("test_runpython", "ShetlandPony") pony1 = ShetlandPony.objects.create(weight=4.0) self.assertIsNot(pony1.pk, None) pony2 = ShetlandPony.objects.create(weight=5.0) self.assertIsNot(pony2.pk, None) self.assertNotEqual(pony1.pk, pony2.pk) operation = migrations.RunPython(create_shetlandponies) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 6 ) self.assertEqual( project_state.apps.get_model( "test_runpython", "ShetlandPony" ).objects.count(), 2, ) # And elidable reduction self.assertIs(False, operation.reduce(operation, [])) elidable_operation = migrations.RunPython(inner_method, elidable=True) self.assertEqual(elidable_operation.reduce(operation, []), [operation]) def test_run_python_atomic(self): """ Tests the RunPython operation correctly handles the "atomic" keyword """ project_state = self.set_up_test_model("test_runpythonatomic", mti_model=True) def inner_method(models, schema_editor): Pony = models.get_model("test_runpythonatomic", "Pony") Pony.objects.create(pink=1, weight=3.55) raise ValueError("Adrian hates ponies.") # Verify atomicity when applying. atomic_migration = Migration("test", "test_runpythonatomic") atomic_migration.operations = [ migrations.RunPython(inner_method, reverse_code=inner_method) ] non_atomic_migration = Migration("test", "test_runpythonatomic") non_atomic_migration.operations = [ migrations.RunPython(inner_method, reverse_code=inner_method, atomic=False) ] # If we're a fully-transactional database, both versions should rollback if connection.features.can_rollback_ddl: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) # Otherwise, the non-atomic operation should leave a row there else: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 1, ) # Reset object count to zero and verify atomicity when unapplying. project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.all().delete() # On a fully-transactional database, both versions rollback. if connection.features.can_rollback_ddl: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) # Otherwise, the non-atomic operation leaves a row there. else: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 1, ) # Verify deconstruction. definition = non_atomic_migration.operations[0].deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["atomic", "code", "reverse_code"]) def test_run_python_related_assignment(self): """ #24282 - Model changes to a FK reverse side update the model on the FK side as well. """ def inner_method(models, schema_editor): Author = models.get_model("test_authors", "Author") Book = models.get_model("test_books", "Book") author = Author.objects.create(name="Hemingway") Book.objects.create(title="Old Man and The Sea", author=author) create_author = migrations.CreateModel( "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_book = migrations.CreateModel( "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=100)), ("author", models.ForeignKey("test_authors.Author", models.CASCADE)), ], options={}, ) add_hometown = migrations.AddField( "Author", "hometown", models.CharField(max_length=100), ) create_old_man = migrations.RunPython(inner_method, inner_method) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_author.state_forwards("test_authors", new_state) create_author.database_forwards( "test_authors", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_book.state_forwards("test_books", new_state) create_book.database_forwards( "test_books", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: add_hometown.state_forwards("test_authors", new_state) add_hometown.database_forwards( "test_authors", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_old_man.state_forwards("test_books", new_state) create_old_man.database_forwards( "test_books", editor, project_state, new_state ) def test_model_with_bigautofield(self): """ A model with BigAutoField can be created. """ def create_data(models, schema_editor): Author = models.get_model("test_author", "Author") Book = models.get_model("test_book", "Book") author1 = Author.objects.create(name="Hemingway") Book.objects.create(title="Old Man and The Sea", author=author1) Book.objects.create(id=2**33, title="A farewell to arms", author=author1) author2 = Author.objects.create(id=2**33, name="Remarque") Book.objects.create(title="All quiet on the western front", author=author2) Book.objects.create(title="Arc de Triomphe", author=author2) create_author = migrations.CreateModel( "Author", [ ("id", models.BigAutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_book = migrations.CreateModel( "Book", [ ("id", models.BigAutoField(primary_key=True)), ("title", models.CharField(max_length=100)), ( "author", models.ForeignKey( to="test_author.Author", on_delete=models.CASCADE ), ), ], options={}, ) fill_data = migrations.RunPython(create_data) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_author.state_forwards("test_author", new_state) create_author.database_forwards( "test_author", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_book.state_forwards("test_book", new_state) create_book.database_forwards("test_book", editor, project_state, new_state) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_data.state_forwards("fill_data", new_state) fill_data.database_forwards("fill_data", editor, project_state, new_state) def _test_autofield_foreignfield_growth( self, source_field, target_field, target_value ): """ A field may be migrated in the following ways: - AutoField to BigAutoField - SmallAutoField to AutoField - SmallAutoField to BigAutoField """ def create_initial_data(models, schema_editor): Article = models.get_model("test_article", "Article") Blog = models.get_model("test_blog", "Blog") blog = Blog.objects.create(name="web development done right") Article.objects.create(name="Frameworks", blog=blog) Article.objects.create(name="Programming Languages", blog=blog) def create_big_data(models, schema_editor): Article = models.get_model("test_article", "Article") Blog = models.get_model("test_blog", "Blog") blog2 = Blog.objects.create(name="Frameworks", id=target_value) Article.objects.create(name="Django", blog=blog2) Article.objects.create(id=target_value, name="Django2", blog=blog2) create_blog = migrations.CreateModel( "Blog", [ ("id", source_field(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_article = migrations.CreateModel( "Article", [ ("id", source_field(primary_key=True)), ( "blog", models.ForeignKey(to="test_blog.Blog", on_delete=models.CASCADE), ), ("name", models.CharField(max_length=100)), ("data", models.TextField(default="")), ], options={}, ) fill_initial_data = migrations.RunPython( create_initial_data, create_initial_data ) fill_big_data = migrations.RunPython(create_big_data, create_big_data) grow_article_id = migrations.AlterField( "Article", "id", target_field(primary_key=True) ) grow_blog_id = migrations.AlterField( "Blog", "id", target_field(primary_key=True) ) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_blog.state_forwards("test_blog", new_state) create_blog.database_forwards("test_blog", editor, project_state, new_state) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_article.state_forwards("test_article", new_state) create_article.database_forwards( "test_article", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_initial_data.state_forwards("fill_initial_data", new_state) fill_initial_data.database_forwards( "fill_initial_data", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: grow_article_id.state_forwards("test_article", new_state) grow_article_id.database_forwards( "test_article", editor, project_state, new_state ) state = new_state.clone() article = state.apps.get_model("test_article.Article") self.assertIsInstance(article._meta.pk, target_field) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: grow_blog_id.state_forwards("test_blog", new_state) grow_blog_id.database_forwards( "test_blog", editor, project_state, new_state ) state = new_state.clone() blog = state.apps.get_model("test_blog.Blog") self.assertIsInstance(blog._meta.pk, target_field) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_big_data.state_forwards("fill_big_data", new_state) fill_big_data.database_forwards( "fill_big_data", editor, project_state, new_state ) def test_autofield__bigautofield_foreignfield_growth(self): """A field may be migrated from AutoField to BigAutoField.""" self._test_autofield_foreignfield_growth( models.AutoField, models.BigAutoField, 2**33, ) def test_smallfield_autofield_foreignfield_growth(self): """A field may be migrated from SmallAutoField to AutoField.""" self._test_autofield_foreignfield_growth( models.SmallAutoField, models.AutoField, 2**22, ) def test_smallfield_bigautofield_foreignfield_growth(self): """A field may be migrated from SmallAutoField to BigAutoField.""" self._test_autofield_foreignfield_growth( models.SmallAutoField, models.BigAutoField, 2**33, ) def test_run_python_noop(self): """ #24098 - Tests no-op RunPython operations. """ project_state = ProjectState() new_state = project_state.clone() operation = migrations.RunPython( migrations.RunPython.noop, migrations.RunPython.noop ) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) operation.database_backwards( "test_runpython", editor, new_state, project_state ) def test_separate_database_and_state(self): """ Tests the SeparateDatabaseAndState operation. """ project_state = self.set_up_test_model("test_separatedatabaseandstate") # Create the operation database_operation = migrations.RunSQL( "CREATE TABLE i_love_ponies (id int, special_thing int);", "DROP TABLE i_love_ponies;", ) state_operation = migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))] ) operation = migrations.SeparateDatabaseAndState( state_operations=[state_operation], database_operations=[database_operation] ) self.assertEqual( operation.describe(), "Custom state/database change combination" ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_separatedatabaseandstate", new_state) self.assertEqual( len( new_state.models[ "test_separatedatabaseandstate", "somethingelse" ].fields ), 1, ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_separatedatabaseandstate", editor, project_state, new_state ) self.assertTableExists("i_love_ponies") # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_separatedatabaseandstate", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "SeparateDatabaseAndState") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["database_operations", "state_operations"] ) def test_separate_database_and_state2(self): """ A complex SeparateDatabaseAndState operation: Multiple operations both for state and database. Verify the state dependencies within each list and that state ops don't affect the database. """ app_label = "test_separatedatabaseandstate2" project_state = self.set_up_test_model(app_label) # Create the operation database_operations = [ migrations.CreateModel( "ILovePonies", [("id", models.AutoField(primary_key=True))], options={"db_table": "iloveponies"}, ), migrations.CreateModel( "ILoveMorePonies", # We use IntegerField and not AutoField because # the model is going to be deleted immediately # and with an AutoField this fails on Oracle [("id", models.IntegerField(primary_key=True))], options={"db_table": "ilovemoreponies"}, ), migrations.DeleteModel("ILoveMorePonies"), migrations.CreateModel( "ILoveEvenMorePonies", [("id", models.AutoField(primary_key=True))], options={"db_table": "iloveevenmoreponies"}, ), ] state_operations = [ migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))], options={"db_table": "somethingelse"}, ), migrations.DeleteModel("SomethingElse"), migrations.CreateModel( "SomethingCompletelyDifferent", [("id", models.AutoField(primary_key=True))], options={"db_table": "somethingcompletelydifferent"}, ), ] operation = migrations.SeparateDatabaseAndState( state_operations=state_operations, database_operations=database_operations, ) # Test the state alteration new_state = project_state.clone() operation.state_forwards(app_label, new_state) def assertModelsAndTables(after_db): # Tables and models exist, or don't, as they should: self.assertNotIn((app_label, "somethingelse"), new_state.models) self.assertEqual( len(new_state.models[app_label, "somethingcompletelydifferent"].fields), 1, ) self.assertNotIn((app_label, "iloveponiesonies"), new_state.models) self.assertNotIn((app_label, "ilovemoreponies"), new_state.models) self.assertNotIn((app_label, "iloveevenmoreponies"), new_state.models) self.assertTableNotExists("somethingelse") self.assertTableNotExists("somethingcompletelydifferent") self.assertTableNotExists("ilovemoreponies") if after_db: self.assertTableExists("iloveponies") self.assertTableExists("iloveevenmoreponies") else: self.assertTableNotExists("iloveponies") self.assertTableNotExists("iloveevenmoreponies") assertModelsAndTables(after_db=False) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertModelsAndTables(after_db=True) # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertModelsAndTables(after_db=False) class SwappableOperationTests(OperationTestBase): """ Key operations ignore swappable models (we don't want to replicate all of them here, as the functionality is in a common base class anyway) """ available_apps = ["migrations"] @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_create_ignore_swapped(self): """ The CreateTable operation ignores swapped models. """ operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], options={ "swappable": "TEST_SWAP_MODEL", }, ) # Test the state alteration (it should still be there!) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crigsw", new_state) self.assertEqual(new_state.models["test_crigsw", "pony"].name, "Pony") self.assertEqual(len(new_state.models["test_crigsw", "pony"].fields), 2) # Test the database alteration self.assertTableNotExists("test_crigsw_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crigsw", editor, project_state, new_state) self.assertTableNotExists("test_crigsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crigsw", editor, new_state, project_state ) self.assertTableNotExists("test_crigsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_delete_ignore_swapped(self): """ Tests the DeleteModel operation ignores swapped models. """ operation = migrations.DeleteModel("Pony") project_state, new_state = self.make_test_state("test_dligsw", operation) # Test the database alteration self.assertTableNotExists("test_dligsw_pony") with connection.schema_editor() as editor: operation.database_forwards("test_dligsw", editor, project_state, new_state) self.assertTableNotExists("test_dligsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dligsw", editor, new_state, project_state ) self.assertTableNotExists("test_dligsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_add_field_ignore_swapped(self): """ Tests the AddField operation. """ # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=5), ) project_state, new_state = self.make_test_state("test_adfligsw", operation) # Test the database alteration self.assertTableNotExists("test_adfligsw_pony") with connection.schema_editor() as editor: operation.database_forwards( "test_adfligsw", editor, project_state, new_state ) self.assertTableNotExists("test_adfligsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_adfligsw", editor, new_state, project_state ) self.assertTableNotExists("test_adfligsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_indexes_ignore_swapped(self): """ Add/RemoveIndex operations ignore swapped models. """ operation = migrations.AddIndex( "Pony", models.Index(fields=["pink"], name="my_name_idx") ) project_state, new_state = self.make_test_state("test_adinigsw", operation) with connection.schema_editor() as editor: # No database queries should be run for swapped models operation.database_forwards( "test_adinigsw", editor, project_state, new_state ) operation.database_backwards( "test_adinigsw", editor, new_state, project_state ) operation = migrations.RemoveIndex( "Pony", models.Index(fields=["pink"], name="my_name_idx") ) project_state, new_state = self.make_test_state("test_rminigsw", operation) with connection.schema_editor() as editor: operation.database_forwards( "test_rminigsw", editor, project_state, new_state ) operation.database_backwards( "test_rminigsw", editor, new_state, project_state ) class TestCreateModel(SimpleTestCase): def test_references_model_mixin(self): migrations.CreateModel( "name", fields=[], bases=(Mixin, models.Model), ).references_model("other_model", "migrations") class FieldOperationTests(SimpleTestCase): def test_references_model(self): operation = FieldOperation( "MoDel", "field", models.ForeignKey("Other", models.CASCADE) ) # Model name match. self.assertIs(operation.references_model("mOdEl", "migrations"), True) # Referenced field. self.assertIs(operation.references_model("oTher", "migrations"), True) # Doesn't reference. self.assertIs(operation.references_model("Whatever", "migrations"), False) def test_references_field_by_name(self): operation = FieldOperation("MoDel", "field", models.BooleanField(default=False)) self.assertIs(operation.references_field("model", "field", "migrations"), True) def test_references_field_by_remote_field_model(self): operation = FieldOperation( "Model", "field", models.ForeignKey("Other", models.CASCADE) ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_references_field_by_from_fields(self): operation = FieldOperation( "Model", "field", models.fields.related.ForeignObject( "Other", models.CASCADE, ["from"], ["to"] ), ) self.assertIs(operation.references_field("Model", "from", "migrations"), True) self.assertIs(operation.references_field("Model", "to", "migrations"), False) self.assertIs(operation.references_field("Other", "from", "migrations"), False) self.assertIs(operation.references_field("Model", "to", "migrations"), False) def test_references_field_by_to_fields(self): operation = FieldOperation( "Model", "field", models.ForeignKey("Other", models.CASCADE, to_field="field"), ) self.assertIs(operation.references_field("Other", "field", "migrations"), True) self.assertIs( operation.references_field("Other", "whatever", "migrations"), False ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_references_field_by_through(self): operation = FieldOperation( "Model", "field", models.ManyToManyField("Other", through="Through") ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Through", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_reference_field_by_through_fields(self): operation = FieldOperation( "Model", "field", models.ManyToManyField( "Other", through="Through", through_fields=("first", "second") ), ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Through", "whatever", "migrations"), False ) self.assertIs( operation.references_field("Through", "first", "migrations"), True ) self.assertIs( operation.references_field("Through", "second", "migrations"), True )
44a503d682de1df0f278d055f9b0af72719fd757d5f913fa8cf35252364e8abb
import functools import re from unittest import mock from django.apps import apps from django.conf import settings from django.contrib.auth.models import AbstractBaseUser from django.core.validators import RegexValidator, validate_slug from django.db import connection, migrations, models from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.graph import MigrationGraph from django.db.migrations.loader import MigrationLoader from django.db.migrations.questioner import MigrationQuestioner from django.db.migrations.state import ModelState, ProjectState from django.test import SimpleTestCase, TestCase, override_settings from django.test.utils import isolate_lru_cache from .models import FoodManager, FoodQuerySet class DeconstructibleObject: """ A custom deconstructible object. """ def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def deconstruct(self): return (self.__module__ + "." + self.__class__.__name__, self.args, self.kwargs) class AutodetectorTests(TestCase): """ Tests the migration autodetector. """ author_empty = ModelState( "testapp", "Author", [("id", models.AutoField(primary_key=True))] ) author_name = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], ) author_name_null = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, null=True)), ], ) author_name_longer = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=400)), ], ) author_name_renamed = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("names", models.CharField(max_length=200)), ], ) author_name_default = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default="Ada Lovelace")), ], ) author_name_check_constraint = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], { "constraints": [ models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) ] }, ) author_dates_of_birth_auto_now = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now=True)), ("date_time_of_birth", models.DateTimeField(auto_now=True)), ("time_of_birth", models.TimeField(auto_now=True)), ], ) author_dates_of_birth_auto_now_add = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("date_of_birth", models.DateField(auto_now_add=True)), ("date_time_of_birth", models.DateTimeField(auto_now_add=True)), ("time_of_birth", models.TimeField(auto_now_add=True)), ], ) author_name_deconstructible_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ], ) author_name_deconstructible_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=DeconstructibleObject())), ], ) author_name_deconstructible_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ], ) author_name_deconstructible_4 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, default=models.IntegerField())), ], ) author_name_deconstructible_list_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 123] ), ), ], ) author_name_deconstructible_list_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 123] ), ), ], ) author_name_deconstructible_list_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=[DeconstructibleObject(), 999] ), ), ], ) author_name_deconstructible_tuple_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 123) ), ), ], ) author_name_deconstructible_tuple_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 123) ), ), ], ) author_name_deconstructible_tuple_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=(DeconstructibleObject(), 999) ), ), ], ) author_name_deconstructible_dict_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 123}, ), ), ], ) author_name_deconstructible_dict_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 123}, ), ), ], ) author_name_deconstructible_dict_3 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default={"item": DeconstructibleObject(), "otheritem": 999}, ), ), ], ) author_name_nested_deconstructible_1 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_2 = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_changed_arg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2-changed"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_extra_arg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), None, a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), ), ), ), ], ) author_name_nested_deconstructible_changed_kwarg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c-changed")), ), ), ), ], ) author_name_nested_deconstructible_extra_kwarg = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, default=DeconstructibleObject( DeconstructibleObject(1), ( DeconstructibleObject("t1"), DeconstructibleObject("t2"), ), a=DeconstructibleObject("A"), b=DeconstructibleObject(B=DeconstructibleObject("c")), c=None, ), ), ), ], ) author_custom_pk = ModelState( "testapp", "Author", [("pk_field", models.IntegerField(primary_key=True))] ) author_with_biography_non_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField()), ("biography", models.TextField()), ], ) author_with_biography_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(blank=True)), ("biography", models.TextField(blank=True)), ], ) author_with_book = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) author_with_book_order_wrt = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={"order_with_respect_to": "book"}, ) author_renamed_with_book = ModelState( "testapp", "Writer", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) author_with_publisher_string = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher_name", models.CharField(max_length=200)), ], ) author_with_publisher = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) author_with_user = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("auth.User", models.CASCADE)), ], ) author_with_custom_user = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("user", models.ForeignKey("thirdapp.CustomUser", models.CASCADE)), ], ) author_proxy = ModelState( "testapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",) ) author_proxy_options = ModelState( "testapp", "AuthorProxy", [], { "proxy": True, "verbose_name": "Super Author", }, ("testapp.author",), ) author_proxy_notproxy = ModelState( "testapp", "AuthorProxy", [], {}, ("testapp.author",) ) author_proxy_third = ModelState( "thirdapp", "AuthorProxy", [], {"proxy": True}, ("testapp.author",) ) author_proxy_third_notproxy = ModelState( "thirdapp", "AuthorProxy", [], {}, ("testapp.author",) ) author_proxy_proxy = ModelState( "testapp", "AAuthorProxyProxy", [], {"proxy": True}, ("testapp.authorproxy",) ) author_unmanaged = ModelState( "testapp", "AuthorUnmanaged", [], {"managed": False}, ("testapp.author",) ) author_unmanaged_managed = ModelState( "testapp", "AuthorUnmanaged", [], {}, ("testapp.author",) ) author_unmanaged_default_pk = ModelState( "testapp", "Author", [("id", models.AutoField(primary_key=True))] ) author_unmanaged_custom_pk = ModelState( "testapp", "Author", [ ("pk_field", models.IntegerField(primary_key=True)), ], ) author_with_m2m = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher")), ], ) author_with_m2m_blank = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.ManyToManyField("testapp.Publisher", blank=True)), ], ) author_with_m2m_through = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Contract"), ), ], ) author_with_renamed_m2m_through = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "publishers", models.ManyToManyField("testapp.Publisher", through="testapp.Deal"), ), ], ) author_with_former_m2m = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("publishers", models.CharField(max_length=100)), ], ) author_with_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], { "permissions": [("can_hire", "Can hire")], "verbose_name": "Authi", }, ) author_with_db_table_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}, ) author_with_new_db_table_options = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_two"}, ) author_renamed_with_db_table_options = ModelState( "testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_one"}, ) author_renamed_with_new_db_table_options = ModelState( "testapp", "NewAuthor", [ ("id", models.AutoField(primary_key=True)), ], {"db_table": "author_three"}, ) contract = ModelState( "testapp", "Contract", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) contract_renamed = ModelState( "testapp", "Deal", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("publisher", models.ForeignKey("testapp.Publisher", models.CASCADE)), ], ) publisher = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], ) publisher_with_author = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) publisher_with_aardvark_author = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Aardvark", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) publisher_with_book = ModelState( "testapp", "Publisher", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Book", models.CASCADE)), ("name", models.CharField(max_length=100)), ], ) other_pony = ModelState( "otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ], ) other_pony_food = ModelState( "otherapp", "Pony", [ ("id", models.AutoField(primary_key=True)), ], managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) other_stable = ModelState( "otherapp", "Stable", [("id", models.AutoField(primary_key=True))] ) third_thing = ModelState( "thirdapp", "Thing", [("id", models.AutoField(primary_key=True))] ) book = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_proxy_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("thirdapp.AuthorProxy", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_proxy_proxy_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.AAuthorProxyProxy", models.CASCADE)), ], ) book_migrations_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("migrations.UnmigratedModel", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_no_author_fk = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.IntegerField()), ("title", models.CharField(max_length=200)), ], ) book_with_no_author = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ], ) book_with_author_renamed = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_field_and_author_renamed = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("writer", models.ForeignKey("testapp.Writer", models.CASCADE)), ("title", models.CharField(max_length=200)), ], ) book_with_multiple_authors = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author")), ("title", models.CharField(max_length=200)), ], ) book_with_multiple_authors_through_attribution = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ( "authors", models.ManyToManyField( "testapp.Author", through="otherapp.Attribution" ), ), ("title", models.CharField(max_length=200)), ], ) book_indexes = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index(fields=["author", "title"], name="book_title_author_idx") ], }, ) book_unordered_indexes = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index(fields=["title", "author"], name="book_author_title_idx") ], }, ) book_foo_together = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("author", "title")}, "unique_together": {("author", "title")}, }, ) book_foo_together_2 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, "unique_together": {("title", "author")}, }, ) book_foo_together_3 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield")}, "unique_together": {("title", "newfield")}, }, ) book_foo_together_4 = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("newfield2", models.IntegerField()), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "newfield2")}, "unique_together": {("title", "newfield2")}, }, ) attribution = ModelState( "otherapp", "Attribution", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) edition = ModelState( "thirdapp", "Edition", [ ("id", models.AutoField(primary_key=True)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], ) custom_user = ModelState( "thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ], bases=(AbstractBaseUser,), ) custom_user_no_inherit = ModelState( "thirdapp", "CustomUser", [ ("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255)), ], ) aardvark = ModelState( "thirdapp", "Aardvark", [("id", models.AutoField(primary_key=True))] ) aardvark_testapp = ModelState( "testapp", "Aardvark", [("id", models.AutoField(primary_key=True))] ) aardvark_based_on_author = ModelState( "testapp", "Aardvark", [], bases=("testapp.Author",) ) aardvark_pk_fk_author = ModelState( "testapp", "Aardvark", [ ( "id", models.OneToOneField( "testapp.Author", models.CASCADE, primary_key=True ), ), ], ) knight = ModelState("eggs", "Knight", [("id", models.AutoField(primary_key=True))]) rabbit = ModelState( "eggs", "Rabbit", [ ("id", models.AutoField(primary_key=True)), ("knight", models.ForeignKey("eggs.Knight", models.CASCADE)), ("parent", models.ForeignKey("eggs.Rabbit", models.CASCADE)), ], { "unique_together": {("parent", "knight")}, "indexes": [ models.Index( fields=["parent", "knight"], name="rabbit_circular_fk_index" ) ], }, ) def repr_changes(self, changes, include_dependencies=False): output = "" for app_label, migrations_ in sorted(changes.items()): output += " %s:\n" % app_label for migration in migrations_: output += " %s\n" % migration.name for operation in migration.operations: output += " %s\n" % operation if include_dependencies: output += " Dependencies:\n" if migration.dependencies: for dep in migration.dependencies: output += " %s\n" % (dep,) else: output += " None\n" return output def assertNumberMigrations(self, changes, app_label, number): if len(changes.get(app_label, [])) != number: self.fail( "Incorrect number of migrations (%s) for %s (expected %s)\n%s" % ( len(changes.get(app_label, [])), app_label, number, self.repr_changes(changes), ) ) def assertMigrationDependencies(self, changes, app_label, position, dependencies): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if set(migration.dependencies) != set(dependencies): self.fail( "Migration dependencies mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, dependencies, self.repr_changes(changes, include_dependencies=True), ) ) def assertOperationTypes(self, changes, app_label, position, types): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] real_types = [ operation.__class__.__name__ for operation in migration.operations ] if types != real_types: self.fail( "Operation type mismatch for %s.%s (expected %s):\n%s" % ( app_label, migration.name, types, self.repr_changes(changes), ) ) def assertOperationAttributes( self, changes, app_label, position, operation_position, **attrs ): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail( "No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), ) ) operation = migration.operations[operation_position] for attr, value in attrs.items(): if getattr(operation, attr, None) != value: self.fail( "Attribute mismatch for %s.%s op #%s, %s (expected %r, got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(operation, attr, None), self.repr_changes(changes), ) ) def assertOperationFieldAttributes( self, changes, app_label, position, operation_position, **attrs ): if not changes.get(app_label): self.fail( "No migrations found for %s\n%s" % (app_label, self.repr_changes(changes)) ) if len(changes[app_label]) < position + 1: self.fail( "No migration at index %s for %s\n%s" % (position, app_label, self.repr_changes(changes)) ) migration = changes[app_label][position] if len(changes[app_label]) < position + 1: self.fail( "No operation at index %s for %s.%s\n%s" % ( operation_position, app_label, migration.name, self.repr_changes(changes), ) ) operation = migration.operations[operation_position] if not hasattr(operation, "field"): self.fail( "No field attribute for %s.%s op #%s." % ( app_label, migration.name, operation_position, ) ) field = operation.field for attr, value in attrs.items(): if getattr(field, attr, None) != value: self.fail( "Field attribute mismatch for %s.%s op #%s, field.%s (expected %r, " "got %r):\n%s" % ( app_label, migration.name, operation_position, attr, value, getattr(field, attr, None), self.repr_changes(changes), ) ) def make_project_state(self, model_states): "Shortcut to make ProjectStates from lists of predefined models" project_state = ProjectState() for model_state in model_states: project_state.add_model(model_state.clone()) return project_state def get_changes(self, before_states, after_states, questioner=None): if not isinstance(before_states, ProjectState): before_states = self.make_project_state(before_states) if not isinstance(after_states, ProjectState): after_states = self.make_project_state(after_states) return MigrationAutodetector( before_states, after_states, questioner, )._detect_changes() def test_arrange_for_graph(self): """Tests auto-naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency( "testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial"), ) graph.add_dependency( "testapp.0002_foobar", ("testapp", "0002_foobar"), ("otherapp", "0001_initial"), ) # Use project state to make a new migration change set before = self.make_project_state([self.publisher, self.other_pony]) after = self.make_project_state( [ self.author_empty, self.publisher, self.other_pony, self.other_stable, ] ) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph changes = autodetector.arrange_for_graph(changes, graph) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_author") self.assertEqual( changes["testapp"][0].dependencies, [("testapp", "0002_foobar")] ) self.assertEqual(changes["otherapp"][0].name, "0002_stable") self.assertEqual( changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")] ) def test_arrange_for_graph_with_multiple_initial(self): # Make a fake graph. graph = MigrationGraph() # Use project state to make a new migration change set. before = self.make_project_state([]) after = self.make_project_state( [self.author_with_book, self.book, self.attribution] ) autodetector = MigrationAutodetector( before, after, MigrationQuestioner({"ask_initial": True}) ) changes = autodetector._detect_changes() changes = autodetector.arrange_for_graph(changes, graph) self.assertEqual(changes["otherapp"][0].name, "0001_initial") self.assertEqual(changes["otherapp"][0].dependencies, []) self.assertEqual(changes["otherapp"][1].name, "0002_initial") self.assertCountEqual( changes["otherapp"][1].dependencies, [("testapp", "0001_initial"), ("otherapp", "0001_initial")], ) self.assertEqual(changes["testapp"][0].name, "0001_initial") self.assertEqual( changes["testapp"][0].dependencies, [("otherapp", "0001_initial")] ) def test_trim_apps(self): """ Trim does not remove dependencies but does remove unwanted apps. """ # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state( [self.author_empty, self.other_pony, self.other_stable, self.third_thing] ) autodetector = MigrationAutodetector( before, after, MigrationQuestioner({"ask_initial": True}) ) changes = autodetector._detect_changes() # Run through arrange_for_graph graph = MigrationGraph() changes = autodetector.arrange_for_graph(changes, graph) changes["testapp"][0].dependencies.append(("otherapp", "0001_initial")) changes = autodetector._trim_to_apps(changes, {"testapp"}) # Make sure there's the right set of migrations self.assertEqual(changes["testapp"][0].name, "0001_initial") self.assertEqual(changes["otherapp"][0].name, "0001_initial") self.assertNotIn("thirdapp", changes) def test_custom_migration_name(self): """Tests custom naming of migrations for graph matching.""" # Make a fake graph graph = MigrationGraph() graph.add_node(("testapp", "0001_initial"), None) graph.add_node(("testapp", "0002_foobar"), None) graph.add_node(("otherapp", "0001_initial"), None) graph.add_dependency( "testapp.0002_foobar", ("testapp", "0002_foobar"), ("testapp", "0001_initial"), ) # Use project state to make a new migration change set before = self.make_project_state([]) after = self.make_project_state( [self.author_empty, self.other_pony, self.other_stable] ) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Run through arrange_for_graph migration_name = "custom_name" changes = autodetector.arrange_for_graph(changes, graph, migration_name) # Make sure there's a new name, deps match, etc. self.assertEqual(changes["testapp"][0].name, "0003_%s" % migration_name) self.assertEqual( changes["testapp"][0].dependencies, [("testapp", "0002_foobar")] ) self.assertEqual(changes["otherapp"][0].name, "0002_%s" % migration_name) self.assertEqual( changes["otherapp"][0].dependencies, [("otherapp", "0001_initial")] ) def test_new_model(self): """Tests autodetection of new models.""" changes = self.get_changes([], [self.other_pony_food]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Pony") self.assertEqual( [name for name, mgr in changes["otherapp"][0].operations[0].managers], ["food_qs", "food_mgr", "food_mgr_kwargs"], ) def test_old_model(self): """Tests deletion of old models.""" changes = self.get_changes([self.author_empty], []) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") def test_add_field(self): """Tests autodetection of new fields.""" changes = self.get_changes([self.author_empty], [self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_date_fields_with_auto_now_not_asking_for_default( self, mocked_ask_method ): changes = self.get_changes( [self.author_empty], [self.author_dates_of_birth_auto_now] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AddField", "AddField"] ) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now=True) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_date_fields_with_auto_now_add_not_asking_for_null_addition( self, mocked_ask_method ): changes = self.get_changes( [self.author_empty], [self.author_dates_of_birth_auto_now_add] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AddField", "AddField"] ) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now_add=True) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_auto_now_add_addition" ) def test_add_date_fields_with_auto_now_add_asking_for_default( self, mocked_ask_method ): changes = self.get_changes( [self.author_empty], [self.author_dates_of_birth_auto_now_add] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AddField", "AddField"] ) self.assertOperationFieldAttributes(changes, "testapp", 0, 0, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 1, auto_now_add=True) self.assertOperationFieldAttributes(changes, "testapp", 0, 2, auto_now_add=True) self.assertEqual(mocked_ask_method.call_count, 3) def test_remove_field(self): """Tests autodetection of removed fields.""" changes = self.get_changes([self.author_name], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") def test_alter_field(self): """Tests autodetection of new fields.""" changes = self.get_changes([self.author_name], [self.author_name_longer]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=True ) def test_supports_functools_partial(self): def _content_file_name(instance, filename, key, **kwargs): return "{}/{}".format(instance, filename) def content_file_name(key, **kwargs): return functools.partial(_content_file_name, key, **kwargs) # An unchanged partial reference. before = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("file") ), ), ], ) ] after = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("file") ), ), ], ) ] changes = self.get_changes(before, after) self.assertNumberMigrations(changes, "testapp", 0) # A changed partial reference. args_changed = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("other-file") ), ), ], ) ] changes = self.get_changes(before, args_changed) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) # Can't use assertOperationFieldAttributes because we need the # deconstructed version, i.e., the exploded func/args/keywords rather # than the partial: we don't care if it's not the same instance of the # partial, only if it's the same source function, args, and keywords. value = changes["testapp"][0].operations[0].field.upload_to self.assertEqual( (_content_file_name, ("other-file",), {}), (value.func, value.args, value.keywords), ) kwargs_changed = [ ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "file", models.FileField( max_length=200, upload_to=content_file_name("file", spam="eggs"), ), ), ], ) ] changes = self.get_changes(before, kwargs_changed) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) value = changes["testapp"][0].operations[0].field.upload_to self.assertEqual( (_content_file_name, ("file",), {"spam": "eggs"}), (value.func, value.args, value.keywords), ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_alter_field_to_not_null_with_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name_default]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=True ) self.assertOperationFieldAttributes( changes, "testapp", 0, 0, default="Ada Lovelace" ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration", return_value=models.NOT_PROVIDED, ) def test_alter_field_to_not_null_without_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name]) self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=True ) self.assertOperationFieldAttributes( changes, "testapp", 0, 0, default=models.NOT_PROVIDED ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_alteration", return_value="Some Name", ) def test_alter_field_to_not_null_oneoff_default(self, mocked_ask_method): """ #23609 - Tests autodetection of nullable to non-nullable alterations. """ changes = self.get_changes([self.author_name_null], [self.author_name]) self.assertEqual(mocked_ask_method.call_count, 1) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="name", preserve_default=False ) self.assertOperationFieldAttributes( changes, "testapp", 0, 0, default="Some Name" ) def test_rename_field(self): """Tests autodetection of renamed fields.""" changes = self.get_changes( [self.author_name], [self.author_name_renamed], MigrationQuestioner({"ask_rename": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="name", new_name="names" ) def test_rename_field_foreign_key_to_field(self): before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField(unique=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ( "foo", models.ForeignKey("app.Foo", models.CASCADE, to_field="field"), ), ], ), ] after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("renamed_field", models.IntegerField(unique=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ( "foo", models.ForeignKey( "app.Foo", models.CASCADE, to_field="renamed_field" ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) # Right number/type of migrations? self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, old_name="field", new_name="renamed_field" ) def test_rename_foreign_object_fields(self): fields = ("first", "second") renamed_fields = ("first_renamed", "second_renamed") before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ], options={"unique_together": {fields}}, ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ( "foo", models.ForeignObject( "app.Foo", models.CASCADE, from_fields=fields, to_fields=fields, ), ), ], ), ] # Case 1: to_fields renames. after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("first_renamed", models.IntegerField()), ("second_renamed", models.IntegerField()), ], options={"unique_together": {renamed_fields}}, ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ( "foo", models.ForeignObject( "app.Foo", models.CASCADE, from_fields=fields, to_fields=renamed_fields, ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes( changes, "app", 0, ["RenameField", "RenameField", "AlterUniqueTogether"] ) self.assertOperationAttributes( changes, "app", 0, 0, model_name="foo", old_name="first", new_name="first_renamed", ) self.assertOperationAttributes( changes, "app", 0, 1, model_name="foo", old_name="second", new_name="second_renamed", ) # Case 2: from_fields renames. after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("first", models.IntegerField()), ("second", models.IntegerField()), ], options={"unique_together": {fields}}, ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("first_renamed", models.IntegerField()), ("second_renamed", models.IntegerField()), ( "foo", models.ForeignObject( "app.Foo", models.CASCADE, from_fields=renamed_fields, to_fields=fields, ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["RenameField", "RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, model_name="bar", old_name="first", new_name="first_renamed", ) self.assertOperationAttributes( changes, "app", 0, 1, model_name="bar", old_name="second", new_name="second_renamed", ) def test_rename_referenced_primary_key(self): before = [ ModelState( "app", "Foo", [ ("id", models.CharField(primary_key=True, serialize=False)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("foo", models.ForeignKey("app.Foo", models.CASCADE)), ], ), ] after = [ ModelState( "app", "Foo", [("renamed_id", models.CharField(primary_key=True, serialize=False))], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("foo", models.ForeignKey("app.Foo", models.CASCADE)), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, old_name="id", new_name="renamed_id" ) def test_rename_field_preserved_db_column(self): """ RenameField is used if a field is renamed and db_column equal to the old field's column is added. """ before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField()), ], ), ] after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ("renamed_field", models.IntegerField(db_column="field")), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["AlterField", "RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, model_name="foo", name="field", ) self.assertEqual( changes["app"][0].operations[0].field.deconstruct(), ( "field", "django.db.models.IntegerField", [], {"db_column": "field"}, ), ) self.assertOperationAttributes( changes, "app", 0, 1, model_name="foo", old_name="field", new_name="renamed_field", ) def test_rename_related_field_preserved_db_column(self): before = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ("foo", models.ForeignKey("app.Foo", models.CASCADE)), ], ), ] after = [ ModelState( "app", "Foo", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "app", "Bar", [ ("id", models.AutoField(primary_key=True)), ( "renamed_foo", models.ForeignKey( "app.Foo", models.CASCADE, db_column="foo_id" ), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename": True}) ) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["AlterField", "RenameField"]) self.assertOperationAttributes( changes, "app", 0, 0, model_name="bar", name="foo", ) self.assertEqual( changes["app"][0].operations[0].field.deconstruct(), ( "foo", "django.db.models.ForeignKey", [], {"to": "app.foo", "on_delete": models.CASCADE, "db_column": "foo_id"}, ), ) self.assertOperationAttributes( changes, "app", 0, 1, model_name="bar", old_name="foo", new_name="renamed_foo", ) def test_rename_field_with_renamed_model(self): changes = self.get_changes( [self.author_name], [ ModelState( "testapp", "RenamedAuthor", [ ("id", models.AutoField(primary_key=True)), ("renamed_name", models.CharField(max_length=200)), ], ), ], MigrationQuestioner({"ask_rename_model": True, "ask_rename": True}), ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel", "RenameField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="RenamedAuthor", ) self.assertOperationAttributes( changes, "testapp", 0, 1, old_name="name", new_name="renamed_name", ) def test_rename_model(self): """Tests autodetection of renamed models.""" changes = self.get_changes( [self.author_with_book, self.book], [self.author_renamed_with_book, self.book_with_author_renamed], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="Writer" ) # Now that RenameModel handles related fields too, there should be # no AlterField for the related field. self.assertNumberMigrations(changes, "otherapp", 0) def test_rename_model_case(self): """ Model name is case-insensitive. Changing case doesn't lead to any autodetected operations. """ author_renamed = ModelState( "testapp", "author", [ ("id", models.AutoField(primary_key=True)), ], ) changes = self.get_changes( [self.author_empty, self.book], [author_renamed, self.book], questioner=MigrationQuestioner({"ask_rename_model": True}), ) self.assertNumberMigrations(changes, "testapp", 0) self.assertNumberMigrations(changes, "otherapp", 0) def test_renamed_referenced_m2m_model_case(self): publisher_renamed = ModelState( "testapp", "publisher", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], ) changes = self.get_changes( [self.publisher, self.author_with_m2m], [publisher_renamed, self.author_with_m2m], questioner=MigrationQuestioner({"ask_rename_model": True}), ) self.assertNumberMigrations(changes, "testapp", 0) self.assertNumberMigrations(changes, "otherapp", 0) def test_rename_m2m_through_model(self): """ Tests autodetection of renamed models that are used in M2M relations as through models. """ changes = self.get_changes( [self.author_with_m2m_through, self.publisher, self.contract], [ self.author_with_renamed_m2m_through, self.publisher, self.contract_renamed, ], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Contract", new_name="Deal" ) def test_rename_model_with_renamed_rel_field(self): """ Tests autodetection of renamed models while simultaneously renaming one of the fields that relate to the renamed model. """ changes = self.get_changes( [self.author_with_book, self.book], [self.author_renamed_with_book, self.book_with_field_and_author_renamed], MigrationQuestioner({"ask_rename": True, "ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="Writer" ) # Right number/type of migrations for related field rename? # Alter is already taken care of. self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RenameField"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, old_name="author", new_name="writer" ) def test_rename_model_with_fks_in_different_position(self): """ #24537 - The order of fields in a model does not influence the RenameModel detection. """ before = [ ModelState( "testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "testapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ("some_label", models.CharField(max_length=255)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ], ), ] after = [ ModelState( "testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "testapp", "RenamedEntityB", [ ("id", models.AutoField(primary_key=True)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ("some_label", models.CharField(max_length=255)), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename_model": True}) ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="EntityB", new_name="RenamedEntityB" ) def test_rename_model_reverse_relation_dependencies(self): """ The migration to rename a model pointed to by a foreign key in another app must run after the other app's migration that adds the foreign key with model's original name. Therefore, the renaming migration has a dependency on that other migration. """ before = [ ModelState( "testapp", "EntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "otherapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ("entity_a", models.ForeignKey("testapp.EntityA", models.CASCADE)), ], ), ] after = [ ModelState( "testapp", "RenamedEntityA", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "otherapp", "EntityB", [ ("id", models.AutoField(primary_key=True)), ( "entity_a", models.ForeignKey("testapp.RenamedEntityA", models.CASCADE), ), ], ), ] changes = self.get_changes( before, after, MigrationQuestioner({"ask_rename_model": True}) ) self.assertNumberMigrations(changes, "testapp", 1) self.assertMigrationDependencies( changes, "testapp", 0, [("otherapp", "__first__")] ) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="EntityA", new_name="RenamedEntityA" ) def test_fk_dependency(self): """Having a ForeignKey automatically adds a dependency.""" # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (author), # thirdapp (edition) depends on otherapp (book) changes = self.get_changes([], [self.author_name, self.book, self.edition]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertMigrationDependencies(changes, "testapp", 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("testapp", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes(changes, "thirdapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="Edition") self.assertMigrationDependencies( changes, "thirdapp", 0, [("otherapp", "auto_1")] ) def test_proxy_fk_dependency(self): """FK dependencies still work on proxy models.""" # Note that testapp (author) has no dependencies, # otherapp (book) depends on testapp (authorproxy) changes = self.get_changes( [], [self.author_empty, self.author_proxy_third, self.book_proxy_fk] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertMigrationDependencies(changes, "testapp", 0, []) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("thirdapp", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes(changes, "thirdapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="AuthorProxy") self.assertMigrationDependencies( changes, "thirdapp", 0, [("testapp", "auto_1")] ) def test_same_app_no_fk_dependency(self): """ A migration with a FK between two models of the same app does not have a dependency to itself. """ changes = self.get_changes([], [self.author_with_publisher, self.publisher]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Author") self.assertMigrationDependencies(changes, "testapp", 0, []) def test_circular_fk_dependency(self): """ Having a circular ForeignKey dependency automatically resolves the situation into 2 migrations on one side and 1 on the other. """ changes = self.get_changes( [], [self.author_with_book, self.book, self.publisher_with_book] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Author") self.assertMigrationDependencies( changes, "testapp", 0, [("otherapp", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 2) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationTypes(changes, "otherapp", 1, ["AddField"]) self.assertMigrationDependencies(changes, "otherapp", 0, []) self.assertMigrationDependencies( changes, "otherapp", 1, [("otherapp", "auto_1"), ("testapp", "auto_1")] ) # both split migrations should be `initial` self.assertTrue(changes["otherapp"][0].initial) self.assertTrue(changes["otherapp"][1].initial) def test_same_app_circular_fk_dependency(self): """ A migration with a FK between two models of the same app does not have a dependency to itself. """ changes = self.get_changes( [], [self.author_with_publisher, self.publisher_with_author] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "CreateModel", "AddField"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher") self.assertMigrationDependencies(changes, "testapp", 0, []) def test_same_app_circular_fk_dependency_with_unique_together_and_indexes(self): """ #22275 - A migration with circular FK dependency does not try to create unique together constraint and indexes before creating all required fields first. """ changes = self.get_changes([], [self.knight, self.rabbit]) # Right number/type of migrations? self.assertNumberMigrations(changes, "eggs", 1) self.assertOperationTypes( changes, "eggs", 0, ["CreateModel", "CreateModel", "AddIndex", "AlterUniqueTogether"], ) self.assertNotIn("unique_together", changes["eggs"][0].operations[0].options) self.assertNotIn("unique_together", changes["eggs"][0].operations[1].options) self.assertMigrationDependencies(changes, "eggs", 0, []) def test_alter_db_table_add(self): """Tests detection for adding db_table in model's options.""" changes = self.get_changes( [self.author_empty], [self.author_with_db_table_options] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTable"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", table="author_one" ) def test_alter_db_table_change(self): """Tests detection for changing db_table in model's options'.""" changes = self.get_changes( [self.author_with_db_table_options], [self.author_with_new_db_table_options] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTable"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", table="author_two" ) def test_alter_db_table_remove(self): """Tests detection for removing db_table in model's options.""" changes = self.get_changes( [self.author_with_db_table_options], [self.author_empty] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelTable"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", table=None ) def test_alter_db_table_no_changes(self): """ Alter_db_table doesn't generate a migration if no changes have been made. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_with_db_table_options] ) # Right number of migrations? self.assertEqual(len(changes), 0) def test_keep_db_table_with_model_change(self): """ Tests when model changes but db_table stays as-is, autodetector must not create more than one operation. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_renamed_with_db_table_options], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RenameModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor" ) def test_alter_db_table_with_model_change(self): """ Tests when model and db_table changes, autodetector must create two operations. """ changes = self.get_changes( [self.author_with_db_table_options], [self.author_renamed_with_new_db_table_options], MigrationQuestioner({"ask_rename_model": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RenameModel", "AlterModelTable"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, old_name="Author", new_name="NewAuthor" ) self.assertOperationAttributes( changes, "testapp", 0, 1, name="newauthor", table="author_three" ) def test_identical_regex_doesnt_alter(self): from_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[ RegexValidator( re.compile("^[-a-zA-Z0-9_]+\\Z"), "Enter a valid “slug” consisting of letters, numbers, " "underscores or hyphens.", "invalid", ) ], ), ) ], ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))], ) changes = self.get_changes([from_state], [to_state]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 0) def test_different_regex_does_alter(self): from_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[ RegexValidator( re.compile("^[a-z]+\\Z", 32), "Enter a valid “slug” consisting of letters, numbers, " "underscores or hyphens.", "invalid", ) ], ), ) ], ) to_state = ModelState( "testapp", "model", [("id", models.AutoField(primary_key=True, validators=[validate_slug]))], ) changes = self.get_changes([from_state], [to_state]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) def test_alter_regex_string_to_compiled_regex(self): regex_string = "^[a-z]+$" from_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[RegexValidator(regex_string)] ), ) ], ) to_state = ModelState( "testapp", "model", [ ( "id", models.AutoField( primary_key=True, validators=[RegexValidator(re.compile(regex_string))], ), ) ], ) changes = self.get_changes([from_state], [to_state]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) def test_empty_foo_together(self): """ #23452 - Empty unique/index_together shouldn't generate a migration. """ # Explicitly testing for not specified, since this is the case after # a CreateModel operation w/o any definition on the original model model_state_not_specified = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))] ) # Explicitly testing for None, since this was the issue in #23452 after # an AlterFooTogether operation with e.g. () as value model_state_none = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))], { "index_together": None, "unique_together": None, }, ) # Explicitly testing for the empty set, since we now always have sets. # During removal (('col1', 'col2'),) --> () this becomes set([]) model_state_empty = ModelState( "a", "model", [("id", models.AutoField(primary_key=True))], { "index_together": set(), "unique_together": set(), }, ) def test(from_state, to_state, msg): changes = self.get_changes([from_state], [to_state]) if changes: ops = ", ".join( o.__class__.__name__ for o in changes["a"][0].operations ) self.fail("Created operation(s) %s from %s" % (ops, msg)) tests = ( ( model_state_not_specified, model_state_not_specified, '"not specified" to "not specified"', ), (model_state_not_specified, model_state_none, '"not specified" to "None"'), ( model_state_not_specified, model_state_empty, '"not specified" to "empty"', ), (model_state_none, model_state_not_specified, '"None" to "not specified"'), (model_state_none, model_state_none, '"None" to "None"'), (model_state_none, model_state_empty, '"None" to "empty"'), ( model_state_empty, model_state_not_specified, '"empty" to "not specified"', ), (model_state_empty, model_state_none, '"empty" to "None"'), (model_state_empty, model_state_empty, '"empty" to "empty"'), ) for t in tests: test(*t) def test_create_model_with_indexes(self): """Test creation of new model with indexes already defined.""" author = ModelState( "otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], { "indexes": [ models.Index(fields=["name"], name="create_model_with_indexes_idx") ] }, ) changes = self.get_changes([], [author]) added_index = models.Index( fields=["name"], name="create_model_with_indexes_idx" ) # Right number of migrations? self.assertEqual(len(changes["otherapp"]), 1) # Right number of actions? migration = changes["otherapp"][0] self.assertEqual(len(migration.operations), 2) # Right actions order? self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel", "AddIndex"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Author") self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="author", index=added_index ) def test_add_indexes(self): """Test change detection of new indexes.""" changes = self.get_changes( [self.author_empty, self.book], [self.author_empty, self.book_indexes] ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AddIndex"]) added_index = models.Index( fields=["author", "title"], name="book_title_author_idx" ) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", index=added_index ) def test_remove_indexes(self): """Test change detection of removed indexes.""" changes = self.get_changes( [self.author_empty, self.book_indexes], [self.author_empty, self.book] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RemoveIndex"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", name="book_title_author_idx" ) def test_rename_indexes(self): book_renamed_indexes = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index( fields=["author", "title"], name="renamed_book_title_author_idx" ) ], }, ) changes = self.get_changes( [self.author_empty, self.book_indexes], [self.author_empty, book_renamed_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RenameIndex"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", new_name="renamed_book_title_author_idx", old_name="book_title_author_idx", ) def test_rename_index_together_to_index(self): changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["RenameIndex", "AlterUniqueTogether"] ) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", new_name="book_title_author_idx", old_fields=("author", "title"), ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", unique_together=set(), ) def test_rename_index_together_to_index_extra_options(self): # Indexes with extra options don't match indexes in index_together. book_partial_index = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "indexes": [ models.Index( fields=["author", "title"], condition=models.Q(title__startswith="The"), name="book_title_author_idx", ) ], }, ) changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, book_partial_index], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether", "AddIndex"], ) def test_rename_index_together_to_index_order_fields(self): # Indexes with reordered fields don't match indexes in index_together. changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book_unordered_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether", "AddIndex"], ) def test_order_fields_indexes(self): """Test change detection of reordering of fields in indexes.""" changes = self.get_changes( [self.author_empty, self.book_indexes], [self.author_empty, self.book_unordered_indexes], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["RemoveIndex", "AddIndex"]) self.assertOperationAttributes( changes, "otherapp", 0, 0, model_name="book", name="book_title_author_idx" ) added_index = models.Index( fields=["title", "author"], name="book_author_title_idx" ) self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="book", index=added_index ) def test_create_model_with_check_constraint(self): """Test creation of new model with constraints already defined.""" author = ModelState( "otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], { "constraints": [ models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) ] }, ) changes = self.get_changes([], [author]) added_constraint = models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) # Right number of migrations? self.assertEqual(len(changes["otherapp"]), 1) # Right number of actions? migration = changes["otherapp"][0] self.assertEqual(len(migration.operations), 2) # Right actions order? self.assertOperationTypes( changes, "otherapp", 0, ["CreateModel", "AddConstraint"] ) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Author") self.assertOperationAttributes( changes, "otherapp", 0, 1, model_name="author", constraint=added_constraint ) def test_add_constraints(self): """Test change detection of new constraints.""" changes = self.get_changes( [self.author_name], [self.author_name_check_constraint] ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddConstraint"]) added_constraint = models.CheckConstraint( check=models.Q(name__contains="Bob"), name="name_contains_bob" ) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", constraint=added_constraint ) def test_remove_constraints(self): """Test change detection of removed constraints.""" changes = self.get_changes( [self.author_name_check_constraint], [self.author_name] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveConstraint"]) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", name="name_contains_bob" ) def test_add_foo_together(self): """Tests index/unique_together detection.""" changes = self.get_changes( [self.author_empty, self.book], [self.author_empty, self.book_foo_together] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether"] ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together={("author", "title")}, ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", index_together={("author", "title")} ) def test_remove_foo_together(self): """Tests index/unique_together detection.""" changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether"] ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together=set() ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", index_together=set() ) def test_foo_together_remove_fk(self): """Tests unique_together and field removal detection & ordering""" changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book_with_no_author], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AlterUniqueTogether", "AlterIndexTogether", "RemoveField"], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together=set() ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", index_together=set() ) self.assertOperationAttributes( changes, "otherapp", 0, 2, model_name="book", name="author" ) def test_foo_together_no_changes(self): """ index/unique_together doesn't generate a migration if no changes have been made. """ changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book_foo_together], ) # Right number of migrations? self.assertEqual(len(changes), 0) def test_foo_together_ordering(self): """ index/unique_together also triggers on ordering changes. """ changes = self.get_changes( [self.author_empty, self.book_foo_together], [self.author_empty, self.book_foo_together_2], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, [ "AlterUniqueTogether", "AlterIndexTogether", ], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together={("title", "author")}, ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", index_together={("title", "author")}, ) def test_add_field_and_foo_together(self): """ Added fields will be created before using them in index/unique_together. """ changes = self.get_changes( [self.author_empty, self.book], [self.author_empty, self.book_foo_together_3], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["AddField", "AlterUniqueTogether", "AlterIndexTogether"], ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", unique_together={("title", "newfield")}, ) self.assertOperationAttributes( changes, "otherapp", 0, 2, name="book", index_together={("title", "newfield")}, ) def test_create_model_and_unique_together(self): author = ModelState( "otherapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ], ) book_with_author = ModelState( "otherapp", "Book", [ ("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("otherapp.Author", models.CASCADE)), ("title", models.CharField(max_length=200)), ], { "index_together": {("title", "author")}, "unique_together": {("title", "author")}, }, ) changes = self.get_changes( [self.book_with_no_author], [author, book_with_author] ) # Right number of migrations? self.assertEqual(len(changes["otherapp"]), 1) # Right number of actions? migration = changes["otherapp"][0] self.assertEqual(len(migration.operations), 4) # Right actions order? self.assertOperationTypes( changes, "otherapp", 0, ["CreateModel", "AddField", "AlterUniqueTogether", "AlterIndexTogether"], ) def test_remove_field_and_foo_together(self): """ Removed fields will be removed after updating index/unique_together. """ changes = self.get_changes( [self.author_empty, self.book_foo_together_3], [self.author_empty, self.book_foo_together], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, [ "AlterUniqueTogether", "AlterIndexTogether", "RemoveField", ], ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="book", unique_together={("author", "title")}, ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", index_together={("author", "title")}, ) self.assertOperationAttributes( changes, "otherapp", 0, 2, model_name="book", name="newfield", ) def test_alter_field_and_foo_together(self): """Fields are altered after deleting some index/unique_together.""" initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField(db_index=True)), ], { "unique_together": {("name",)}, }, ) author_reversed_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200, unique=True)), ("age", models.IntegerField()), ], { "index_together": {("age",)}, }, ) changes = self.get_changes([initial_author], [author_reversed_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "AlterUniqueTogether", "AlterField", "AlterField", "AlterIndexTogether", ], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", unique_together=set(), ) self.assertOperationAttributes( changes, "testapp", 0, 1, model_name="author", name="age", ) self.assertOperationAttributes( changes, "testapp", 0, 2, model_name="author", name="name", ) self.assertOperationAttributes( changes, "testapp", 0, 3, name="author", index_together={("age",)}, ) def test_partly_alter_foo_together(self): initial_author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "unique_together": {("name",), ("age",)}, "index_together": {("name",)}, }, ) author_reversed_constraints = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("age", models.IntegerField()), ], { "unique_together": {("age",)}, "index_together": {("name",), ("age",)}, }, ) changes = self.get_changes([initial_author], [author_reversed_constraints]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "AlterUniqueTogether", "AlterIndexTogether", ], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", unique_together={("age",)}, ) self.assertOperationAttributes( changes, "testapp", 0, 1, name="author", index_together={("name",), ("age",)}, ) def test_rename_field_and_foo_together(self): """Fields are renamed before updating index/unique_together.""" changes = self.get_changes( [self.author_empty, self.book_foo_together_3], [self.author_empty, self.book_foo_together_4], MigrationQuestioner({"ask_rename": True}), ) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, [ "RenameField", "AlterUniqueTogether", "AlterIndexTogether", ], ) self.assertOperationAttributes( changes, "otherapp", 0, 1, name="book", unique_together={("title", "newfield2")}, ) self.assertOperationAttributes( changes, "otherapp", 0, 2, name="book", index_together={("title", "newfield2")}, ) def test_proxy(self): """The autodetector correctly deals with proxy models.""" # First, we test adding a proxy model changes = self.get_changes( [self.author_empty], [self.author_empty, self.author_proxy] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="AuthorProxy", options={"proxy": True, "indexes": [], "constraints": []}, ) # Now, we test turning a proxy model into a non-proxy model # It should delete the proxy then make the real one changes = self.get_changes( [self.author_empty, self.author_proxy], [self.author_empty, self.author_proxy_notproxy], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="AuthorProxy") self.assertOperationAttributes( changes, "testapp", 0, 1, name="AuthorProxy", options={} ) def test_proxy_non_model_parent(self): class Mixin: pass author_proxy_non_model_parent = ModelState( "testapp", "AuthorProxy", [], {"proxy": True}, (Mixin, "testapp.author"), ) changes = self.get_changes( [self.author_empty], [self.author_empty, author_proxy_non_model_parent], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="AuthorProxy", options={"proxy": True, "indexes": [], "constraints": []}, bases=(Mixin, "testapp.author"), ) def test_proxy_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on proxy models. """ # First, we test the default pk field name changes = self.get_changes( [], [self.author_empty, self.author_proxy_third, self.book_proxy_fk] ) # The model the FK is pointing from and to. self.assertEqual( changes["otherapp"][0].operations[0].fields[2][1].remote_field.model, "thirdapp.AuthorProxy", ) # Now, we test the custom pk field name changes = self.get_changes( [], [self.author_custom_pk, self.author_proxy_third, self.book_proxy_fk] ) # The model the FK is pointing from and to. self.assertEqual( changes["otherapp"][0].operations[0].fields[2][1].remote_field.model, "thirdapp.AuthorProxy", ) def test_proxy_to_mti_with_fk_to_proxy(self): # First, test the pk table and field name. to_state = self.make_project_state( [self.author_empty, self.author_proxy_third, self.book_proxy_fk], ) changes = self.get_changes([], to_state) fk_field = changes["otherapp"][0].operations[0].fields[2][1] self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("testapp", "author"), ) self.assertEqual(fk_field.remote_field.model, "thirdapp.AuthorProxy") # Change AuthorProxy to use MTI. from_state = to_state.clone() to_state = self.make_project_state( [self.author_empty, self.author_proxy_third_notproxy, self.book_proxy_fk], ) changes = self.get_changes(from_state, to_state) # Right number/type of migrations for the AuthorProxy model? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes( changes, "thirdapp", 0, ["DeleteModel", "CreateModel"] ) # Right number/type of migrations for the Book model with a FK to # AuthorProxy? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterField"]) # otherapp should depend on thirdapp. self.assertMigrationDependencies( changes, "otherapp", 0, [("thirdapp", "auto_1")] ) # Now, test the pk table and field name. fk_field = changes["otherapp"][0].operations[0].field self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("thirdapp", "authorproxy"), ) self.assertEqual(fk_field.remote_field.model, "thirdapp.AuthorProxy") def test_proxy_to_mti_with_fk_to_proxy_proxy(self): # First, test the pk table and field name. to_state = self.make_project_state( [ self.author_empty, self.author_proxy, self.author_proxy_proxy, self.book_proxy_proxy_fk, ] ) changes = self.get_changes([], to_state) fk_field = changes["otherapp"][0].operations[0].fields[1][1] self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("testapp", "author"), ) self.assertEqual(fk_field.remote_field.model, "testapp.AAuthorProxyProxy") # Change AuthorProxy to use MTI. FK still points to AAuthorProxyProxy, # a proxy of AuthorProxy. from_state = to_state.clone() to_state = self.make_project_state( [ self.author_empty, self.author_proxy_notproxy, self.author_proxy_proxy, self.book_proxy_proxy_fk, ] ) changes = self.get_changes(from_state, to_state) # Right number/type of migrations for the AuthorProxy model? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel", "CreateModel"]) # Right number/type of migrations for the Book model with a FK to # AAuthorProxyProxy? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterField"]) # otherapp should depend on testapp. self.assertMigrationDependencies( changes, "otherapp", 0, [("testapp", "auto_1")] ) # Now, test the pk table and field name. fk_field = changes["otherapp"][0].operations[0].field self.assertEqual( to_state.get_concrete_model_key(fk_field.remote_field.model), ("testapp", "authorproxy"), ) self.assertEqual(fk_field.remote_field.model, "testapp.AAuthorProxyProxy") def test_unmanaged_create(self): """The autodetector correctly deals with managed models.""" # First, we test adding an unmanaged model changes = self.get_changes( [self.author_empty], [self.author_empty, self.author_unmanaged] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="AuthorUnmanaged", options={"managed": False} ) def test_unmanaged_delete(self): changes = self.get_changes( [self.author_empty, self.author_unmanaged], [self.author_empty] ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["DeleteModel"]) def test_unmanaged_to_managed(self): # Now, we test turning an unmanaged model into a managed model changes = self.get_changes( [self.author_empty, self.author_unmanaged], [self.author_empty, self.author_unmanaged_managed], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="authorunmanaged", options={} ) def test_managed_to_unmanaged(self): # Now, we turn managed to unmanaged. changes = self.get_changes( [self.author_empty, self.author_unmanaged_managed], [self.author_empty, self.author_unmanaged], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="authorunmanaged", options={"managed": False} ) def test_unmanaged_custom_pk(self): """ #23415 - The autodetector must correctly deal with custom FK on unmanaged models. """ # First, we test the default pk field name changes = self.get_changes([], [self.author_unmanaged_default_pk, self.book]) # The model the FK on the book model points to. fk_field = changes["otherapp"][0].operations[0].fields[2][1] self.assertEqual(fk_field.remote_field.model, "testapp.Author") # Now, we test the custom pk field name changes = self.get_changes([], [self.author_unmanaged_custom_pk, self.book]) # The model the FK on the book model points to. fk_field = changes["otherapp"][0].operations[0].fields[2][1] self.assertEqual(fk_field.remote_field.model, "testapp.Author") @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable(self): with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes( [self.custom_user], [self.custom_user, self.author_with_custom_user] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertMigrationDependencies( changes, "testapp", 0, [("__setting__", "AUTH_USER_MODEL")] ) def test_swappable_lowercase(self): model_state = ModelState( "testapp", "Document", [ ("id", models.AutoField(primary_key=True)), ( "owner", models.ForeignKey( settings.AUTH_USER_MODEL.lower(), models.CASCADE, ), ), ], ) with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes([], [model_state]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Document") self.assertMigrationDependencies( changes, "testapp", 0, [("__setting__", "AUTH_USER_MODEL")], ) @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable_many_to_many_model_case(self): document_lowercase = ModelState( "testapp", "Document", [ ("id", models.AutoField(primary_key=True)), ("owners", models.ManyToManyField(settings.AUTH_USER_MODEL.lower())), ], ) document = ModelState( "testapp", "Document", [ ("id", models.AutoField(primary_key=True)), ("owners", models.ManyToManyField(settings.AUTH_USER_MODEL)), ], ) with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes( [self.custom_user, document_lowercase], [self.custom_user, document], ) self.assertEqual(len(changes), 0) def test_swappable_changed(self): with isolate_lru_cache(apps.get_swappable_settings_name): before = self.make_project_state([self.custom_user, self.author_with_user]) with override_settings(AUTH_USER_MODEL="thirdapp.CustomUser"): after = self.make_project_state( [self.custom_user, self.author_with_custom_user] ) autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes() # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", name="user" ) fk_field = changes["testapp"][0].operations[0].field self.assertEqual(fk_field.remote_field.model, "thirdapp.CustomUser") def test_add_field_with_default(self): """#22030 - Adding a field with a default should work.""" changes = self.get_changes([self.author_empty], [self.author_name_default]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="name") def test_custom_deconstructible(self): """ Two instances which deconstruct to the same value aren't considered a change. """ changes = self.get_changes( [self.author_name_deconstructible_1], [self.author_name_deconstructible_2] ) # Right number of migrations? self.assertEqual(len(changes), 0) def test_deconstruct_field_kwarg(self): """Field instances are handled correctly by nested deconstruction.""" changes = self.get_changes( [self.author_name_deconstructible_3], [self.author_name_deconstructible_4] ) self.assertEqual(changes, {}) def test_deconstructible_list(self): """Nested deconstruction descends into lists.""" # When lists contain items that deconstruct to identical values, those lists # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). changes = self.get_changes( [self.author_name_deconstructible_list_1], [self.author_name_deconstructible_list_2], ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed lists should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_list_1], [self.author_name_deconstructible_list_3], ) self.assertEqual(len(changes), 1) def test_deconstructible_tuple(self): """Nested deconstruction descends into tuples.""" # When tuples contain items that deconstruct to identical values, those tuples # should be considered equal for the purpose of detecting state changes # (even if the original items are unequal). changes = self.get_changes( [self.author_name_deconstructible_tuple_1], [self.author_name_deconstructible_tuple_2], ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed tuples should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_tuple_1], [self.author_name_deconstructible_tuple_3], ) self.assertEqual(len(changes), 1) def test_deconstructible_dict(self): """Nested deconstruction descends into dict values.""" # When dicts contain items whose values deconstruct to identical values, # those dicts should be considered equal for the purpose of detecting # state changes (even if the original values are unequal). changes = self.get_changes( [self.author_name_deconstructible_dict_1], [self.author_name_deconstructible_dict_2], ) self.assertEqual(changes, {}) # Legitimate differences within the deconstructed dicts should be reported # as a change changes = self.get_changes( [self.author_name_deconstructible_dict_1], [self.author_name_deconstructible_dict_3], ) self.assertEqual(len(changes), 1) def test_nested_deconstructible_objects(self): """ Nested deconstruction is applied recursively to the args/kwargs of deconstructed objects. """ # If the items within a deconstructed object's args/kwargs have the same # deconstructed values - whether or not the items themselves are different # instances - then the object as a whole is regarded as unchanged. changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_2], ) self.assertEqual(changes, {}) # Differences that exist solely within the args list of a deconstructed object # should be reported as changes changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_changed_arg], ) self.assertEqual(len(changes), 1) # Additional args should also be reported as a change changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_extra_arg], ) self.assertEqual(len(changes), 1) # Differences that exist solely within the kwargs dict of a deconstructed object # should be reported as changes changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_changed_kwarg], ) self.assertEqual(len(changes), 1) # Additional kwargs should also be reported as a change changes = self.get_changes( [self.author_name_nested_deconstructible_1], [self.author_name_nested_deconstructible_extra_kwarg], ) self.assertEqual(len(changes), 1) def test_deconstruct_type(self): """ #22951 -- Uninstantiated classes with deconstruct are correctly returned by deep_deconstruct during serialization. """ author = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ( "name", models.CharField( max_length=200, # IntegerField intentionally not instantiated. default=models.IntegerField, ), ), ], ) changes = self.get_changes([], [author]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) def test_replace_string_with_foreignkey(self): """ #22300 - Adding an FK in the same "spot" as a deleted CharField should work. """ changes = self.get_changes( [self.author_with_publisher_string], [self.author_with_publisher, self.publisher], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "RemoveField", "AddField"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="publisher_name") self.assertOperationAttributes(changes, "testapp", 0, 2, name="publisher") def test_foreign_key_removed_before_target_model(self): """ Removing an FK and the model it targets in the same change must remove the FK field before the model to maintain consistency. """ changes = self.get_changes( [self.author_with_publisher, self.publisher], [self.author_name] ) # removes both the model and FK # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["RemoveField", "DeleteModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publisher") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_many_to_many(self, mocked_ask_method): """#22435 - Adding a ManyToManyField should not prompt for a default.""" changes = self.get_changes( [self.author_empty, self.publisher], [self.author_with_m2m, self.publisher] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publishers") def test_alter_many_to_many(self): changes = self.get_changes( [self.author_with_m2m, self.publisher], [self.author_with_m2m_blank, self.publisher], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="publishers") def test_create_with_through_model(self): """ Adding a m2m with a through model and the models that use it should be ordered correctly. """ changes = self.get_changes( [], [self.author_with_m2m_through, self.publisher, self.contract] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "CreateModel", "CreateModel", "CreateModel", "AddField", ], ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Publisher") self.assertOperationAttributes(changes, "testapp", 0, 2, name="Contract") self.assertOperationAttributes( changes, "testapp", 0, 3, model_name="author", name="publishers" ) def test_many_to_many_removed_before_through_model(self): """ Removing a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ changes = self.get_changes( [ self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution, ], [self.book_with_no_author, self.author_name], ) # Remove both the through model and ManyToMany # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["RemoveField", "DeleteModel"] ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="authors", model_name="book" ) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="Attribution") def test_many_to_many_removed_before_through_model_2(self): """ Removing a model that contains a ManyToManyField and the "through" model in the same change must remove the field before the model to maintain consistency. """ changes = self.get_changes( [ self.book_with_multiple_authors_through_attribution, self.author_name, self.attribution, ], [self.author_name], ) # Remove both the through model and ManyToMany # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes( changes, "otherapp", 0, ["RemoveField", "DeleteModel", "DeleteModel"] ) self.assertOperationAttributes( changes, "otherapp", 0, 0, name="authors", model_name="book" ) self.assertOperationAttributes(changes, "otherapp", 0, 1, name="Attribution") self.assertOperationAttributes(changes, "otherapp", 0, 2, name="Book") def test_m2m_w_through_multistep_remove(self): """ A model with a m2m field that specifies a "through" model cannot be removed in the same migration as that through model as the schema will pass through an inconsistent state. The autodetector should produce two migrations to avoid this issue. """ changes = self.get_changes( [self.author_with_m2m_through, self.publisher, self.contract], [self.publisher], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RemoveField", "RemoveField", "DeleteModel", "DeleteModel"], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", model_name="contract" ) self.assertOperationAttributes( changes, "testapp", 0, 1, name="publisher", model_name="contract" ) self.assertOperationAttributes(changes, "testapp", 0, 2, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 3, name="Contract") def test_concrete_field_changed_to_many_to_many(self): """ #23938 - Changing a concrete field into a ManyToManyField first removes the concrete field and then adds the m2m field. """ changes = self.get_changes( [self.author_with_former_m2m], [self.author_with_m2m, self.publisher] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "RemoveField", "AddField"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Publisher") self.assertOperationAttributes( changes, "testapp", 0, 1, name="publishers", model_name="author" ) self.assertOperationAttributes( changes, "testapp", 0, 2, name="publishers", model_name="author" ) def test_many_to_many_changed_to_concrete_field(self): """ #23938 - Changing a ManyToManyField into a concrete field first removes the m2m field and then adds the concrete field. """ changes = self.get_changes( [self.author_with_m2m, self.publisher], [self.author_with_former_m2m] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RemoveField", "AddField", "DeleteModel"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="publishers", model_name="author" ) self.assertOperationAttributes( changes, "testapp", 0, 1, name="publishers", model_name="author" ) self.assertOperationAttributes(changes, "testapp", 0, 2, name="Publisher") self.assertOperationFieldAttributes(changes, "testapp", 0, 1, max_length=100) def test_non_circular_foreignkey_dependency_removal(self): """ If two models with a ForeignKey from one to the other are removed at the same time, the autodetector should remove them in the correct order. """ changes = self.get_changes( [self.author_with_publisher, self.publisher_with_author], [] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["RemoveField", "DeleteModel", "DeleteModel"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", model_name="publisher" ) self.assertOperationAttributes(changes, "testapp", 0, 1, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 2, name="Publisher") def test_alter_model_options(self): """Changing a model's options should make a change.""" changes = self.get_changes([self.author_empty], [self.author_with_options]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, options={ "permissions": [("can_hire", "Can hire")], "verbose_name": "Authi", }, ) # Changing them back to empty should also make a change changes = self.get_changes([self.author_with_options], [self.author_empty]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", options={} ) def test_alter_model_options_proxy(self): """Changing a proxy model's options should also make a change.""" changes = self.get_changes( [self.author_proxy, self.author_empty], [self.author_proxy_options, self.author_empty], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterModelOptions"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="authorproxy", options={"verbose_name": "Super Author"}, ) def test_set_alter_order_with_respect_to(self): """Setting order_with_respect_to adds a field.""" changes = self.get_changes( [self.book, self.author_with_book], [self.book, self.author_with_book_order_wrt], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AlterOrderWithRespectTo"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", order_with_respect_to="book" ) def test_add_alter_order_with_respect_to(self): """ Setting order_with_respect_to when adding the FK too does things in the right order. """ changes = self.get_changes( [self.author_name], [self.book, self.author_with_book_order_wrt] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AddField", "AlterOrderWithRespectTo"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, model_name="author", name="book" ) self.assertOperationAttributes( changes, "testapp", 0, 1, name="author", order_with_respect_to="book" ) def test_remove_alter_order_with_respect_to(self): """ Removing order_with_respect_to when removing the FK too does things in the right order. """ changes = self.get_changes( [self.book, self.author_with_book_order_wrt], [self.author_name] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["AlterOrderWithRespectTo", "RemoveField"] ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="author", order_with_respect_to=None ) self.assertOperationAttributes( changes, "testapp", 0, 1, model_name="author", name="book" ) def test_add_model_order_with_respect_to(self): """ Setting order_with_respect_to when adding the whole model does things in the right order. """ changes = self.get_changes([], [self.book, self.author_with_book_order_wrt]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="Author", options={"order_with_respect_to": "book"}, ) self.assertNotIn( "_order", [name for name, field in changes["testapp"][0].operations[0].fields], ) def test_add_model_order_with_respect_to_index_foo_together(self): changes = self.get_changes( [], [ self.book, ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", "index_together": {("name", "_order")}, "unique_together": {("id", "_order")}, }, ), ], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "testapp", 0, 0, name="Author", options={ "order_with_respect_to": "book", "index_together": {("name", "_order")}, "unique_together": {("id", "_order")}, }, ) def test_add_model_order_with_respect_to_index_constraint(self): tests = [ ( "AddIndex", { "indexes": [ models.Index(fields=["_order"], name="book_order_idx"), ] }, ), ( "AddConstraint", { "constraints": [ models.CheckConstraint( check=models.Q(_order__gt=1), name="book_order_gt_1", ), ] }, ), ] for operation, extra_option in tests: with self.subTest(operation=operation): after = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", **extra_option, }, ) changes = self.get_changes([], [self.book, after]) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "CreateModel", operation, ], ) self.assertOperationAttributes( changes, "testapp", 0, 0, name="Author", options={"order_with_respect_to": "book"}, ) def test_set_alter_order_with_respect_to_index_constraint_foo_together(self): tests = [ ( "AddIndex", { "indexes": [ models.Index(fields=["_order"], name="book_order_idx"), ] }, ), ( "AddConstraint", { "constraints": [ models.CheckConstraint( check=models.Q(_order__gt=1), name="book_order_gt_1", ), ] }, ), ("AlterIndexTogether", {"index_together": {("name", "_order")}}), ("AlterUniqueTogether", {"unique_together": {("id", "_order")}}), ] for operation, extra_option in tests: with self.subTest(operation=operation): after = ModelState( "testapp", "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200)), ("book", models.ForeignKey("otherapp.Book", models.CASCADE)), ], options={ "order_with_respect_to": "book", **extra_option, }, ) changes = self.get_changes( [self.book, self.author_with_book], [self.book, after], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, [ "AlterOrderWithRespectTo", operation, ], ) def test_alter_model_managers(self): """ Changing the model managers adds a new operation. """ changes = self.get_changes([self.other_pony], [self.other_pony_food]) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterModelManagers"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="pony") self.assertEqual( [name for name, mgr in changes["otherapp"][0].operations[0].managers], ["food_qs", "food_mgr", "food_mgr_kwargs"], ) self.assertEqual( changes["otherapp"][0].operations[0].managers[1][1].args, ("a", "b", 1, 2) ) self.assertEqual( changes["otherapp"][0].operations[0].managers[2][1].args, ("x", "y", 3, 4) ) def test_swappable_first_inheritance(self): """Swappable models get their CreateModel first.""" changes = self.get_changes([], [self.custom_user, self.aardvark]) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes( changes, "thirdapp", 0, ["CreateModel", "CreateModel"] ) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="CustomUser") self.assertOperationAttributes(changes, "thirdapp", 0, 1, name="Aardvark") def test_default_related_name_option(self): model_state = ModelState( "app", "model", [ ("id", models.AutoField(primary_key=True)), ], options={"default_related_name": "related_name"}, ) changes = self.get_changes([], [model_state]) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["CreateModel"]) self.assertOperationAttributes( changes, "app", 0, 0, name="model", options={"default_related_name": "related_name"}, ) altered_model_state = ModelState( "app", "Model", [ ("id", models.AutoField(primary_key=True)), ], ) changes = self.get_changes([model_state], [altered_model_state]) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["AlterModelOptions"]) self.assertOperationAttributes(changes, "app", 0, 0, name="model", options={}) @override_settings(AUTH_USER_MODEL="thirdapp.CustomUser") def test_swappable_first_setting(self): """Swappable models get their CreateModel first.""" with isolate_lru_cache(apps.get_swappable_settings_name): changes = self.get_changes([], [self.custom_user_no_inherit, self.aardvark]) # Right number/type of migrations? self.assertNumberMigrations(changes, "thirdapp", 1) self.assertOperationTypes( changes, "thirdapp", 0, ["CreateModel", "CreateModel"] ) self.assertOperationAttributes(changes, "thirdapp", 0, 0, name="CustomUser") self.assertOperationAttributes(changes, "thirdapp", 0, 1, name="Aardvark") def test_bases_first(self): """Bases of other models come first.""" changes = self.get_changes( [], [self.aardvark_based_on_author, self.author_name] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Aardvark") def test_bases_first_mixed_case_app_label(self): app_label = "MiXedCaseApp" changes = self.get_changes( [], [ ModelState( app_label, "owner", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( app_label, "place", [ ("id", models.AutoField(primary_key=True)), ( "owner", models.ForeignKey("MiXedCaseApp.owner", models.CASCADE), ), ], ), ModelState(app_label, "restaurant", [], bases=("MiXedCaseApp.place",)), ], ) self.assertNumberMigrations(changes, app_label, 1) self.assertOperationTypes( changes, app_label, 0, [ "CreateModel", "CreateModel", "CreateModel", ], ) self.assertOperationAttributes(changes, app_label, 0, 0, name="owner") self.assertOperationAttributes(changes, app_label, 0, 1, name="place") self.assertOperationAttributes(changes, app_label, 0, 2, name="restaurant") def test_multiple_bases(self): """ Inheriting models doesn't move *_ptr fields into AddField operations. """ A = ModelState("app", "A", [("a_id", models.AutoField(primary_key=True))]) B = ModelState("app", "B", [("b_id", models.AutoField(primary_key=True))]) C = ModelState("app", "C", [], bases=("app.A", "app.B")) D = ModelState("app", "D", [], bases=("app.A", "app.B")) E = ModelState("app", "E", [], bases=("app.A", "app.B")) changes = self.get_changes([], [A, B, C, D, E]) # Right number/type of migrations? self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes( changes, "app", 0, ["CreateModel", "CreateModel", "CreateModel", "CreateModel", "CreateModel"], ) self.assertOperationAttributes(changes, "app", 0, 0, name="A") self.assertOperationAttributes(changes, "app", 0, 1, name="B") self.assertOperationAttributes(changes, "app", 0, 2, name="C") self.assertOperationAttributes(changes, "app", 0, 3, name="D") self.assertOperationAttributes(changes, "app", 0, 4, name="E") def test_proxy_bases_first(self): """Bases of proxies come first.""" changes = self.get_changes( [], [self.author_empty, self.author_proxy, self.author_proxy_proxy] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "CreateModel", "CreateModel"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="AuthorProxy") self.assertOperationAttributes( changes, "testapp", 0, 2, name="AAuthorProxyProxy" ) def test_pk_fk_included(self): """ A relation used as the primary key is kept as part of CreateModel. """ changes = self.get_changes([], [self.aardvark_pk_fk_author, self.author_name]) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel", "CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Author") self.assertOperationAttributes(changes, "testapp", 0, 1, name="Aardvark") def test_first_dependency(self): """ A dependency to an app with no migrations uses __first__. """ # Load graph loader = MigrationLoader(connection) before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = {"migrations"} autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("migrations", "__first__")] ) @override_settings(MIGRATION_MODULES={"migrations": "migrations.test_migrations"}) def test_last_dependency(self): """ A dependency to an app with existing migrations uses the last migration of that app. """ # Load graph loader = MigrationLoader(connection) before = self.make_project_state([]) after = self.make_project_state([self.book_migrations_fk]) after.real_apps = {"migrations"} autodetector = MigrationAutodetector(before, after) changes = autodetector._detect_changes(graph=loader.graph) # Right number/type of migrations? self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "otherapp", 0, 0, name="Book") self.assertMigrationDependencies( changes, "otherapp", 0, [("migrations", "0002_second")] ) def test_alter_fk_before_model_deletion(self): """ ForeignKeys are altered _before_ the model they used to refer to are deleted. """ changes = self.get_changes( [self.author_name, self.publisher_with_author], [self.aardvark_testapp, self.publisher_with_aardvark_author], ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes( changes, "testapp", 0, ["CreateModel", "AlterField", "DeleteModel"] ) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Aardvark") self.assertOperationAttributes(changes, "testapp", 0, 1, name="author") self.assertOperationAttributes(changes, "testapp", 0, 2, name="Author") def test_fk_dependency_other_app(self): """ #23100 - ForeignKeys correctly depend on other apps' models. """ changes = self.get_changes( [self.author_name, self.book], [self.author_with_book, self.book] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="book") self.assertMigrationDependencies( changes, "testapp", 0, [("otherapp", "__first__")] ) def test_alter_field_to_fk_dependency_other_app(self): changes = self.get_changes( [self.author_empty, self.book_with_no_author_fk], [self.author_empty, self.book], ) self.assertNumberMigrations(changes, "otherapp", 1) self.assertOperationTypes(changes, "otherapp", 0, ["AlterField"]) self.assertMigrationDependencies( changes, "otherapp", 0, [("testapp", "__first__")] ) def test_circular_dependency_mixed_addcreate(self): """ #23315 - The dependency resolver knows to put all CreateModel before AddField and not become unsolvable. """ address = ModelState( "a", "Address", [ ("id", models.AutoField(primary_key=True)), ("country", models.ForeignKey("b.DeliveryCountry", models.CASCADE)), ], ) person = ModelState( "a", "Person", [ ("id", models.AutoField(primary_key=True)), ], ) apackage = ModelState( "b", "APackage", [ ("id", models.AutoField(primary_key=True)), ("person", models.ForeignKey("a.Person", models.CASCADE)), ], ) country = ModelState( "b", "DeliveryCountry", [ ("id", models.AutoField(primary_key=True)), ], ) changes = self.get_changes([], [address, person, apackage, country]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 2) self.assertNumberMigrations(changes, "b", 1) self.assertOperationTypes(changes, "a", 0, ["CreateModel", "CreateModel"]) self.assertOperationTypes(changes, "a", 1, ["AddField"]) self.assertOperationTypes(changes, "b", 0, ["CreateModel", "CreateModel"]) @override_settings(AUTH_USER_MODEL="a.Tenant") def test_circular_dependency_swappable(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): tenant = ModelState( "a", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("b.Address", models.CASCADE)), ], bases=(AbstractBaseUser,), ) address = ModelState( "b", "Address", [ ("id", models.AutoField(primary_key=True)), ( "tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE), ), ], ) changes = self.get_changes([], [address, tenant]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 2) self.assertOperationTypes(changes, "a", 0, ["CreateModel"]) self.assertOperationTypes(changes, "a", 1, ["AddField"]) self.assertMigrationDependencies(changes, "a", 0, []) self.assertMigrationDependencies( changes, "a", 1, [("a", "auto_1"), ("b", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "b", 1) self.assertOperationTypes(changes, "b", 0, ["CreateModel"]) self.assertMigrationDependencies( changes, "b", 0, [("__setting__", "AUTH_USER_MODEL")] ) @override_settings(AUTH_USER_MODEL="b.Tenant") def test_circular_dependency_swappable2(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models but with the swappable not being the first migrated model. """ with isolate_lru_cache(apps.get_swappable_settings_name): address = ModelState( "a", "Address", [ ("id", models.AutoField(primary_key=True)), ( "tenant", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE), ), ], ) tenant = ModelState( "b", "Tenant", [ ("id", models.AutoField(primary_key=True)), ("primary_address", models.ForeignKey("a.Address", models.CASCADE)), ], bases=(AbstractBaseUser,), ) changes = self.get_changes([], [address, tenant]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 2) self.assertOperationTypes(changes, "a", 0, ["CreateModel"]) self.assertOperationTypes(changes, "a", 1, ["AddField"]) self.assertMigrationDependencies(changes, "a", 0, []) self.assertMigrationDependencies( changes, "a", 1, [("__setting__", "AUTH_USER_MODEL"), ("a", "auto_1")] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "b", 1) self.assertOperationTypes(changes, "b", 0, ["CreateModel"]) self.assertMigrationDependencies(changes, "b", 0, [("a", "auto_1")]) @override_settings(AUTH_USER_MODEL="a.Person") def test_circular_dependency_swappable_self(self): """ #23322 - The dependency resolver knows to explicitly resolve swappable models. """ with isolate_lru_cache(apps.get_swappable_settings_name): person = ModelState( "a", "Person", [ ("id", models.AutoField(primary_key=True)), ( "parent1", models.ForeignKey( settings.AUTH_USER_MODEL, models.CASCADE, related_name="children", ), ), ], ) changes = self.get_changes([], [person]) # Right number/type of migrations? self.assertNumberMigrations(changes, "a", 1) self.assertOperationTypes(changes, "a", 0, ["CreateModel"]) self.assertMigrationDependencies(changes, "a", 0, []) @override_settings(AUTH_USER_MODEL="a.User") def test_swappable_circular_multi_mti(self): with isolate_lru_cache(apps.get_swappable_settings_name): parent = ModelState( "a", "Parent", [("user", models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE))], ) child = ModelState("a", "Child", [], bases=("a.Parent",)) user = ModelState("a", "User", [], bases=(AbstractBaseUser, "a.Child")) changes = self.get_changes([], [parent, child, user]) self.assertNumberMigrations(changes, "a", 1) self.assertOperationTypes( changes, "a", 0, ["CreateModel", "CreateModel", "CreateModel", "AddField"] ) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition", side_effect=AssertionError("Should not have prompted for not null addition"), ) def test_add_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and blank `CharField` or `TextField` without default should not prompt for a default. """ changes = self.get_changes( [self.author_empty], [self.author_with_biography_blank] ) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0) @mock.patch( "django.db.migrations.questioner.MigrationQuestioner.ask_not_null_addition" ) def test_add_non_blank_textfield_and_charfield(self, mocked_ask_method): """ #23405 - Adding a NOT NULL and non-blank `CharField` or `TextField` without default should prompt for a default. """ changes = self.get_changes( [self.author_empty], [self.author_with_biography_non_blank] ) self.assertEqual(mocked_ask_method.call_count, 2) # Right number/type of migrations? self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["AddField", "AddField"]) self.assertOperationAttributes(changes, "testapp", 0, 0) def test_mti_inheritance_model_removal(self): Animal = ModelState( "app", "Animal", [ ("id", models.AutoField(primary_key=True)), ], ) Dog = ModelState("app", "Dog", [], bases=("app.Animal",)) changes = self.get_changes([Animal, Dog], [Animal]) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["DeleteModel"]) self.assertOperationAttributes(changes, "app", 0, 0, name="Dog") def test_add_model_with_field_removed_from_base_model(self): """ Removing a base field takes place before adding a new inherited model that has a field with the same name. """ before = [ ModelState( "app", "readable", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=200)), ], ), ] after = [ ModelState( "app", "readable", [ ("id", models.AutoField(primary_key=True)), ], ), ModelState( "app", "book", [ ("title", models.CharField(max_length=200)), ], bases=("app.readable",), ), ] changes = self.get_changes(before, after) self.assertNumberMigrations(changes, "app", 1) self.assertOperationTypes(changes, "app", 0, ["RemoveField", "CreateModel"]) self.assertOperationAttributes( changes, "app", 0, 0, name="title", model_name="readable" ) self.assertOperationAttributes(changes, "app", 0, 1, name="book") def test_parse_number(self): tests = [ ("no_number", None), ("0001_initial", 1), ("0002_model3", 2), ("0002_auto_20380101_1112", 2), ("0002_squashed_0003", 3), ("0002_model2_squashed_0003_other4", 3), ("0002_squashed_0003_squashed_0004", 4), ("0002_model2_squashed_0003_other4_squashed_0005_other6", 5), ("0002_custom_name_20380101_1112_squashed_0003_model", 3), ("2_squashed_4", 4), ] for migration_name, expected_number in tests: with self.subTest(migration_name=migration_name): self.assertEqual( MigrationAutodetector.parse_number(migration_name), expected_number, ) def test_add_custom_fk_with_hardcoded_to(self): class HardcodedForeignKey(models.ForeignKey): def __init__(self, *args, **kwargs): kwargs["to"] = "testapp.Author" super().__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super().deconstruct() del kwargs["to"] return name, path, args, kwargs book_hardcoded_fk_to = ModelState( "testapp", "Book", [ ("author", HardcodedForeignKey(on_delete=models.CASCADE)), ], ) changes = self.get_changes( [self.author_empty], [self.author_empty, book_hardcoded_fk_to], ) self.assertNumberMigrations(changes, "testapp", 1) self.assertOperationTypes(changes, "testapp", 0, ["CreateModel"]) self.assertOperationAttributes(changes, "testapp", 0, 0, name="Book") class MigrationSuggestNameTests(SimpleTestCase): def test_no_operations(self): class Migration(migrations.Migration): operations = [] migration = Migration("some_migration", "test_app") self.assertIs(migration.suggest_name().startswith("auto_"), True) def test_no_operations_initial(self): class Migration(migrations.Migration): initial = True operations = [] migration = Migration("some_migration", "test_app") self.assertEqual(migration.suggest_name(), "initial") def test_single_operation(self): class Migration(migrations.Migration): operations = [migrations.CreateModel("Person", fields=[])] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "person") class Migration(migrations.Migration): operations = [migrations.DeleteModel("Person")] migration = Migration("0002_initial", "test_app") self.assertEqual(migration.suggest_name(), "delete_person") def test_single_operation_long_name(self): class Migration(migrations.Migration): operations = [migrations.CreateModel("A" * 53, fields=[])] migration = Migration("some_migration", "test_app") self.assertEqual(migration.suggest_name(), "a" * 53) def test_two_operations(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person", fields=[]), migrations.DeleteModel("Animal"), ] migration = Migration("some_migration", "test_app") self.assertEqual(migration.suggest_name(), "person_delete_animal") def test_two_create_models(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person", fields=[]), migrations.CreateModel("Animal", fields=[]), ] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "person_animal") def test_two_create_models_with_initial_true(self): class Migration(migrations.Migration): initial = True operations = [ migrations.CreateModel("Person", fields=[]), migrations.CreateModel("Animal", fields=[]), ] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "initial") def test_many_operations_suffix(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person1", fields=[]), migrations.CreateModel("Person2", fields=[]), migrations.CreateModel("Person3", fields=[]), migrations.DeleteModel("Person4"), migrations.DeleteModel("Person5"), ] migration = Migration("some_migration", "test_app") self.assertEqual( migration.suggest_name(), "person1_person2_person3_delete_person4_and_more", ) def test_operation_with_no_suggested_name(self): class Migration(migrations.Migration): operations = [ migrations.CreateModel("Person", fields=[]), migrations.RunSQL("SELECT 1 FROM person;"), ] migration = Migration("some_migration", "test_app") self.assertIs(migration.suggest_name().startswith("auto_"), True) def test_none_name(self): class Migration(migrations.Migration): operations = [migrations.RunSQL("SELECT 1 FROM person;")] migration = Migration("0001_initial", "test_app") suggest_name = migration.suggest_name() self.assertIs(suggest_name.startswith("auto_"), True) def test_none_name_with_initial_true(self): class Migration(migrations.Migration): initial = True operations = [migrations.RunSQL("SELECT 1 FROM person;")] migration = Migration("0001_initial", "test_app") self.assertEqual(migration.suggest_name(), "initial") def test_auto(self): migration = migrations.Migration("0001_initial", "test_app") suggest_name = migration.suggest_name() self.assertIs(suggest_name.startswith("auto_"), True)
1b1b1b16ae8f2cf6686633a1a1cf55bacef252302da3fae5a8b37ccd621f2d00
import builtins import getpass import os import sys from datetime import date from io import StringIO from unittest import mock from django.apps import apps from django.contrib.auth import get_permission_codename, management from django.contrib.auth.management import create_permissions, get_default_username from django.contrib.auth.management.commands import changepassword, createsuperuser from django.contrib.auth.models import Group, Permission, User from django.contrib.contenttypes.models import ContentType from django.core.management import call_command from django.core.management.base import CommandError from django.db import migrations from django.test import TestCase, override_settings from django.utils.translation import gettext_lazy as _ from .models import ( CustomUser, CustomUserNonUniqueUsername, CustomUserWithFK, CustomUserWithM2M, CustomUserWithUniqueConstraint, Email, Organization, UserProxy, ) MOCK_INPUT_KEY_TO_PROMPTS = { # @mock_inputs dict key: [expected prompt messages], "bypass": ["Bypass password validation and create user anyway? [y/N]: "], "email": ["Email address: "], "date_of_birth": ["Date of birth: "], "first_name": ["First name: "], "username": [ "Username: ", lambda: "Username (leave blank to use '%s'): " % get_default_username(), ], } def mock_inputs(inputs): """ Decorator to temporarily replace input/getpass to allow interactive createsuperuser. """ def inner(test_func): def wrapper(*args): class mock_getpass: @staticmethod def getpass(prompt=b"Password: ", stream=None): if callable(inputs["password"]): return inputs["password"]() return inputs["password"] def mock_input(prompt): assert "__proxy__" not in prompt response = None for key, val in inputs.items(): if val == "KeyboardInterrupt": raise KeyboardInterrupt # get() fallback because sometimes 'key' is the actual # prompt rather than a shortcut name. prompt_msgs = MOCK_INPUT_KEY_TO_PROMPTS.get(key, key) if isinstance(prompt_msgs, list): prompt_msgs = [ msg() if callable(msg) else msg for msg in prompt_msgs ] if prompt in prompt_msgs: if callable(val): response = val() else: response = val break if response is None: raise ValueError("Mock input for %r not found." % prompt) return response old_getpass = createsuperuser.getpass old_input = builtins.input createsuperuser.getpass = mock_getpass builtins.input = mock_input try: test_func(*args) finally: createsuperuser.getpass = old_getpass builtins.input = old_input return wrapper return inner class MockTTY: """ A fake stdin object that pretends to be a TTY to be used in conjunction with mock_inputs. """ def isatty(self): return True class MockInputTests(TestCase): @mock_inputs({"username": "alice"}) def test_input_not_found(self): with self.assertRaisesMessage( ValueError, "Mock input for 'Email address: ' not found." ): call_command("createsuperuser", stdin=MockTTY()) class GetDefaultUsernameTestCase(TestCase): databases = {"default", "other"} def setUp(self): self.old_get_system_username = management.get_system_username def tearDown(self): management.get_system_username = self.old_get_system_username def test_actual_implementation(self): self.assertIsInstance(management.get_system_username(), str) def test_simple(self): management.get_system_username = lambda: "joe" self.assertEqual(management.get_default_username(), "joe") def test_existing(self): User.objects.create(username="joe") management.get_system_username = lambda: "joe" self.assertEqual(management.get_default_username(), "") self.assertEqual(management.get_default_username(check_db=False), "joe") def test_i18n(self): # 'Julia' with accented 'u': management.get_system_username = lambda: "J\xfalia" self.assertEqual(management.get_default_username(), "julia") def test_with_database(self): User.objects.create(username="joe") management.get_system_username = lambda: "joe" self.assertEqual(management.get_default_username(), "") self.assertEqual(management.get_default_username(database="other"), "joe") User.objects.using("other").create(username="joe") self.assertEqual(management.get_default_username(database="other"), "") @override_settings( AUTH_PASSWORD_VALIDATORS=[ {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"}, ] ) class ChangepasswordManagementCommandTestCase(TestCase): @classmethod def setUpTestData(cls): cls.user = User.objects.create_user(username="joe", password="qwerty") def setUp(self): self.stdout = StringIO() self.stderr = StringIO() def tearDown(self): self.stdout.close() self.stderr.close() @mock.patch.object(getpass, "getpass", return_value="password") def test_get_pass(self, mock_get_pass): call_command("changepassword", username="joe", stdout=self.stdout) self.assertIs(User.objects.get(username="joe").check_password("password"), True) @mock.patch.object(getpass, "getpass", return_value="") def test_get_pass_no_input(self, mock_get_pass): with self.assertRaisesMessage(CommandError, "aborted"): call_command("changepassword", username="joe", stdout=self.stdout) @mock.patch.object(changepassword.Command, "_get_pass", return_value="new_password") def test_system_username(self, mock_get_pass): """The system username is used if --username isn't provided.""" username = getpass.getuser() User.objects.create_user(username=username, password="qwerty") call_command("changepassword", stdout=self.stdout) self.assertIs( User.objects.get(username=username).check_password("new_password"), True ) def test_nonexistent_username(self): with self.assertRaisesMessage(CommandError, "user 'test' does not exist"): call_command("changepassword", username="test", stdout=self.stdout) @mock.patch.object(changepassword.Command, "_get_pass", return_value="not qwerty") def test_that_changepassword_command_changes_joes_password(self, mock_get_pass): "Executing the changepassword management command should change joe's password" self.assertTrue(self.user.check_password("qwerty")) call_command("changepassword", username="joe", stdout=self.stdout) command_output = self.stdout.getvalue().strip() self.assertEqual( command_output, "Changing password for user 'joe'\n" "Password changed successfully for user 'joe'", ) self.assertTrue(User.objects.get(username="joe").check_password("not qwerty")) @mock.patch.object( changepassword.Command, "_get_pass", side_effect=lambda *args: str(args) ) def test_that_max_tries_exits_1(self, mock_get_pass): """ A CommandError should be thrown by handle() if the user enters in mismatched passwords three times. """ msg = "Aborting password change for user 'joe' after 3 attempts" with self.assertRaisesMessage(CommandError, msg): call_command( "changepassword", username="joe", stdout=self.stdout, stderr=self.stderr ) @mock.patch.object(changepassword.Command, "_get_pass", return_value="1234567890") def test_password_validation(self, mock_get_pass): """ A CommandError should be raised if the user enters in passwords which fail validation three times. """ abort_msg = "Aborting password change for user 'joe' after 3 attempts" with self.assertRaisesMessage(CommandError, abort_msg): call_command( "changepassword", username="joe", stdout=self.stdout, stderr=self.stderr ) self.assertIn("This password is entirely numeric.", self.stderr.getvalue()) @mock.patch.object(changepassword.Command, "_get_pass", return_value="not qwerty") def test_that_changepassword_command_works_with_nonascii_output( self, mock_get_pass ): """ #21627 -- Executing the changepassword management command should allow non-ASCII characters from the User object representation. """ # 'Julia' with accented 'u': User.objects.create_user(username="J\xfalia", password="qwerty") call_command("changepassword", username="J\xfalia", stdout=self.stdout) class MultiDBChangepasswordManagementCommandTestCase(TestCase): databases = {"default", "other"} @mock.patch.object(changepassword.Command, "_get_pass", return_value="not qwerty") def test_that_changepassword_command_with_database_option_uses_given_db( self, mock_get_pass ): """ changepassword --database should operate on the specified DB. """ user = User.objects.db_manager("other").create_user( username="joe", password="qwerty" ) self.assertTrue(user.check_password("qwerty")) out = StringIO() call_command("changepassword", username="joe", database="other", stdout=out) command_output = out.getvalue().strip() self.assertEqual( command_output, "Changing password for user 'joe'\n" "Password changed successfully for user 'joe'", ) self.assertTrue( User.objects.using("other").get(username="joe").check_password("not qwerty") ) @override_settings( SILENCED_SYSTEM_CHECKS=["fields.W342"], # ForeignKey(unique=True) AUTH_PASSWORD_VALIDATORS=[ {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"} ], ) class CreatesuperuserManagementCommandTestCase(TestCase): def test_no_email_argument(self): new_io = StringIO() with self.assertRaisesMessage( CommandError, "You must use --email with --noinput." ): call_command( "createsuperuser", interactive=False, username="joe", stdout=new_io ) def test_basic_usage(self): "Check the operation of the createsuperuser management command" # We can use the management command to create a superuser new_io = StringIO() call_command( "createsuperuser", interactive=False, username="joe", email="[email protected]", stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") u = User.objects.get(username="joe") self.assertEqual(u.email, "[email protected]") # created password should be unusable self.assertFalse(u.has_usable_password()) def test_non_ascii_verbose_name(self): @mock_inputs( { "password": "nopasswd", "Uživatel (leave blank to use '%s'): " % get_default_username(): "foo", # username (cz) "email": "[email protected]", } ) def test(self): username_field = User._meta.get_field("username") old_verbose_name = username_field.verbose_name username_field.verbose_name = _("u\u017eivatel") new_io = StringIO() try: call_command( "createsuperuser", interactive=True, stdout=new_io, stdin=MockTTY(), ) finally: username_field.verbose_name = old_verbose_name command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") test(self) def test_verbosity_zero(self): # We can suppress output on the management command new_io = StringIO() call_command( "createsuperuser", interactive=False, username="joe2", email="[email protected]", verbosity=0, stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "") u = User.objects.get(username="joe2") self.assertEqual(u.email, "[email protected]") self.assertFalse(u.has_usable_password()) def test_email_in_username(self): call_command( "createsuperuser", interactive=False, username="[email protected]", email="[email protected]", verbosity=0, ) u = User._default_manager.get(username="[email protected]") self.assertEqual(u.email, "[email protected]") self.assertFalse(u.has_usable_password()) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUser") def test_swappable_user(self): "A superuser can be created when a custom user model is in use" # We can use the management command to create a superuser # We skip validation because the temporary substitution of the # swappable User model messes with validation. new_io = StringIO() call_command( "createsuperuser", interactive=False, email="[email protected]", date_of_birth="1976-04-01", first_name="Joe", stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") u = CustomUser._default_manager.get(email="[email protected]") self.assertEqual(u.date_of_birth, date(1976, 4, 1)) # created password should be unusable self.assertFalse(u.has_usable_password()) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUser") def test_swappable_user_missing_required_field(self): "A Custom superuser won't be created when a required field isn't provided" # We can use the management command to create a superuser # We skip validation because the temporary substitution of the # swappable User model messes with validation. new_io = StringIO() with self.assertRaisesMessage( CommandError, "You must use --email with --noinput." ): call_command( "createsuperuser", interactive=False, stdout=new_io, stderr=new_io, ) self.assertEqual(CustomUser._default_manager.count(), 0) @override_settings( AUTH_USER_MODEL="auth_tests.CustomUserNonUniqueUsername", AUTHENTICATION_BACKENDS=["my.custom.backend"], ) def test_swappable_user_username_non_unique(self): @mock_inputs( { "username": "joe", "password": "nopasswd", } ) def createsuperuser(): new_io = StringIO() call_command( "createsuperuser", interactive=True, email="[email protected]", stdout=new_io, stdin=MockTTY(), ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") for i in range(2): createsuperuser() users = CustomUserNonUniqueUsername.objects.filter(username="joe") self.assertEqual(users.count(), 2) def test_skip_if_not_in_TTY(self): """ If the command is not called from a TTY, it should be skipped and a message should be displayed (#7423). """ class FakeStdin: """A fake stdin object that has isatty() return False.""" def isatty(self): return False out = StringIO() call_command( "createsuperuser", stdin=FakeStdin(), stdout=out, interactive=True, ) self.assertEqual(User._default_manager.count(), 0) self.assertIn("Superuser creation skipped", out.getvalue()) def test_passing_stdin(self): """ You can pass a stdin object as an option and it should be available on self.stdin. If no such option is passed, it defaults to sys.stdin. """ sentinel = object() command = createsuperuser.Command() call_command( command, stdin=sentinel, interactive=False, verbosity=0, username="janet", email="[email protected]", ) self.assertIs(command.stdin, sentinel) command = createsuperuser.Command() call_command( command, interactive=False, verbosity=0, username="joe", email="[email protected]", ) self.assertIs(command.stdin, sys.stdin) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_fields_with_fk(self): new_io = StringIO() group = Group.objects.create(name="mygroup") email = Email.objects.create(email="[email protected]") call_command( "createsuperuser", interactive=False, username=email.pk, email=email.email, group=group.pk, stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") u = CustomUserWithFK._default_manager.get(email=email) self.assertEqual(u.username, email) self.assertEqual(u.group, group) non_existent_email = "[email protected]" msg = "email instance with email %r does not exist." % non_existent_email with self.assertRaisesMessage(CommandError, msg): call_command( "createsuperuser", interactive=False, username=email.pk, email=non_existent_email, stdout=new_io, ) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_fields_with_fk_interactive(self): new_io = StringIO() group = Group.objects.create(name="mygroup") email = Email.objects.create(email="[email protected]") @mock_inputs( { "password": "nopasswd", "Username (Email.id): ": email.pk, "Email (Email.email): ": email.email, "Group (Group.id): ": group.pk, } ) def test(self): call_command( "createsuperuser", interactive=True, stdout=new_io, stdin=MockTTY(), ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") u = CustomUserWithFK._default_manager.get(email=email) self.assertEqual(u.username, email) self.assertEqual(u.group, group) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_fields_with_fk_via_option_interactive(self): new_io = StringIO() group = Group.objects.create(name="mygroup") email = Email.objects.create(email="[email protected]") @mock_inputs({"password": "nopasswd"}) def test(self): call_command( "createsuperuser", interactive=True, username=email.pk, email=email.email, group=group.pk, stdout=new_io, stdin=MockTTY(), ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") u = CustomUserWithFK._default_manager.get(email=email) self.assertEqual(u.username, email) self.assertEqual(u.group, group) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_validate_fk(self): email = Email.objects.create(email="[email protected]") Group.objects.all().delete() nonexistent_group_id = 1 msg = f"group instance with id {nonexistent_group_id} does not exist." with self.assertRaisesMessage(CommandError, msg): call_command( "createsuperuser", interactive=False, username=email.pk, email=email.email, group=nonexistent_group_id, verbosity=0, ) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_validate_fk_environment_variable(self): email = Email.objects.create(email="[email protected]") Group.objects.all().delete() nonexistent_group_id = 1 msg = f"group instance with id {nonexistent_group_id} does not exist." with mock.patch.dict( os.environ, {"DJANGO_SUPERUSER_GROUP": str(nonexistent_group_id)}, ): with self.assertRaisesMessage(CommandError, msg): call_command( "createsuperuser", interactive=False, username=email.pk, email=email.email, verbosity=0, ) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithFK") def test_validate_fk_via_option_interactive(self): email = Email.objects.create(email="[email protected]") Group.objects.all().delete() nonexistent_group_id = 1 msg = f"group instance with id {nonexistent_group_id} does not exist." @mock_inputs( { "password": "nopasswd", "Username (Email.id): ": email.pk, "Email (Email.email): ": email.email, } ) def test(self): with self.assertRaisesMessage(CommandError, msg): call_command( "createsuperuser", group=nonexistent_group_id, stdin=MockTTY(), verbosity=0, ) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2m") def test_fields_with_m2m(self): new_io = StringIO() org_id_1 = Organization.objects.create(name="Organization 1").pk org_id_2 = Organization.objects.create(name="Organization 2").pk call_command( "createsuperuser", interactive=False, username="joe", orgs=[org_id_1, org_id_2], stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") user = CustomUserWithM2M._default_manager.get(username="joe") self.assertEqual(user.orgs.count(), 2) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2M") def test_fields_with_m2m_interactive(self): new_io = StringIO() org_id_1 = Organization.objects.create(name="Organization 1").pk org_id_2 = Organization.objects.create(name="Organization 2").pk @mock_inputs( { "password": "nopasswd", "Username: ": "joe", "Orgs (Organization.id): ": "%s, %s" % (org_id_1, org_id_2), } ) def test(self): call_command( "createsuperuser", interactive=True, stdout=new_io, stdin=MockTTY(), ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") user = CustomUserWithM2M._default_manager.get(username="joe") self.assertEqual(user.orgs.count(), 2) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2M") def test_fields_with_m2m_interactive_blank(self): new_io = StringIO() org_id = Organization.objects.create(name="Organization").pk entered_orgs = [str(org_id), " "] def return_orgs(): return entered_orgs.pop() @mock_inputs( { "password": "nopasswd", "Username: ": "joe", "Orgs (Organization.id): ": return_orgs, } ) def test(self): call_command( "createsuperuser", interactive=True, stdout=new_io, stderr=new_io, stdin=MockTTY(), ) self.assertEqual( new_io.getvalue().strip(), "Error: This field cannot be blank.\n" "Superuser created successfully.", ) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2MThrough") def test_fields_with_m2m_and_through(self): msg = ( "Required field 'orgs' specifies a many-to-many relation through " "model, which is not supported." ) with self.assertRaisesMessage(CommandError, msg): call_command("createsuperuser") def test_default_username(self): """createsuperuser uses a default username when one isn't provided.""" # Get the default username before creating a user. default_username = get_default_username() new_io = StringIO() entered_passwords = ["password", "password"] def return_passwords(): return entered_passwords.pop(0) @mock_inputs({"password": return_passwords, "username": "", "email": ""}) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Superuser created successfully." ) self.assertTrue(User.objects.filter(username=default_username).exists()) test(self) def test_password_validation(self): """ Creation should fail if the password fails validation. """ new_io = StringIO() entered_passwords = ["1234567890", "1234567890", "password", "password"] def bad_then_good_password(): return entered_passwords.pop(0) @mock_inputs( { "password": bad_then_good_password, "username": "joe1234567890", "email": "", "bypass": "n", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "This password is entirely numeric.\n" "Superuser created successfully.", ) test(self) @override_settings( AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, ] ) def test_validate_password_against_username(self): new_io = StringIO() username = "supremelycomplex" entered_passwords = [ username, username, "superduperunguessablepassword", "superduperunguessablepassword", ] def bad_then_good_password(): return entered_passwords.pop(0) @mock_inputs( { "password": bad_then_good_password, "username": username, "email": "", "bypass": "n", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "The password is too similar to the username.\n" "Superuser created successfully.", ) test(self) @override_settings( AUTH_USER_MODEL="auth_tests.CustomUser", AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, ], ) def test_validate_password_against_required_fields(self): new_io = StringIO() first_name = "josephine" entered_passwords = [ first_name, first_name, "superduperunguessablepassword", "superduperunguessablepassword", ] def bad_then_good_password(): return entered_passwords.pop(0) @mock_inputs( { "password": bad_then_good_password, "username": "whatever", "first_name": first_name, "date_of_birth": "1970-01-01", "email": "[email protected]", "bypass": "n", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "The password is too similar to the first name.\n" "Superuser created successfully.", ) test(self) @override_settings( AUTH_USER_MODEL="auth_tests.CustomUser", AUTH_PASSWORD_VALIDATORS=[ { "NAME": ( "django.contrib.auth.password_validation." "UserAttributeSimilarityValidator" ) }, ], ) def test_validate_password_against_required_fields_via_option(self): new_io = StringIO() first_name = "josephine" entered_passwords = [ first_name, first_name, "superduperunguessablepassword", "superduperunguessablepassword", ] def bad_then_good_password(): return entered_passwords.pop(0) @mock_inputs( { "password": bad_then_good_password, "bypass": "n", } ) def test(self): call_command( "createsuperuser", interactive=True, first_name=first_name, date_of_birth="1970-01-01", email="[email protected]", stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "The password is too similar to the first name.\n" "Superuser created successfully.", ) test(self) def test_blank_username(self): """Creation fails if --username is blank.""" new_io = StringIO() with self.assertRaisesMessage(CommandError, "Username cannot be blank."): call_command( "createsuperuser", username="", stdin=MockTTY(), stdout=new_io, stderr=new_io, ) def test_blank_username_non_interactive(self): new_io = StringIO() with self.assertRaisesMessage(CommandError, "Username cannot be blank."): call_command( "createsuperuser", username="", interactive=False, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) def test_password_validation_bypass(self): """ Password validation can be bypassed by entering 'y' at the prompt. """ new_io = StringIO() @mock_inputs( { "password": "1234567890", "username": "joe1234567890", "email": "", "bypass": "y", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "This password is entirely numeric.\n" "Superuser created successfully.", ) test(self) def test_invalid_username(self): """Creation fails if the username fails validation.""" user_field = User._meta.get_field(User.USERNAME_FIELD) new_io = StringIO() entered_passwords = ["password", "password"] # Enter an invalid (too long) username first and then a valid one. invalid_username = ("x" * user_field.max_length) + "y" entered_usernames = [invalid_username, "janet"] def return_passwords(): return entered_passwords.pop(0) def return_usernames(): return entered_usernames.pop(0) @mock_inputs( {"password": return_passwords, "username": return_usernames, "email": ""} ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Error: Ensure this value has at most %s characters (it has %s).\n" "Superuser created successfully." % (user_field.max_length, len(invalid_username)), ) test(self) @mock_inputs({"username": "KeyboardInterrupt"}) def test_keyboard_interrupt(self): new_io = StringIO() with self.assertRaises(SystemExit): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual(new_io.getvalue(), "\nOperation cancelled.\n") def test_existing_username(self): """Creation fails if the username already exists.""" user = User.objects.create(username="janet") new_io = StringIO() entered_passwords = ["password", "password"] # Enter the existing username first and then a new one. entered_usernames = [user.username, "joe"] def return_passwords(): return entered_passwords.pop(0) def return_usernames(): return entered_usernames.pop(0) @mock_inputs( {"password": return_passwords, "username": return_usernames, "email": ""} ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Error: That username is already taken.\n" "Superuser created successfully.", ) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithUniqueConstraint") def test_existing_username_meta_unique_constraint(self): """ Creation fails if the username already exists and a custom user model has UniqueConstraint. """ user = CustomUserWithUniqueConstraint.objects.create(username="janet") new_io = StringIO() entered_passwords = ["password", "password"] # Enter the existing username first and then a new one. entered_usernames = [user.username, "joe"] def return_passwords(): return entered_passwords.pop(0) def return_usernames(): return entered_usernames.pop(0) @mock_inputs({"password": return_passwords, "username": return_usernames}) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Error: That username is already taken.\n" "Superuser created successfully.", ) test(self) def test_existing_username_non_interactive(self): """Creation fails if the username already exists.""" User.objects.create(username="janet") new_io = StringIO() with self.assertRaisesMessage( CommandError, "Error: That username is already taken." ): call_command( "createsuperuser", username="janet", email="", interactive=False, stdout=new_io, ) def test_existing_username_provided_via_option_and_interactive(self): """call_command() gets username='janet' and interactive=True.""" new_io = StringIO() entered_passwords = ["password", "password"] User.objects.create(username="janet") def return_passwords(): return entered_passwords.pop(0) @mock_inputs( { "password": return_passwords, "username": "janet1", "email": "[email protected]", } ) def test(self): call_command( "createsuperuser", username="janet", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) msg = ( "Error: That username is already taken.\n" "Superuser created successfully." ) self.assertEqual(new_io.getvalue().strip(), msg) test(self) def test_validation_mismatched_passwords(self): """ Creation should fail if the user enters mismatched passwords. """ new_io = StringIO() # The first two passwords do not match, but the second two do match and # are valid. entered_passwords = ["password", "not password", "password2", "password2"] def mismatched_passwords_then_matched(): return entered_passwords.pop(0) @mock_inputs( { "password": mismatched_passwords_then_matched, "username": "joe1234567890", "email": "", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Error: Your passwords didn't match.\n" "Superuser created successfully.", ) test(self) def test_validation_blank_password_entered(self): """ Creation should fail if the user enters blank passwords. """ new_io = StringIO() # The first two passwords are empty strings, but the second two are # valid. entered_passwords = ["", "", "password2", "password2"] def blank_passwords_then_valid(): return entered_passwords.pop(0) @mock_inputs( { "password": blank_passwords_then_valid, "username": "joe1234567890", "email": "", } ) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Error: Blank passwords aren't allowed.\n" "Superuser created successfully.", ) test(self) @override_settings(AUTH_USER_MODEL="auth_tests.NoPasswordUser") def test_usermodel_without_password(self): new_io = StringIO() call_command( "createsuperuser", interactive=False, stdin=MockTTY(), stdout=new_io, stderr=new_io, username="username", ) self.assertEqual(new_io.getvalue().strip(), "Superuser created successfully.") @override_settings(AUTH_USER_MODEL="auth_tests.NoPasswordUser") def test_usermodel_without_password_interactive(self): new_io = StringIO() @mock_inputs({"username": "username"}) def test(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), stdout=new_io, stderr=new_io, ) self.assertEqual( new_io.getvalue().strip(), "Superuser created successfully." ) test(self) @mock.patch.dict( os.environ, { "DJANGO_SUPERUSER_PASSWORD": "test_password", "DJANGO_SUPERUSER_USERNAME": "test_superuser", "DJANGO_SUPERUSER_EMAIL": "[email protected]", "DJANGO_SUPERUSER_FIRST_NAME": "ignored_first_name", }, ) def test_environment_variable_non_interactive(self): call_command("createsuperuser", interactive=False, verbosity=0) user = User.objects.get(username="test_superuser") self.assertEqual(user.email, "[email protected]") self.assertTrue(user.check_password("test_password")) # Environment variables are ignored for non-required fields. self.assertEqual(user.first_name, "") @override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithM2m") def test_environment_variable_m2m_non_interactive(self): new_io = StringIO() org_id_1 = Organization.objects.create(name="Organization 1").pk org_id_2 = Organization.objects.create(name="Organization 2").pk with mock.patch.dict( os.environ, { "DJANGO_SUPERUSER_ORGS": f"{org_id_1},{org_id_2}", }, ): call_command( "createsuperuser", interactive=False, username="joe", stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") user = CustomUserWithM2M._default_manager.get(username="joe") self.assertEqual(user.orgs.count(), 2) @mock.patch.dict( os.environ, { "DJANGO_SUPERUSER_USERNAME": "test_superuser", "DJANGO_SUPERUSER_EMAIL": "[email protected]", }, ) def test_ignore_environment_variable_non_interactive(self): # Environment variables are ignored in non-interactive mode, if # provided by a command line arguments. call_command( "createsuperuser", interactive=False, username="cmd_superuser", email="[email protected]", verbosity=0, ) user = User.objects.get(username="cmd_superuser") self.assertEqual(user.email, "[email protected]") self.assertFalse(user.has_usable_password()) @mock.patch.dict( os.environ, { "DJANGO_SUPERUSER_PASSWORD": "test_password", "DJANGO_SUPERUSER_USERNAME": "test_superuser", "DJANGO_SUPERUSER_EMAIL": "[email protected]", }, ) def test_ignore_environment_variable_interactive(self): # Environment variables are ignored in interactive mode. @mock_inputs({"password": "cmd_password"}) def test(self): call_command( "createsuperuser", interactive=True, username="cmd_superuser", email="[email protected]", stdin=MockTTY(), verbosity=0, ) user = User.objects.get(username="cmd_superuser") self.assertEqual(user.email, "[email protected]") self.assertTrue(user.check_password("cmd_password")) test(self) class MultiDBCreatesuperuserTestCase(TestCase): databases = {"default", "other"} def test_createsuperuser_command_with_database_option(self): """ createsuperuser --database should operate on the specified DB. """ new_io = StringIO() call_command( "createsuperuser", interactive=False, username="joe", email="[email protected]", database="other", stdout=new_io, ) command_output = new_io.getvalue().strip() self.assertEqual(command_output, "Superuser created successfully.") user = User.objects.using("other").get(username="joe") self.assertEqual(user.email, "[email protected]") def test_createsuperuser_command_suggested_username_with_database_option(self): default_username = get_default_username(database="other") qs = User.objects.using("other") @mock_inputs({"password": "nopasswd", "username": "", "email": ""}) def test_other_create_with_suggested_username(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), verbosity=0, database="other", ) self.assertIs(qs.filter(username=default_username).exists(), True) test_other_create_with_suggested_username(self) @mock_inputs({"password": "nopasswd", "Username: ": "other", "email": ""}) def test_other_no_suggestion(self): call_command( "createsuperuser", interactive=True, stdin=MockTTY(), verbosity=0, database="other", ) self.assertIs(qs.filter(username="other").exists(), True) test_other_no_suggestion(self) class CreatePermissionsTests(TestCase): def setUp(self): self._original_permissions = Permission._meta.permissions[:] self._original_default_permissions = Permission._meta.default_permissions self.app_config = apps.get_app_config("auth") def tearDown(self): Permission._meta.permissions = self._original_permissions Permission._meta.default_permissions = self._original_default_permissions ContentType.objects.clear_cache() def test_default_permissions(self): permission_content_type = ContentType.objects.get_by_natural_key( "auth", "permission" ) Permission._meta.permissions = [ ("my_custom_permission", "Some permission"), ] create_permissions(self.app_config, verbosity=0) # view/add/change/delete permission by default + custom permission self.assertEqual( Permission.objects.filter( content_type=permission_content_type, ).count(), 5, ) Permission.objects.filter(content_type=permission_content_type).delete() Permission._meta.default_permissions = [] create_permissions(self.app_config, verbosity=0) # custom permission only since default permissions is empty self.assertEqual( Permission.objects.filter( content_type=permission_content_type, ).count(), 1, ) def test_unavailable_models(self): """ #24075 - Permissions shouldn't be created or deleted if the ContentType or Permission models aren't available. """ state = migrations.state.ProjectState() # Unavailable contenttypes.ContentType with self.assertNumQueries(0): create_permissions(self.app_config, verbosity=0, apps=state.apps) # Unavailable auth.Permission state = migrations.state.ProjectState(real_apps={"contenttypes"}) with self.assertNumQueries(0): create_permissions(self.app_config, verbosity=0, apps=state.apps) def test_create_permissions_checks_contenttypes_created(self): """ `post_migrate` handler ordering isn't guaranteed. Simulate a case where create_permissions() is called before create_contenttypes(). """ # Warm the manager cache. ContentType.objects.get_for_model(Group) # Apply a deletion as if e.g. a database 'flush' had been executed. ContentType.objects.filter(app_label="auth", model="group").delete() # This fails with a foreign key constraint without the fix. create_permissions(apps.get_app_config("auth"), interactive=False, verbosity=0) def test_permission_with_proxy_content_type_created(self): """ A proxy model's permissions use its own content type rather than the content type of the concrete model. """ opts = UserProxy._meta codename = get_permission_codename("add", opts) self.assertTrue( Permission.objects.filter( content_type__model=opts.model_name, content_type__app_label=opts.app_label, codename=codename, ).exists() )
85c90b8e793c8b8351225b9ec5932d291a26eaa1f5e076efd5655fc75b895292
from unittest import mock, skipUnless from django.conf.global_settings import PASSWORD_HASHERS from django.contrib.auth.hashers import ( UNUSABLE_PASSWORD_PREFIX, UNUSABLE_PASSWORD_SUFFIX_LENGTH, BasePasswordHasher, BCryptPasswordHasher, BCryptSHA256PasswordHasher, MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, SHA1PasswordHasher, check_password, get_hasher, identify_hasher, is_password_usable, make_password, ) from django.test import SimpleTestCase, ignore_warnings from django.test.utils import override_settings from django.utils.deprecation import RemovedInDjango50Warning # RemovedInDjango50Warning. try: import crypt except ImportError: crypt = None else: # On some platforms (e.g. OpenBSD), crypt.crypt() always return None. if crypt.crypt("") is None: crypt = None try: import bcrypt except ImportError: bcrypt = None try: import argon2 except ImportError: argon2 = None class PBKDF2SingleIterationHasher(PBKDF2PasswordHasher): iterations = 1 @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPass(SimpleTestCase): def test_simple(self): encoded = make_password("lètmein") self.assertTrue(encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) # Blank passwords blank_encoded = make_password("") self.assertTrue(blank_encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) def test_bytes(self): encoded = make_password(b"bytes_password") self.assertTrue(encoded.startswith("pbkdf2_sha256$")) self.assertIs(is_password_usable(encoded), True) self.assertIs(check_password(b"bytes_password", encoded), True) def test_invalid_password(self): msg = "Password must be a string or bytes, got int." with self.assertRaisesMessage(TypeError, msg): make_password(1) def test_pbkdf2(self): encoded = make_password("lètmein", "seasalt", "pbkdf2_sha256") self.assertEqual( encoded, "pbkdf2_sha256$480000$seasalt$G4ja8YRtfnNyEx4Ii2pbFMp/l8s4nnbMdJ+Fob/qNK8=", ) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "pbkdf2_sha256") # Blank passwords blank_encoded = make_password("", "seasalt", "pbkdf2_sha256") self.assertTrue(blank_encoded.startswith("pbkdf2_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Salt entropy check. hasher = get_hasher("pbkdf2_sha256") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "pbkdf2_sha256") encoded_strong_salt = make_password("lètmein", hasher.salt(), "pbkdf2_sha256") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.SHA1PasswordHasher"] ) def test_sha1(self): encoded = make_password("lètmein", "seasalt", "sha1") self.assertEqual( encoded, "sha1$seasalt$cff36ea83f5706ce9aa7454e63e431fc726b2dc8" ) self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "sha1") # Blank passwords blank_encoded = make_password("", "seasalt", "sha1") self.assertTrue(blank_encoded.startswith("sha1$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Salt entropy check. hasher = get_hasher("sha1") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "sha1") encoded_strong_salt = make_password("lètmein", hasher.salt(), "sha1") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"] ) def test_md5(self): encoded = make_password("lètmein", "seasalt", "md5") self.assertEqual(encoded, "md5$seasalt$3f86d0d3d465b7b458c231bf3555c0e3") self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "md5") # Blank passwords blank_encoded = make_password("", "seasalt", "md5") self.assertTrue(blank_encoded.startswith("md5$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Salt entropy check. hasher = get_hasher("md5") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "md5") encoded_strong_salt = make_password("lètmein", hasher.salt(), "md5") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedMD5PasswordHasher"] ) def test_unsalted_md5(self): encoded = make_password("lètmein", "", "unsalted_md5") self.assertEqual(encoded, "88a434c88cca4e900f7874cd98123f43") self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "unsalted_md5") # Alternate unsalted syntax alt_encoded = "md5$$%s" % encoded self.assertTrue(is_password_usable(alt_encoded)) self.assertTrue(check_password("lètmein", alt_encoded)) self.assertFalse(check_password("lètmeinz", alt_encoded)) # Blank passwords blank_encoded = make_password("", "", "unsalted_md5") self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedMD5PasswordHasher"] ) def test_unsalted_md5_encode_invalid_salt(self): hasher = get_hasher("unsalted_md5") msg = "salt must be empty." with self.assertRaisesMessage(ValueError, msg): hasher.encode("password", salt="salt") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher"] ) def test_unsalted_sha1(self): encoded = make_password("lètmein", "", "unsalted_sha1") self.assertEqual(encoded, "sha1$$6d138ca3ae545631b3abd71a4f076ce759c5700b") self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "unsalted_sha1") # Raw SHA1 isn't acceptable alt_encoded = encoded[6:] self.assertFalse(check_password("lètmein", alt_encoded)) # Blank passwords blank_encoded = make_password("", "", "unsalted_sha1") self.assertTrue(blank_encoded.startswith("sha1$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher"] ) def test_unsalted_sha1_encode_invalid_salt(self): hasher = get_hasher("unsalted_sha1") msg = "salt must be empty." with self.assertRaisesMessage(ValueError, msg): hasher.encode("password", salt="salt") @ignore_warnings(category=RemovedInDjango50Warning) @skipUnless(crypt, "no crypt module to generate password.") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.CryptPasswordHasher"] ) def test_crypt(self): encoded = make_password("lètmei", "ab", "crypt") self.assertEqual(encoded, "crypt$$ab1Hv2Lg7ltQo") self.assertTrue(is_password_usable(encoded)) self.assertTrue(check_password("lètmei", encoded)) self.assertFalse(check_password("lètmeiz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "crypt") # Blank passwords blank_encoded = make_password("", "ab", "crypt") self.assertTrue(blank_encoded.startswith("crypt$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @ignore_warnings(category=RemovedInDjango50Warning) @skipUnless(crypt, "no crypt module to generate password.") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.CryptPasswordHasher"] ) def test_crypt_encode_invalid_salt(self): hasher = get_hasher("crypt") msg = "salt must be of length 2." with self.assertRaisesMessage(ValueError, msg): hasher.encode("password", salt="a") @ignore_warnings(category=RemovedInDjango50Warning) @skipUnless(crypt, "no crypt module to generate password.") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.CryptPasswordHasher"] ) def test_crypt_encode_invalid_hash(self): hasher = get_hasher("crypt") msg = "hash must be provided." with mock.patch("crypt.crypt", return_value=None): with self.assertRaisesMessage(TypeError, msg): hasher.encode("password", salt="ab") @skipUnless(crypt, "no crypt module to generate password.") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.CryptPasswordHasher"] ) def test_crypt_deprecation_warning(self): msg = "django.contrib.auth.hashers.CryptPasswordHasher is deprecated." with self.assertRaisesMessage(RemovedInDjango50Warning, msg): get_hasher("crypt") @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_sha256(self): encoded = make_password("lètmein", hasher="bcrypt_sha256") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("bcrypt_sha256$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt_sha256") # password truncation no longer works password = ( "VSK0UYV6FFQVZ0KG88DYN9WADAADZO1CTSIVDJUNZSUML6IBX7LN7ZS3R5" "JGB3RGZ7VI7G7DJQ9NI8BQFSRPTG6UWTTVESA5ZPUN" ) encoded = make_password(password, hasher="bcrypt_sha256") self.assertTrue(check_password(password, encoded)) self.assertFalse(check_password(password[:72], encoded)) # Blank passwords blank_encoded = make_password("", hasher="bcrypt_sha256") self.assertTrue(blank_encoded.startswith("bcrypt_sha256$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt(self): encoded = make_password("lètmein", hasher="bcrypt") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("bcrypt$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "bcrypt") # Blank passwords blank_encoded = make_password("", hasher="bcrypt") self.assertTrue(blank_encoded.startswith("bcrypt$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt_upgrade(self): hasher = get_hasher("bcrypt") self.assertEqual("bcrypt", hasher.algorithm) self.assertNotEqual(hasher.rounds, 4) old_rounds = hasher.rounds try: # Generate a password with 4 rounds. hasher.rounds = 4 encoded = make_password("letmein", hasher="bcrypt") rounds = hasher.safe_summary(encoded)["work factor"] self.assertEqual(rounds, 4) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered. self.assertTrue(check_password("letmein", encoded, setter, "bcrypt")) self.assertFalse(state["upgraded"]) # Revert to the old rounds count and ... hasher.rounds = old_rounds # ... check if the password would get updated to the new count. self.assertTrue(check_password("letmein", encoded, setter, "bcrypt")) self.assertTrue(state["upgraded"]) finally: hasher.rounds = old_rounds @skipUnless(bcrypt, "bcrypt not installed") @override_settings( PASSWORD_HASHERS=["django.contrib.auth.hashers.BCryptPasswordHasher"] ) def test_bcrypt_harden_runtime(self): hasher = get_hasher("bcrypt") self.assertEqual("bcrypt", hasher.algorithm) with mock.patch.object(hasher, "rounds", 4): encoded = make_password("letmein", hasher="bcrypt") with mock.patch.object(hasher, "rounds", 6), mock.patch.object( hasher, "encode", side_effect=hasher.encode ): hasher.harden_runtime("wrong_password", encoded) # Increasing rounds from 4 to 6 means an increase of 4 in workload, # therefore hardening should run 3 times to make the timing the # same (the original encode() call already ran once). self.assertEqual(hasher.encode.call_count, 3) # Get the original salt (includes the original workload factor) algorithm, data = encoded.split("$", 1) expected_call = (("wrong_password", data[:29].encode()),) self.assertEqual(hasher.encode.call_args_list, [expected_call] * 3) def test_unusable(self): encoded = make_password(None) self.assertEqual( len(encoded), len(UNUSABLE_PASSWORD_PREFIX) + UNUSABLE_PASSWORD_SUFFIX_LENGTH, ) self.assertFalse(is_password_usable(encoded)) self.assertFalse(check_password(None, encoded)) self.assertFalse(check_password(encoded, encoded)) self.assertFalse(check_password(UNUSABLE_PASSWORD_PREFIX, encoded)) self.assertFalse(check_password("", encoded)) self.assertFalse(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) with self.assertRaisesMessage(ValueError, "Unknown password hashing algorith"): identify_hasher(encoded) # Assert that the unusable passwords actually contain a random part. # This might fail one day due to a hash collision. self.assertNotEqual(encoded, make_password(None), "Random password collision?") def test_unspecified_password(self): """ Makes sure specifying no plain password with a valid encoded password returns `False`. """ self.assertFalse(check_password(None, make_password("lètmein"))) def test_bad_algorithm(self): msg = ( "Unknown password hashing algorithm '%s'. Did you specify it in " "the PASSWORD_HASHERS setting?" ) with self.assertRaisesMessage(ValueError, msg % "lolcat"): make_password("lètmein", hasher="lolcat") with self.assertRaisesMessage(ValueError, msg % "lolcat"): identify_hasher("lolcat$salt$hash") def test_is_password_usable(self): passwords = ("lètmein_badencoded", "", None) for password in passwords: with self.subTest(password=password): self.assertIs(is_password_usable(password), True) def test_low_level_pbkdf2(self): hasher = PBKDF2PasswordHasher() encoded = hasher.encode("lètmein", "seasalt2") self.assertEqual( encoded, "pbkdf2_sha256$480000$seasalt2$WlORJKPl5w3Lubr7rYLOwSQCEOm4Or/NCA" "aECnB1PE0=", ) self.assertTrue(hasher.verify("lètmein", encoded)) def test_low_level_pbkdf2_sha1(self): hasher = PBKDF2SHA1PasswordHasher() encoded = hasher.encode("lètmein", "seasalt2") self.assertEqual( encoded, "pbkdf2_sha1$480000$seasalt2$qyT+EkK5g82hk2r+fRecFeoe28E=" ) self.assertTrue(hasher.verify("lètmein", encoded)) @skipUnless(bcrypt, "bcrypt not installed") def test_bcrypt_salt_check(self): hasher = BCryptPasswordHasher() encoded = hasher.encode("lètmein", hasher.salt()) self.assertIs(hasher.must_update(encoded), False) @skipUnless(bcrypt, "bcrypt not installed") def test_bcryptsha256_salt_check(self): hasher = BCryptSHA256PasswordHasher() encoded = hasher.encode("lètmein", hasher.salt()) self.assertIs(hasher.must_update(encoded), False) @override_settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.SHA1PasswordHasher", "django.contrib.auth.hashers.MD5PasswordHasher", ], ) def test_upgrade(self): self.assertEqual("pbkdf2_sha256", get_hasher("default").algorithm) for algo in ("sha1", "md5"): with self.subTest(algo=algo): encoded = make_password("lètmein", hasher=algo) state = {"upgraded": False} def setter(password): state["upgraded"] = True self.assertTrue(check_password("lètmein", encoded, setter)) self.assertTrue(state["upgraded"]) def test_no_upgrade(self): encoded = make_password("lètmein") state = {"upgraded": False} def setter(): state["upgraded"] = True self.assertFalse(check_password("WRONG", encoded, setter)) self.assertFalse(state["upgraded"]) @override_settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "django.contrib.auth.hashers.SHA1PasswordHasher", "django.contrib.auth.hashers.MD5PasswordHasher", ], ) def test_no_upgrade_on_incorrect_pass(self): self.assertEqual("pbkdf2_sha256", get_hasher("default").algorithm) for algo in ("sha1", "md5"): with self.subTest(algo=algo): encoded = make_password("lètmein", hasher=algo) state = {"upgraded": False} def setter(): state["upgraded"] = True self.assertFalse(check_password("WRONG", encoded, setter)) self.assertFalse(state["upgraded"]) def test_pbkdf2_upgrade(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) self.assertNotEqual(hasher.iterations, 1) old_iterations = hasher.iterations try: # Generate a password with 1 iteration. hasher.iterations = 1 encoded = make_password("letmein") algo, iterations, salt, hash = encoded.split("$", 3) self.assertEqual(iterations, "1") state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered self.assertTrue(check_password("letmein", encoded, setter)) self.assertFalse(state["upgraded"]) # Revert to the old iteration count and ... hasher.iterations = old_iterations # ... check if the password would get updated to the new iteration count. self.assertTrue(check_password("letmein", encoded, setter)) self.assertTrue(state["upgraded"]) finally: hasher.iterations = old_iterations def test_pbkdf2_harden_runtime(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) with mock.patch.object(hasher, "iterations", 1): encoded = make_password("letmein") with mock.patch.object(hasher, "iterations", 6), mock.patch.object( hasher, "encode", side_effect=hasher.encode ): hasher.harden_runtime("wrong_password", encoded) # Encode should get called once ... self.assertEqual(hasher.encode.call_count, 1) # ... with the original salt and 5 iterations. algorithm, iterations, salt, hash = encoded.split("$", 3) expected_call = (("wrong_password", salt, 5),) self.assertEqual(hasher.encode.call_args, expected_call) def test_pbkdf2_upgrade_new_hasher(self): hasher = get_hasher("default") self.assertEqual("pbkdf2_sha256", hasher.algorithm) self.assertNotEqual(hasher.iterations, 1) state = {"upgraded": False} def setter(password): state["upgraded"] = True with self.settings( PASSWORD_HASHERS=["auth_tests.test_hashers.PBKDF2SingleIterationHasher"] ): encoded = make_password("letmein") algo, iterations, salt, hash = encoded.split("$", 3) self.assertEqual(iterations, "1") # No upgrade is triggered self.assertTrue(check_password("letmein", encoded, setter)) self.assertFalse(state["upgraded"]) # Revert to the old iteration count and check if the password would get # updated to the new iteration count. with self.settings( PASSWORD_HASHERS=[ "django.contrib.auth.hashers.PBKDF2PasswordHasher", "auth_tests.test_hashers.PBKDF2SingleIterationHasher", ] ): self.assertTrue(check_password("letmein", encoded, setter)) self.assertTrue(state["upgraded"]) def test_check_password_calls_harden_runtime(self): hasher = get_hasher("default") encoded = make_password("letmein") with mock.patch.object(hasher, "harden_runtime"), mock.patch.object( hasher, "must_update", return_value=True ): # Correct password supplied, no hardening needed check_password("letmein", encoded) self.assertEqual(hasher.harden_runtime.call_count, 0) # Wrong password supplied, hardening needed check_password("wrong_password", encoded) self.assertEqual(hasher.harden_runtime.call_count, 1) def test_encode_invalid_salt(self): hasher_classes = [ MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, SHA1PasswordHasher, ] msg = "salt must be provided and cannot contain $." for hasher_class in hasher_classes: hasher = hasher_class() for salt in [None, "", "sea$salt"]: with self.subTest(hasher_class.__name__, salt=salt): with self.assertRaisesMessage(ValueError, msg): hasher.encode("password", salt) def test_encode_password_required(self): hasher_classes = [ MD5PasswordHasher, PBKDF2PasswordHasher, PBKDF2SHA1PasswordHasher, ScryptPasswordHasher, SHA1PasswordHasher, ] msg = "password must be provided." for hasher_class in hasher_classes: hasher = hasher_class() with self.subTest(hasher_class.__name__): with self.assertRaisesMessage(TypeError, msg): hasher.encode(None, "seasalt") class BasePasswordHasherTests(SimpleTestCase): not_implemented_msg = "subclasses of BasePasswordHasher must provide %s() method" def setUp(self): self.hasher = BasePasswordHasher() def test_load_library_no_algorithm(self): msg = "Hasher 'BasePasswordHasher' doesn't specify a library attribute" with self.assertRaisesMessage(ValueError, msg): self.hasher._load_library() def test_load_library_importerror(self): PlainHasher = type( "PlainHasher", (BasePasswordHasher,), {"algorithm": "plain", "library": "plain"}, ) msg = "Couldn't load 'PlainHasher' algorithm library: No module named 'plain'" with self.assertRaisesMessage(ValueError, msg): PlainHasher()._load_library() def test_attributes(self): self.assertIsNone(self.hasher.algorithm) self.assertIsNone(self.hasher.library) def test_encode(self): msg = self.not_implemented_msg % "an encode" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.encode("password", "salt") def test_decode(self): msg = self.not_implemented_msg % "a decode" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.decode("encoded") def test_harden_runtime(self): msg = ( "subclasses of BasePasswordHasher should provide a harden_runtime() method" ) with self.assertWarnsMessage(Warning, msg): self.hasher.harden_runtime("password", "encoded") def test_must_update(self): self.assertIs(self.hasher.must_update("encoded"), False) def test_safe_summary(self): msg = self.not_implemented_msg % "a safe_summary" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.safe_summary("encoded") def test_verify(self): msg = self.not_implemented_msg % "a verify" with self.assertRaisesMessage(NotImplementedError, msg): self.hasher.verify("password", "encoded") @skipUnless(argon2, "argon2-cffi not installed") @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPassArgon2(SimpleTestCase): def test_argon2(self): encoded = make_password("lètmein", hasher="argon2") self.assertTrue(is_password_usable(encoded)) self.assertTrue(encoded.startswith("argon2$argon2id$")) self.assertTrue(check_password("lètmein", encoded)) self.assertFalse(check_password("lètmeinz", encoded)) self.assertEqual(identify_hasher(encoded).algorithm, "argon2") # Blank passwords blank_encoded = make_password("", hasher="argon2") self.assertTrue(blank_encoded.startswith("argon2$argon2id$")) self.assertTrue(is_password_usable(blank_encoded)) self.assertTrue(check_password("", blank_encoded)) self.assertFalse(check_password(" ", blank_encoded)) # Old hashes without version attribute encoded = ( "argon2$argon2i$m=8,t=1,p=1$c29tZXNhbHQ$gwQOXSNhxiOxPOA0+PY10P9QFO" "4NAYysnqRt1GSQLE55m+2GYDt9FEjPMHhP2Cuf0nOEXXMocVrsJAtNSsKyfg" ) self.assertTrue(check_password("secret", encoded)) self.assertFalse(check_password("wrong", encoded)) # Old hashes with version attribute. encoded = "argon2$argon2i$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$YC9+jJCrQhs5R6db7LlN8Q" self.assertIs(check_password("secret", encoded), True) self.assertIs(check_password("wrong", encoded), False) # Salt entropy check. hasher = get_hasher("argon2") encoded_weak_salt = make_password("lètmein", "iodizedsalt", "argon2") encoded_strong_salt = make_password("lètmein", hasher.salt(), "argon2") self.assertIs(hasher.must_update(encoded_weak_salt), True) self.assertIs(hasher.must_update(encoded_strong_salt), False) def test_argon2_decode(self): salt = "abcdefghijk" encoded = make_password("lètmein", salt=salt, hasher="argon2") hasher = get_hasher("argon2") decoded = hasher.decode(encoded) self.assertEqual(decoded["memory_cost"], hasher.memory_cost) self.assertEqual(decoded["parallelism"], hasher.parallelism) self.assertEqual(decoded["salt"], salt) self.assertEqual(decoded["time_cost"], hasher.time_cost) def test_argon2_upgrade(self): self._test_argon2_upgrade("time_cost", "time cost", 1) self._test_argon2_upgrade("memory_cost", "memory cost", 64) self._test_argon2_upgrade("parallelism", "parallelism", 1) def test_argon2_version_upgrade(self): hasher = get_hasher("argon2") state = {"upgraded": False} encoded = ( "argon2$argon2id$v=19$m=102400,t=2,p=8$Y041dExhNkljRUUy$TMa6A8fPJh" "CAUXRhJXCXdw" ) def setter(password): state["upgraded"] = True old_m = hasher.memory_cost old_t = hasher.time_cost old_p = hasher.parallelism try: hasher.memory_cost = 8 hasher.time_cost = 1 hasher.parallelism = 1 self.assertTrue(check_password("secret", encoded, setter, "argon2")) self.assertTrue(state["upgraded"]) finally: hasher.memory_cost = old_m hasher.time_cost = old_t hasher.parallelism = old_p def _test_argon2_upgrade(self, attr, summary_key, new_value): hasher = get_hasher("argon2") self.assertEqual("argon2", hasher.algorithm) self.assertNotEqual(getattr(hasher, attr), new_value) old_value = getattr(hasher, attr) try: # Generate hash with attr set to 1 setattr(hasher, attr, new_value) encoded = make_password("letmein", hasher="argon2") attr_value = hasher.safe_summary(encoded)[summary_key] self.assertEqual(attr_value, new_value) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No upgrade is triggered. self.assertTrue(check_password("letmein", encoded, setter, "argon2")) self.assertFalse(state["upgraded"]) # Revert to the old rounds count and ... setattr(hasher, attr, old_value) # ... check if the password would get updated to the new count. self.assertTrue(check_password("letmein", encoded, setter, "argon2")) self.assertTrue(state["upgraded"]) finally: setattr(hasher, attr, old_value) @override_settings(PASSWORD_HASHERS=PASSWORD_HASHERS) class TestUtilsHashPassScrypt(SimpleTestCase): def test_scrypt(self): encoded = make_password("lètmein", "seasalt", "scrypt") self.assertEqual( encoded, "scrypt$16384$seasalt$8$1$Qj3+9PPyRjSJIebHnG81TMjsqtaIGxNQG/aEB/NY" "afTJ7tibgfYz71m0ldQESkXFRkdVCBhhY8mx7rQwite/Pw==", ) self.assertIs(is_password_usable(encoded), True) self.assertIs(check_password("lètmein", encoded), True) self.assertIs(check_password("lètmeinz", encoded), False) self.assertEqual(identify_hasher(encoded).algorithm, "scrypt") # Blank passwords. blank_encoded = make_password("", "seasalt", "scrypt") self.assertIs(blank_encoded.startswith("scrypt$"), True) self.assertIs(is_password_usable(blank_encoded), True) self.assertIs(check_password("", blank_encoded), True) self.assertIs(check_password(" ", blank_encoded), False) def test_scrypt_decode(self): encoded = make_password("lètmein", "seasalt", "scrypt") hasher = get_hasher("scrypt") decoded = hasher.decode(encoded) tests = [ ("block_size", hasher.block_size), ("parallelism", hasher.parallelism), ("salt", "seasalt"), ("work_factor", hasher.work_factor), ] for key, excepted in tests: with self.subTest(key=key): self.assertEqual(decoded[key], excepted) def _test_scrypt_upgrade(self, attr, summary_key, new_value): hasher = get_hasher("scrypt") self.assertEqual(hasher.algorithm, "scrypt") self.assertNotEqual(getattr(hasher, attr), new_value) old_value = getattr(hasher, attr) try: # Generate hash with attr set to the new value. setattr(hasher, attr, new_value) encoded = make_password("lètmein", "seasalt", "scrypt") attr_value = hasher.safe_summary(encoded)[summary_key] self.assertEqual(attr_value, new_value) state = {"upgraded": False} def setter(password): state["upgraded"] = True # No update is triggered. self.assertIs(check_password("lètmein", encoded, setter, "scrypt"), True) self.assertIs(state["upgraded"], False) # Revert to the old value. setattr(hasher, attr, old_value) # Password is updated. self.assertIs(check_password("lètmein", encoded, setter, "scrypt"), True) self.assertIs(state["upgraded"], True) finally: setattr(hasher, attr, old_value) def test_scrypt_upgrade(self): tests = [ ("work_factor", "work factor", 2**11), ("block_size", "block size", 10), ("parallelism", "parallelism", 2), ] for attr, summary_key, new_value in tests: with self.subTest(attr=attr): self._test_scrypt_upgrade(attr, summary_key, new_value)
aa2aadf19bf51251d64254328859eea3b670db7c0f4adbdca3c6cdbbb6586285
from django.contrib import admin from django.contrib.admin.tests import AdminSeleniumTestCase from django.contrib.auth.models import User from django.test import TestCase, override_settings from django.urls import path, reverse from .models import Héllo class AdminSiteWithSidebar(admin.AdminSite): pass class AdminSiteWithoutSidebar(admin.AdminSite): enable_nav_sidebar = False site_with_sidebar = AdminSiteWithSidebar(name="test_with_sidebar") site_without_sidebar = AdminSiteWithoutSidebar(name="test_without_sidebar") site_with_sidebar.register(User) site_with_sidebar.register(Héllo) urlpatterns = [ path("test_sidebar/admin/", site_with_sidebar.urls), path("test_wihout_sidebar/admin/", site_without_sidebar.urls), ] @override_settings(ROOT_URLCONF="admin_views.test_nav_sidebar") class AdminSidebarTests(TestCase): @classmethod def setUpTestData(cls): cls.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]", ) def setUp(self): self.client.force_login(self.superuser) def test_sidebar_not_on_index(self): response = self.client.get(reverse("test_with_sidebar:index")) self.assertContains(response, '<div class="main" id="main">') self.assertNotContains(response, '<nav class="sticky" id="nav-sidebar">') def test_sidebar_disabled(self): response = self.client.get(reverse("test_without_sidebar:index")) self.assertNotContains(response, '<nav class="sticky" id="nav-sidebar">') def test_sidebar_unauthenticated(self): self.client.logout() response = self.client.get(reverse("test_with_sidebar:login")) self.assertNotContains(response, '<nav class="sticky" id="nav-sidebar">') def test_sidebar_aria_current_page(self): url = reverse("test_with_sidebar:auth_user_changelist") response = self.client.get(url) self.assertContains(response, '<nav class="sticky" id="nav-sidebar">') self.assertContains( response, '<a href="%s" aria-current="page">Users</a>' % url ) @override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, } ] ) def test_sidebar_aria_current_page_missing_without_request_context_processor(self): url = reverse("test_with_sidebar:auth_user_changelist") response = self.client.get(url) self.assertContains(response, '<nav class="sticky" id="nav-sidebar">') # Does not include aria-current attribute. self.assertContains(response, '<a href="%s">Users</a>' % url) self.assertNotContains(response, "aria-current") @override_settings(DEBUG=True) def test_included_app_list_template_context_fully_set(self): # All context variables should be set when rendering the sidebar. url = reverse("test_with_sidebar:auth_user_changelist") with self.assertNoLogs("django.template", "DEBUG"): self.client.get(url) def test_sidebar_model_name_non_ascii(self): url = reverse("test_with_sidebar:admin_views_héllo_changelist") response = self.client.get(url) self.assertContains( response, '<div class="app-admin_views module current-app">' ) self.assertContains(response, '<tr class="model-héllo current-model">') self.assertContains( response, '<th scope="row">' '<a href="/test_sidebar/admin/admin_views/h%C3%A9llo/" aria-current="page">' "Héllos</a></th>", ) @override_settings(ROOT_URLCONF="admin_views.test_nav_sidebar") class SeleniumTests(AdminSeleniumTestCase): available_apps = ["admin_views"] + AdminSeleniumTestCase.available_apps def setUp(self): self.superuser = User.objects.create_superuser( username="super", password="secret", email="[email protected]", ) self.admin_login( username="super", password="secret", login_url=reverse("test_with_sidebar:index"), ) self.selenium.execute_script( "localStorage.removeItem('django.admin.navSidebarIsOpen')" ) def test_sidebar_starts_open(self): from selenium.webdriver.common.by import By self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) main_element = self.selenium.find_element(By.CSS_SELECTOR, "#main") self.assertIn("shifted", main_element.get_attribute("class").split()) def test_sidebar_can_be_closed(self): from selenium.webdriver.common.by import By self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) self.assertEqual(toggle_button.tag_name, "button") self.assertEqual(toggle_button.get_attribute("aria-label"), "Toggle navigation") for link in self.selenium.find_elements(By.CSS_SELECTOR, "#nav-sidebar a"): self.assertEqual(link.get_attribute("tabIndex"), "0") filter_input = self.selenium.find_element(By.CSS_SELECTOR, "#nav-filter") self.assertEqual(filter_input.get_attribute("tabIndex"), "0") toggle_button.click() # Hidden sidebar is not reachable via keyboard navigation. for link in self.selenium.find_elements(By.CSS_SELECTOR, "#nav-sidebar a"): self.assertEqual(link.get_attribute("tabIndex"), "-1") filter_input = self.selenium.find_element(By.CSS_SELECTOR, "#nav-filter") self.assertEqual(filter_input.get_attribute("tabIndex"), "-1") main_element = self.selenium.find_element(By.CSS_SELECTOR, "#main") self.assertNotIn("shifted", main_element.get_attribute("class").split()) def test_sidebar_state_persists(self): from selenium.webdriver.common.by import By self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) self.assertIsNone( self.selenium.execute_script( "return localStorage.getItem('django.admin.navSidebarIsOpen')" ) ) toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) toggle_button.click() self.assertEqual( self.selenium.execute_script( "return localStorage.getItem('django.admin.navSidebarIsOpen')" ), "false", ) self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) main_element = self.selenium.find_element(By.CSS_SELECTOR, "#main") self.assertNotIn("shifted", main_element.get_attribute("class").split()) toggle_button = self.selenium.find_element( By.CSS_SELECTOR, "#toggle-nav-sidebar" ) # Hidden sidebar is not reachable via keyboard navigation. for link in self.selenium.find_elements(By.CSS_SELECTOR, "#nav-sidebar a"): self.assertEqual(link.get_attribute("tabIndex"), "-1") filter_input = self.selenium.find_element(By.CSS_SELECTOR, "#nav-filter") self.assertEqual(filter_input.get_attribute("tabIndex"), "-1") toggle_button.click() for link in self.selenium.find_elements(By.CSS_SELECTOR, "#nav-sidebar a"): self.assertEqual(link.get_attribute("tabIndex"), "0") filter_input = self.selenium.find_element(By.CSS_SELECTOR, "#nav-filter") self.assertEqual(filter_input.get_attribute("tabIndex"), "0") self.assertEqual( self.selenium.execute_script( "return localStorage.getItem('django.admin.navSidebarIsOpen')" ), "true", ) self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) main_element = self.selenium.find_element(By.CSS_SELECTOR, "#main") self.assertIn("shifted", main_element.get_attribute("class").split()) def test_sidebar_filter_persists(self): from selenium.webdriver.common.by import By self.selenium.get( self.live_server_url + reverse("test_with_sidebar:auth_user_changelist") ) filter_value_script = ( "return sessionStorage.getItem('django.admin.navSidebarFilterValue')" ) self.assertIsNone(self.selenium.execute_script(filter_value_script)) filter_input = self.selenium.find_element(By.CSS_SELECTOR, "#nav-filter") filter_input.send_keys("users") self.assertEqual(self.selenium.execute_script(filter_value_script), "users")
b4b7d9a4748ab0aed3631824f58098ea32168569dbebc17e17c558bcbe19109a
import unittest from django.contrib.admindocs.utils import ( _is_callback, docutils_is_available, parse_docstring, parse_rst, ) from django.test.utils import captured_stderr from django.urls import get_resolver from .tests import AdminDocsSimpleTestCase, SimpleTestCase @unittest.skipUnless(docutils_is_available, "no docutils installed.") class TestUtils(AdminDocsSimpleTestCase): """ This __doc__ output is required for testing. I copied this example from `admindocs` documentation. (TITLE) Display an individual :model:`myapp.MyModel`. **Context** ``RequestContext`` ``mymodel`` An instance of :model:`myapp.MyModel`. **Template:** :template:`myapp/my_template.html` (DESCRIPTION) some_metadata: some data """ def setUp(self): self.docstring = self.__doc__ def test_parse_docstring(self): title, description, metadata = parse_docstring(self.docstring) docstring_title = ( "This __doc__ output is required for testing. I copied this example from\n" "`admindocs` documentation. (TITLE)" ) docstring_description = ( "Display an individual :model:`myapp.MyModel`.\n\n" "**Context**\n\n``RequestContext``\n\n``mymodel``\n" " An instance of :model:`myapp.MyModel`.\n\n" "**Template:**\n\n:template:`myapp/my_template.html` " "(DESCRIPTION)" ) self.assertEqual(title, docstring_title) self.assertEqual(description, docstring_description) self.assertEqual(metadata, {"some_metadata": "some data"}) def test_title_output(self): title, description, metadata = parse_docstring(self.docstring) title_output = parse_rst(title, "model", "model:admindocs") self.assertIn("TITLE", title_output) title_rendered = ( "<p>This __doc__ output is required for testing. I copied this " 'example from\n<a class="reference external" ' 'href="/admindocs/models/admindocs/">admindocs</a> documentation. ' "(TITLE)</p>\n" ) self.assertHTMLEqual(title_output, title_rendered) def test_description_output(self): title, description, metadata = parse_docstring(self.docstring) description_output = parse_rst(description, "model", "model:admindocs") description_rendered = ( '<p>Display an individual <a class="reference external" ' 'href="/admindocs/models/myapp.mymodel/">myapp.MyModel</a>.</p>\n' '<p><strong>Context</strong></p>\n<p><tt class="docutils literal">' 'RequestContext</tt></p>\n<dl class="docutils">\n<dt><tt class="' 'docutils literal">mymodel</tt></dt>\n<dd>An instance of <a class="' 'reference external" href="/admindocs/models/myapp.mymodel/">' "myapp.MyModel</a>.</dd>\n</dl>\n<p><strong>Template:</strong></p>" '\n<p><a class="reference external" href="/admindocs/templates/' 'myapp/my_template.html/">myapp/my_template.html</a> (DESCRIPTION)' "</p>\n" ) self.assertHTMLEqual(description_output, description_rendered) def test_initial_header_level(self): header = "should be h3...\n\nHeader\n------\n" output = parse_rst(header, "header") self.assertIn("<h3>Header</h3>", output) def test_parse_rst(self): """ parse_rst() should use `cmsreference` as the default role. """ markup = '<p><a class="reference external" href="/admindocs/%s">title</a></p>\n' self.assertEqual(parse_rst("`title`", "model"), markup % "models/title/") self.assertEqual(parse_rst("`title`", "view"), markup % "views/title/") self.assertEqual(parse_rst("`title`", "template"), markup % "templates/title/") self.assertEqual(parse_rst("`title`", "filter"), markup % "filters/#title") self.assertEqual(parse_rst("`title`", "tag"), markup % "tags/#title") def test_parse_rst_with_docstring_no_leading_line_feed(self): title, body, _ = parse_docstring("firstline\n\n second line") with captured_stderr() as stderr: self.assertEqual(parse_rst(title, ""), "<p>firstline</p>\n") self.assertEqual(parse_rst(body, ""), "<p>second line</p>\n") self.assertEqual(stderr.getvalue(), "") def test_publish_parts(self): """ Django shouldn't break the default role for interpreted text when ``publish_parts`` is used directly, by setting it to ``cmsreference`` (#6681). """ import docutils self.assertNotEqual( docutils.parsers.rst.roles.DEFAULT_INTERPRETED_ROLE, "cmsreference" ) source = "reST, `interpreted text`, default role." markup = "<p>reST, <cite>interpreted text</cite>, default role.</p>\n" parts = docutils.core.publish_parts(source=source, writer_name="html4css1") self.assertEqual(parts["fragment"], markup) class TestResolver(SimpleTestCase): def test_namespaced_view_detail(self): resolver = get_resolver("urlpatterns_reverse.nested_urls") self.assertTrue(_is_callback("urlpatterns_reverse.nested_urls.view1", resolver)) self.assertTrue(_is_callback("urlpatterns_reverse.nested_urls.view2", resolver)) self.assertTrue(_is_callback("urlpatterns_reverse.nested_urls.View3", resolver)) self.assertFalse(_is_callback("urlpatterns_reverse.nested_urls.blub", resolver)) def test_view_detail_as_method(self): # Views which have a class name as part of their path. resolver = get_resolver("urlpatterns_reverse.method_view_urls") self.assertTrue( _is_callback( "urlpatterns_reverse.method_view_urls.ViewContainer.method_view", resolver, ) ) self.assertTrue( _is_callback( "urlpatterns_reverse.method_view_urls.ViewContainer.classmethod_view", resolver, ) )
c6a6b5c35c05eea32565de958c42eadb44cfe26c7260e6473d282dab79ad9997
import decimal import enum import json import unittest import uuid from django import forms from django.core import checks, exceptions, serializers, validators from django.core.exceptions import FieldError from django.core.management import call_command from django.db import IntegrityError, connection, models from django.db.models.expressions import Exists, OuterRef, RawSQL, Value from django.db.models.functions import Cast, JSONObject, Upper from django.test import TransactionTestCase, modify_settings, override_settings from django.test.utils import isolate_apps from django.utils import timezone from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase, PostgreSQLWidgetTestCase from .models import ( ArrayEnumModel, ArrayFieldSubclass, CharArrayModel, DateTimeArrayModel, IntegerArrayModel, NestedIntegerArrayModel, NullableIntegerArrayModel, OtherTypesArrayModel, PostgreSQLModel, Tag, ) try: from psycopg2.extras import NumericRange from django.contrib.postgres.aggregates import ArrayAgg from django.contrib.postgres.expressions import ArraySubquery from django.contrib.postgres.fields import ArrayField from django.contrib.postgres.fields.array import IndexTransform, SliceTransform from django.contrib.postgres.forms import ( SimpleArrayField, SplitArrayField, SplitArrayWidget, ) except ImportError: pass @isolate_apps("postgres_tests") class BasicTests(PostgreSQLSimpleTestCase): def test_get_field_display(self): class MyModel(PostgreSQLModel): field = ArrayField( models.CharField(max_length=16), choices=[ ["Media", [(["vinyl", "cd"], "Audio")]], (("mp3", "mp4"), "Digital"), ], ) tests = ( (["vinyl", "cd"], "Audio"), (("mp3", "mp4"), "Digital"), (("a", "b"), "('a', 'b')"), (["c", "d"], "['c', 'd']"), ) for value, display in tests: with self.subTest(value=value, display=display): instance = MyModel(field=value) self.assertEqual(instance.get_field_display(), display) def test_get_field_display_nested_array(self): class MyModel(PostgreSQLModel): field = ArrayField( ArrayField(models.CharField(max_length=16)), choices=[ [ "Media", [([["vinyl", "cd"], ("x",)], "Audio")], ], ((["mp3"], ("mp4",)), "Digital"), ], ) tests = ( ([["vinyl", "cd"], ("x",)], "Audio"), ((["mp3"], ("mp4",)), "Digital"), ((("a", "b"), ("c",)), "(('a', 'b'), ('c',))"), ([["a", "b"], ["c"]], "[['a', 'b'], ['c']]"), ) for value, display in tests: with self.subTest(value=value, display=display): instance = MyModel(field=value) self.assertEqual(instance.get_field_display(), display) class TestSaveLoad(PostgreSQLTestCase): def test_integer(self): instance = IntegerArrayModel(field=[1, 2, 3]) instance.save() loaded = IntegerArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) def test_char(self): instance = CharArrayModel(field=["hello", "goodbye"]) instance.save() loaded = CharArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) def test_dates(self): instance = DateTimeArrayModel( datetimes=[timezone.now()], dates=[timezone.now().date()], times=[timezone.now().time()], ) instance.save() loaded = DateTimeArrayModel.objects.get() self.assertEqual(instance.datetimes, loaded.datetimes) self.assertEqual(instance.dates, loaded.dates) self.assertEqual(instance.times, loaded.times) def test_tuples(self): instance = IntegerArrayModel(field=(1,)) instance.save() loaded = IntegerArrayModel.objects.get() self.assertSequenceEqual(instance.field, loaded.field) def test_integers_passed_as_strings(self): # This checks that get_prep_value is deferred properly instance = IntegerArrayModel(field=["1"]) instance.save() loaded = IntegerArrayModel.objects.get() self.assertEqual(loaded.field, [1]) def test_default_null(self): instance = NullableIntegerArrayModel() instance.save() loaded = NullableIntegerArrayModel.objects.get(pk=instance.pk) self.assertIsNone(loaded.field) self.assertEqual(instance.field, loaded.field) def test_null_handling(self): instance = NullableIntegerArrayModel(field=None) instance.save() loaded = NullableIntegerArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) instance = IntegerArrayModel(field=None) with self.assertRaises(IntegrityError): instance.save() def test_nested(self): instance = NestedIntegerArrayModel(field=[[1, 2], [3, 4]]) instance.save() loaded = NestedIntegerArrayModel.objects.get() self.assertEqual(instance.field, loaded.field) def test_other_array_types(self): instance = OtherTypesArrayModel( ips=["192.168.0.1", "::1"], uuids=[uuid.uuid4()], decimals=[decimal.Decimal(1.25), 1.75], tags=[Tag(1), Tag(2), Tag(3)], json=[{"a": 1}, {"b": 2}], int_ranges=[NumericRange(10, 20), NumericRange(30, 40)], bigint_ranges=[ NumericRange(7000000000, 10000000000), NumericRange(50000000000, 70000000000), ], ) instance.save() loaded = OtherTypesArrayModel.objects.get() self.assertEqual(instance.ips, loaded.ips) self.assertEqual(instance.uuids, loaded.uuids) self.assertEqual(instance.decimals, loaded.decimals) self.assertEqual(instance.tags, loaded.tags) self.assertEqual(instance.json, loaded.json) self.assertEqual(instance.int_ranges, loaded.int_ranges) self.assertEqual(instance.bigint_ranges, loaded.bigint_ranges) def test_null_from_db_value_handling(self): instance = OtherTypesArrayModel.objects.create( ips=["192.168.0.1", "::1"], uuids=[uuid.uuid4()], decimals=[decimal.Decimal(1.25), 1.75], tags=None, ) instance.refresh_from_db() self.assertIsNone(instance.tags) self.assertEqual(instance.json, []) self.assertIsNone(instance.int_ranges) self.assertIsNone(instance.bigint_ranges) def test_model_set_on_base_field(self): instance = IntegerArrayModel() field = instance._meta.get_field("field") self.assertEqual(field.model, IntegerArrayModel) self.assertEqual(field.base_field.model, IntegerArrayModel) def test_nested_nullable_base_field(self): instance = NullableIntegerArrayModel.objects.create( field_nested=[[None, None], [None, None]], ) self.assertEqual(instance.field_nested, [[None, None], [None, None]]) class TestQuerying(PostgreSQLTestCase): @classmethod def setUpTestData(cls): cls.objs = NullableIntegerArrayModel.objects.bulk_create( [ NullableIntegerArrayModel(order=1, field=[1]), NullableIntegerArrayModel(order=2, field=[2]), NullableIntegerArrayModel(order=3, field=[2, 3]), NullableIntegerArrayModel(order=4, field=[20, 30, 40]), NullableIntegerArrayModel(order=5, field=None), ] ) def test_empty_list(self): NullableIntegerArrayModel.objects.create(field=[]) obj = ( NullableIntegerArrayModel.objects.annotate( empty_array=models.Value( [], output_field=ArrayField(models.IntegerField()) ), ) .filter(field=models.F("empty_array")) .get() ) self.assertEqual(obj.field, []) self.assertEqual(obj.empty_array, []) def test_exact(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__exact=[1]), self.objs[:1] ) def test_exact_with_expression(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__exact=[Value(1)]), self.objs[:1], ) def test_exact_charfield(self): instance = CharArrayModel.objects.create(field=["text"]) self.assertSequenceEqual( CharArrayModel.objects.filter(field=["text"]), [instance] ) def test_exact_nested(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field=[[1, 2], [3, 4]]), [instance] ) def test_isnull(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__isnull=True), self.objs[-1:] ) def test_gt(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__gt=[0]), self.objs[:4] ) def test_lt(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__lt=[2]), self.objs[:1] ) def test_in(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__in=[[1], [2]]), self.objs[:2], ) def test_in_subquery(self): IntegerArrayModel.objects.create(field=[2, 3]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__in=IntegerArrayModel.objects.values_list("field", flat=True) ), self.objs[2:3], ) @unittest.expectedFailure def test_in_including_F_object(self): # This test asserts that Array objects passed to filters can be # constructed to contain F objects. This currently doesn't work as the # psycopg2 mogrify method that generates the ARRAY() syntax is # expecting literals, not column references (#27095). self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__in=[[models.F("id")]]), self.objs[:2], ) def test_in_as_F_object(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__in=[models.F("field")]), self.objs[:4], ) def test_contained_by(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__contained_by=[1, 2]), self.objs[:2], ) def test_contained_by_including_F_object(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__contained_by=[models.F("order"), 2] ), self.objs[:3], ) def test_contains(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__contains=[2]), self.objs[1:3], ) def test_contains_subquery(self): IntegerArrayModel.objects.create(field=[2, 3]) inner_qs = IntegerArrayModel.objects.values_list("field", flat=True) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__contains=inner_qs[:1]), self.objs[2:3], ) inner_qs = IntegerArrayModel.objects.filter(field__contains=OuterRef("field")) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(Exists(inner_qs)), self.objs[1:3], ) def test_contains_including_expression(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__contains=[2, Value(6) / Value(2)], ), self.objs[2:3], ) def test_icontains(self): # Using the __icontains lookup with ArrayField is inefficient. instance = CharArrayModel.objects.create(field=["FoO"]) self.assertSequenceEqual( CharArrayModel.objects.filter(field__icontains="foo"), [instance] ) def test_contains_charfield(self): # Regression for #22907 self.assertSequenceEqual( CharArrayModel.objects.filter(field__contains=["text"]), [] ) def test_contained_by_charfield(self): self.assertSequenceEqual( CharArrayModel.objects.filter(field__contained_by=["text"]), [] ) def test_overlap_charfield(self): self.assertSequenceEqual( CharArrayModel.objects.filter(field__overlap=["text"]), [] ) def test_overlap_charfield_including_expression(self): obj_1 = CharArrayModel.objects.create(field=["TEXT", "lower text"]) obj_2 = CharArrayModel.objects.create(field=["lower text", "TEXT"]) CharArrayModel.objects.create(field=["lower text", "text"]) self.assertSequenceEqual( CharArrayModel.objects.filter( field__overlap=[ Upper(Value("text")), "other", ] ), [obj_1, obj_2], ) def test_lookups_autofield_array(self): qs = ( NullableIntegerArrayModel.objects.filter( field__0__isnull=False, ) .values("field__0") .annotate( arrayagg=ArrayAgg("id"), ) .order_by("field__0") ) tests = ( ("contained_by", [self.objs[1].pk, self.objs[2].pk, 0], [2]), ("contains", [self.objs[2].pk], [2]), ("exact", [self.objs[3].pk], [20]), ("overlap", [self.objs[1].pk, self.objs[3].pk], [2, 20]), ) for lookup, value, expected in tests: with self.subTest(lookup=lookup): self.assertSequenceEqual( qs.filter( **{"arrayagg__" + lookup: value}, ).values_list("field__0", flat=True), expected, ) def test_index(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0=2), self.objs[1:3] ) def test_index_chained(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0__lt=3), self.objs[0:3] ) def test_index_nested(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field__0__0=1), [instance] ) @unittest.expectedFailure def test_index_used_on_nested_data(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field__0=[1, 2]), [instance] ) def test_index_transform_expression(self): expr = RawSQL("string_to_array(%s, ';')", ["1;2"]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__0=Cast( IndexTransform(1, models.IntegerField, expr), output_field=models.IntegerField(), ), ), self.objs[:1], ) def test_index_annotation(self): qs = NullableIntegerArrayModel.objects.annotate(second=models.F("field__1")) self.assertCountEqual( qs.values_list("second", flat=True), [None, None, None, 3, 30], ) def test_overlap(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__overlap=[1, 2]), self.objs[0:3], ) def test_len(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__len__lte=2), self.objs[0:3] ) def test_len_empty_array(self): obj = NullableIntegerArrayModel.objects.create(field=[]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__len=0), [obj] ) def test_slice(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0_1=[2]), self.objs[1:3] ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter(field__0_2=[2, 3]), self.objs[2:3] ) def test_order_by_slice(self): more_objs = ( NullableIntegerArrayModel.objects.create(field=[1, 637]), NullableIntegerArrayModel.objects.create(field=[2, 1]), NullableIntegerArrayModel.objects.create(field=[3, -98123]), NullableIntegerArrayModel.objects.create(field=[4, 2]), ) self.assertSequenceEqual( NullableIntegerArrayModel.objects.order_by("field__1"), [ more_objs[2], more_objs[1], more_objs[3], self.objs[2], self.objs[3], more_objs[0], self.objs[4], self.objs[1], self.objs[0], ], ) @unittest.expectedFailure def test_slice_nested(self): instance = NestedIntegerArrayModel.objects.create(field=[[1, 2], [3, 4]]) self.assertSequenceEqual( NestedIntegerArrayModel.objects.filter(field__0__0_1=[1]), [instance] ) def test_slice_transform_expression(self): expr = RawSQL("string_to_array(%s, ';')", ["9;2;3"]) self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( field__0_2=SliceTransform(2, 3, expr) ), self.objs[2:3], ) def test_slice_annotation(self): qs = NullableIntegerArrayModel.objects.annotate( first_two=models.F("field__0_2"), ) self.assertCountEqual( qs.values_list("first_two", flat=True), [None, [1], [2], [2, 3], [20, 30]], ) def test_usage_in_subquery(self): self.assertSequenceEqual( NullableIntegerArrayModel.objects.filter( id__in=NullableIntegerArrayModel.objects.filter(field__len=3) ), [self.objs[3]], ) def test_enum_lookup(self): class TestEnum(enum.Enum): VALUE_1 = "value_1" instance = ArrayEnumModel.objects.create(array_of_enums=[TestEnum.VALUE_1]) self.assertSequenceEqual( ArrayEnumModel.objects.filter(array_of_enums__contains=[TestEnum.VALUE_1]), [instance], ) def test_unsupported_lookup(self): msg = ( "Unsupported lookup '0_bar' for ArrayField or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): list(NullableIntegerArrayModel.objects.filter(field__0_bar=[2])) msg = ( "Unsupported lookup '0bar' for ArrayField or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): list(NullableIntegerArrayModel.objects.filter(field__0bar=[2])) def test_grouping_by_annotations_with_array_field_param(self): value = models.Value([1], output_field=ArrayField(models.IntegerField())) self.assertEqual( NullableIntegerArrayModel.objects.annotate( array_length=models.Func( value, 1, function="ARRAY_LENGTH", output_field=models.IntegerField(), ), ) .values("array_length") .annotate( count=models.Count("pk"), ) .get()["array_length"], 1, ) def test_filter_by_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.filter( field__len=models.OuterRef("field__len"), ).values("field") self.assertSequenceEqual( NullableIntegerArrayModel.objects.alias( same_sized_fields=ArraySubquery(inner_qs), ).filter(same_sized_fields__len__gt=1), self.objs[0:2], ) def test_annotated_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.exclude( pk=models.OuterRef("pk") ).values("order") self.assertSequenceEqual( NullableIntegerArrayModel.objects.annotate( sibling_ids=ArraySubquery(inner_qs), ) .get(order=1) .sibling_ids, [2, 3, 4, 5], ) def test_group_by_with_annotated_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.exclude( pk=models.OuterRef("pk") ).values("order") self.assertSequenceEqual( NullableIntegerArrayModel.objects.annotate( sibling_ids=ArraySubquery(inner_qs), sibling_count=models.Max("sibling_ids__len"), ).values_list("sibling_count", flat=True), [len(self.objs) - 1] * len(self.objs), ) def test_annotated_ordered_array_subquery(self): inner_qs = NullableIntegerArrayModel.objects.order_by("-order").values("order") self.assertSequenceEqual( NullableIntegerArrayModel.objects.annotate( ids=ArraySubquery(inner_qs), ) .first() .ids, [5, 4, 3, 2, 1], ) def test_annotated_array_subquery_with_json_objects(self): inner_qs = NullableIntegerArrayModel.objects.exclude( pk=models.OuterRef("pk") ).values(json=JSONObject(order="order", field="field")) siblings_json = ( NullableIntegerArrayModel.objects.annotate( siblings_json=ArraySubquery(inner_qs), ) .values_list("siblings_json", flat=True) .get(order=1) ) self.assertSequenceEqual( siblings_json, [ {"field": [2], "order": 2}, {"field": [2, 3], "order": 3}, {"field": [20, 30, 40], "order": 4}, {"field": None, "order": 5}, ], ) class TestDateTimeExactQuerying(PostgreSQLTestCase): @classmethod def setUpTestData(cls): now = timezone.now() cls.datetimes = [now] cls.dates = [now.date()] cls.times = [now.time()] cls.objs = [ DateTimeArrayModel.objects.create( datetimes=cls.datetimes, dates=cls.dates, times=cls.times ), ] def test_exact_datetimes(self): self.assertSequenceEqual( DateTimeArrayModel.objects.filter(datetimes=self.datetimes), self.objs ) def test_exact_dates(self): self.assertSequenceEqual( DateTimeArrayModel.objects.filter(dates=self.dates), self.objs ) def test_exact_times(self): self.assertSequenceEqual( DateTimeArrayModel.objects.filter(times=self.times), self.objs ) class TestOtherTypesExactQuerying(PostgreSQLTestCase): @classmethod def setUpTestData(cls): cls.ips = ["192.168.0.1", "::1"] cls.uuids = [uuid.uuid4()] cls.decimals = [decimal.Decimal(1.25), 1.75] cls.tags = [Tag(1), Tag(2), Tag(3)] cls.objs = [ OtherTypesArrayModel.objects.create( ips=cls.ips, uuids=cls.uuids, decimals=cls.decimals, tags=cls.tags, ) ] def test_exact_ip_addresses(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(ips=self.ips), self.objs ) def test_exact_uuids(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(uuids=self.uuids), self.objs ) def test_exact_decimals(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(decimals=self.decimals), self.objs ) def test_exact_tags(self): self.assertSequenceEqual( OtherTypesArrayModel.objects.filter(tags=self.tags), self.objs ) @isolate_apps("postgres_tests") class TestChecks(PostgreSQLSimpleTestCase): def test_field_checks(self): class MyModel(PostgreSQLModel): field = ArrayField(models.CharField()) model = MyModel() errors = model.check() self.assertEqual(len(errors), 1) # The inner CharField is missing a max_length. self.assertEqual(errors[0].id, "postgres.E001") self.assertIn("max_length", errors[0].msg) def test_invalid_base_fields(self): class MyModel(PostgreSQLModel): field = ArrayField( models.ManyToManyField("postgres_tests.IntegerArrayModel") ) model = MyModel() errors = model.check() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].id, "postgres.E002") def test_invalid_default(self): class MyModel(PostgreSQLModel): field = ArrayField(models.IntegerField(), default=[]) model = MyModel() self.assertEqual( model.check(), [ checks.Warning( msg=( "ArrayField default should be a callable instead of an " "instance so that it's not shared between all field " "instances." ), hint="Use a callable instead, e.g., use `list` instead of `[]`.", obj=MyModel._meta.get_field("field"), id="fields.E010", ) ], ) def test_valid_default(self): class MyModel(PostgreSQLModel): field = ArrayField(models.IntegerField(), default=list) model = MyModel() self.assertEqual(model.check(), []) def test_valid_default_none(self): class MyModel(PostgreSQLModel): field = ArrayField(models.IntegerField(), default=None) model = MyModel() self.assertEqual(model.check(), []) def test_nested_field_checks(self): """ Nested ArrayFields are permitted. """ class MyModel(PostgreSQLModel): field = ArrayField(ArrayField(models.CharField())) model = MyModel() errors = model.check() self.assertEqual(len(errors), 1) # The inner CharField is missing a max_length. self.assertEqual(errors[0].id, "postgres.E001") self.assertIn("max_length", errors[0].msg) def test_choices_tuple_list(self): class MyModel(PostgreSQLModel): field = ArrayField( models.CharField(max_length=16), choices=[ [ "Media", [(["vinyl", "cd"], "Audio"), (("vhs", "dvd"), "Video")], ], (["mp3", "mp4"], "Digital"), ], ) self.assertEqual(MyModel._meta.get_field("field").check(), []) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests") class TestMigrations(TransactionTestCase): available_apps = ["postgres_tests"] def test_deconstruct(self): field = ArrayField(models.IntegerField()) name, path, args, kwargs = field.deconstruct() new = ArrayField(*args, **kwargs) self.assertEqual(type(new.base_field), type(field.base_field)) self.assertIsNot(new.base_field, field.base_field) def test_deconstruct_with_size(self): field = ArrayField(models.IntegerField(), size=3) name, path, args, kwargs = field.deconstruct() new = ArrayField(*args, **kwargs) self.assertEqual(new.size, field.size) def test_deconstruct_args(self): field = ArrayField(models.CharField(max_length=20)) name, path, args, kwargs = field.deconstruct() new = ArrayField(*args, **kwargs) self.assertEqual(new.base_field.max_length, field.base_field.max_length) def test_subclass_deconstruct(self): field = ArrayField(models.IntegerField()) name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "django.contrib.postgres.fields.ArrayField") field = ArrayFieldSubclass() name, path, args, kwargs = field.deconstruct() self.assertEqual(path, "postgres_tests.models.ArrayFieldSubclass") @override_settings( MIGRATION_MODULES={ "postgres_tests": "postgres_tests.array_default_migrations", } ) def test_adding_field_with_default(self): # See #22962 table_name = "postgres_tests_integerarraydefaultmodel" with connection.cursor() as cursor: self.assertNotIn(table_name, connection.introspection.table_names(cursor)) call_command("migrate", "postgres_tests", verbosity=0) with connection.cursor() as cursor: self.assertIn(table_name, connection.introspection.table_names(cursor)) call_command("migrate", "postgres_tests", "zero", verbosity=0) with connection.cursor() as cursor: self.assertNotIn(table_name, connection.introspection.table_names(cursor)) @override_settings( MIGRATION_MODULES={ "postgres_tests": "postgres_tests.array_index_migrations", } ) def test_adding_arrayfield_with_index(self): """ ArrayField shouldn't have varchar_patterns_ops or text_patterns_ops indexes. """ table_name = "postgres_tests_chartextarrayindexmodel" call_command("migrate", "postgres_tests", verbosity=0) with connection.cursor() as cursor: like_constraint_columns_list = [ v["columns"] for k, v in list( connection.introspection.get_constraints(cursor, table_name).items() ) if k.endswith("_like") ] # Only the CharField should have a LIKE index. self.assertEqual(like_constraint_columns_list, [["char2"]]) # All fields should have regular indexes. with connection.cursor() as cursor: indexes = [ c["columns"][0] for c in connection.introspection.get_constraints( cursor, table_name ).values() if c["index"] and len(c["columns"]) == 1 ] self.assertIn("char", indexes) self.assertIn("char2", indexes) self.assertIn("text", indexes) call_command("migrate", "postgres_tests", "zero", verbosity=0) with connection.cursor() as cursor: self.assertNotIn(table_name, connection.introspection.table_names(cursor)) class TestSerialization(PostgreSQLSimpleTestCase): test_data = ( '[{"fields": {"field": "[\\"1\\", \\"2\\", null]"}, ' '"model": "postgres_tests.integerarraymodel", "pk": null}]' ) def test_dumping(self): instance = IntegerArrayModel(field=[1, 2, None]) data = serializers.serialize("json", [instance]) self.assertEqual(json.loads(data), json.loads(self.test_data)) def test_loading(self): instance = list(serializers.deserialize("json", self.test_data))[0].object self.assertEqual(instance.field, [1, 2, None]) class TestValidation(PostgreSQLSimpleTestCase): def test_unbounded(self): field = ArrayField(models.IntegerField()) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([1, None], None) self.assertEqual(cm.exception.code, "item_invalid") self.assertEqual( cm.exception.message % cm.exception.params, "Item 2 in the array did not validate: This field cannot be null.", ) def test_blank_true(self): field = ArrayField(models.IntegerField(blank=True, null=True)) # This should not raise a validation error field.clean([1, None], None) def test_with_size(self): field = ArrayField(models.IntegerField(), size=3) field.clean([1, 2, 3], None) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([1, 2, 3, 4], None) self.assertEqual( cm.exception.messages[0], "List contains 4 items, it should contain no more than 3.", ) def test_nested_array_mismatch(self): field = ArrayField(ArrayField(models.IntegerField())) field.clean([[1, 2], [3, 4]], None) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([[1, 2], [3, 4, 5]], None) self.assertEqual(cm.exception.code, "nested_array_mismatch") self.assertEqual( cm.exception.messages[0], "Nested arrays must have the same length." ) def test_with_base_field_error_params(self): field = ArrayField(models.CharField(max_length=2)) with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["abc"], None) self.assertEqual(len(cm.exception.error_list), 1) exception = cm.exception.error_list[0] self.assertEqual( exception.message, "Item 1 in the array did not validate: Ensure this value has at most 2 " "characters (it has 3).", ) self.assertEqual(exception.code, "item_invalid") self.assertEqual( exception.params, {"nth": 1, "value": "abc", "limit_value": 2, "show_value": 3}, ) def test_with_validators(self): field = ArrayField( models.IntegerField(validators=[validators.MinValueValidator(1)]) ) field.clean([1, 2], None) with self.assertRaises(exceptions.ValidationError) as cm: field.clean([0], None) self.assertEqual(len(cm.exception.error_list), 1) exception = cm.exception.error_list[0] self.assertEqual( exception.message, "Item 1 in the array did not validate: Ensure this value is greater than " "or equal to 1.", ) self.assertEqual(exception.code, "item_invalid") self.assertEqual( exception.params, {"nth": 1, "value": 0, "limit_value": 1, "show_value": 0} ) class TestSimpleFormField(PostgreSQLSimpleTestCase): def test_valid(self): field = SimpleArrayField(forms.CharField()) value = field.clean("a,b,c") self.assertEqual(value, ["a", "b", "c"]) def test_to_python_fail(self): field = SimpleArrayField(forms.IntegerField()) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,9") self.assertEqual( cm.exception.messages[0], "Item 1 in the array did not validate: Enter a whole number.", ) def test_validate_fail(self): field = SimpleArrayField(forms.CharField(required=True)) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,") self.assertEqual( cm.exception.messages[0], "Item 3 in the array did not validate: This field is required.", ) def test_validate_fail_base_field_error_params(self): field = SimpleArrayField(forms.CharField(max_length=2)) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("abc,c,defg") errors = cm.exception.error_list self.assertEqual(len(errors), 2) first_error = errors[0] self.assertEqual( first_error.message, "Item 1 in the array did not validate: Ensure this value has at most 2 " "characters (it has 3).", ) self.assertEqual(first_error.code, "item_invalid") self.assertEqual( first_error.params, {"nth": 1, "value": "abc", "limit_value": 2, "show_value": 3}, ) second_error = errors[1] self.assertEqual( second_error.message, "Item 3 in the array did not validate: Ensure this value has at most 2 " "characters (it has 4).", ) self.assertEqual(second_error.code, "item_invalid") self.assertEqual( second_error.params, {"nth": 3, "value": "defg", "limit_value": 2, "show_value": 4}, ) def test_validators_fail(self): field = SimpleArrayField(forms.RegexField("[a-e]{2}")) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,bc,de") self.assertEqual( cm.exception.messages[0], "Item 1 in the array did not validate: Enter a valid value.", ) def test_delimiter(self): field = SimpleArrayField(forms.CharField(), delimiter="|") value = field.clean("a|b|c") self.assertEqual(value, ["a", "b", "c"]) def test_delimiter_with_nesting(self): field = SimpleArrayField(SimpleArrayField(forms.CharField()), delimiter="|") value = field.clean("a,b|c,d") self.assertEqual(value, [["a", "b"], ["c", "d"]]) def test_prepare_value(self): field = SimpleArrayField(forms.CharField()) value = field.prepare_value(["a", "b", "c"]) self.assertEqual(value, "a,b,c") def test_max_length(self): field = SimpleArrayField(forms.CharField(), max_length=2) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,c") self.assertEqual( cm.exception.messages[0], "List contains 3 items, it should contain no more than 2.", ) def test_min_length(self): field = SimpleArrayField(forms.CharField(), min_length=4) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("a,b,c") self.assertEqual( cm.exception.messages[0], "List contains 3 items, it should contain no fewer than 4.", ) def test_required(self): field = SimpleArrayField(forms.CharField(), required=True) with self.assertRaises(exceptions.ValidationError) as cm: field.clean("") self.assertEqual(cm.exception.messages[0], "This field is required.") def test_model_field_formfield(self): model_field = ArrayField(models.CharField(max_length=27)) form_field = model_field.formfield() self.assertIsInstance(form_field, SimpleArrayField) self.assertIsInstance(form_field.base_field, forms.CharField) self.assertEqual(form_field.base_field.max_length, 27) def test_model_field_formfield_size(self): model_field = ArrayField(models.CharField(max_length=27), size=4) form_field = model_field.formfield() self.assertIsInstance(form_field, SimpleArrayField) self.assertEqual(form_field.max_length, 4) def test_model_field_choices(self): model_field = ArrayField(models.IntegerField(choices=((1, "A"), (2, "B")))) form_field = model_field.formfield() self.assertEqual(form_field.clean("1,2"), [1, 2]) def test_already_converted_value(self): field = SimpleArrayField(forms.CharField()) vals = ["a", "b", "c"] self.assertEqual(field.clean(vals), vals) def test_has_changed(self): field = SimpleArrayField(forms.IntegerField()) self.assertIs(field.has_changed([1, 2], [1, 2]), False) self.assertIs(field.has_changed([1, 2], "1,2"), False) self.assertIs(field.has_changed([1, 2], "1,2,3"), True) self.assertIs(field.has_changed([1, 2], "a,b"), True) def test_has_changed_empty(self): field = SimpleArrayField(forms.CharField()) self.assertIs(field.has_changed(None, None), False) self.assertIs(field.has_changed(None, ""), False) self.assertIs(field.has_changed(None, []), False) self.assertIs(field.has_changed([], None), False) self.assertIs(field.has_changed([], ""), False) class TestSplitFormField(PostgreSQLSimpleTestCase): def test_valid(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), size=3) data = {"array_0": "a", "array_1": "b", "array_2": "c"} form = SplitForm(data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {"array": ["a", "b", "c"]}) def test_required(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), required=True, size=3) data = {"array_0": "", "array_1": "", "array_2": ""} form = SplitForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {"array": ["This field is required."]}) def test_remove_trailing_nulls(self): class SplitForm(forms.Form): array = SplitArrayField( forms.CharField(required=False), size=5, remove_trailing_nulls=True ) data = { "array_0": "a", "array_1": "", "array_2": "b", "array_3": "", "array_4": "", } form = SplitForm(data) self.assertTrue(form.is_valid(), form.errors) self.assertEqual(form.cleaned_data, {"array": ["a", "", "b"]}) def test_remove_trailing_nulls_not_required(self): class SplitForm(forms.Form): array = SplitArrayField( forms.CharField(required=False), size=2, remove_trailing_nulls=True, required=False, ) data = {"array_0": "", "array_1": ""} form = SplitForm(data) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {"array": []}) def test_required_field(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), size=3) data = {"array_0": "a", "array_1": "b", "array_2": ""} form = SplitForm(data) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "array": [ "Item 3 in the array did not validate: This field is required." ] }, ) def test_invalid_integer(self): msg = ( "Item 2 in the array did not validate: Ensure this value is less than or " "equal to 100." ) with self.assertRaisesMessage(exceptions.ValidationError, msg): SplitArrayField(forms.IntegerField(max_value=100), size=2).clean([0, 101]) # To locate the widget's template. @modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"}) def test_rendering(self): class SplitForm(forms.Form): array = SplitArrayField(forms.CharField(), size=3) self.assertHTMLEqual( str(SplitForm()), """ <div> <label for="id_array_0">Array:</label> <input id="id_array_0" name="array_0" type="text" required> <input id="id_array_1" name="array_1" type="text" required> <input id="id_array_2" name="array_2" type="text" required> </div> """, ) def test_invalid_char_length(self): field = SplitArrayField(forms.CharField(max_length=2), size=3) with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["abc", "c", "defg"]) self.assertEqual( cm.exception.messages, [ "Item 1 in the array did not validate: Ensure this value has at most 2 " "characters (it has 3).", "Item 3 in the array did not validate: Ensure this value has at most 2 " "characters (it has 4).", ], ) def test_splitarraywidget_value_omitted_from_data(self): class Form(forms.ModelForm): field = SplitArrayField(forms.IntegerField(), required=False, size=2) class Meta: model = IntegerArrayModel fields = ("field",) form = Form({"field_0": "1", "field_1": "2"}) self.assertEqual(form.errors, {}) obj = form.save(commit=False) self.assertEqual(obj.field, [1, 2]) def test_splitarrayfield_has_changed(self): class Form(forms.ModelForm): field = SplitArrayField(forms.IntegerField(), required=False, size=2) class Meta: model = IntegerArrayModel fields = ("field",) tests = [ ({}, {"field_0": "", "field_1": ""}, True), ({"field": None}, {"field_0": "", "field_1": ""}, True), ({"field": [1]}, {"field_0": "", "field_1": ""}, True), ({"field": [1]}, {"field_0": "1", "field_1": "0"}, True), ({"field": [1, 2]}, {"field_0": "1", "field_1": "2"}, False), ({"field": [1, 2]}, {"field_0": "a", "field_1": "b"}, True), ] for initial, data, expected_result in tests: with self.subTest(initial=initial, data=data): obj = IntegerArrayModel(**initial) form = Form(data, instance=obj) self.assertIs(form.has_changed(), expected_result) def test_splitarrayfield_remove_trailing_nulls_has_changed(self): class Form(forms.ModelForm): field = SplitArrayField( forms.IntegerField(), required=False, size=2, remove_trailing_nulls=True ) class Meta: model = IntegerArrayModel fields = ("field",) tests = [ ({}, {"field_0": "", "field_1": ""}, False), ({"field": None}, {"field_0": "", "field_1": ""}, False), ({"field": []}, {"field_0": "", "field_1": ""}, False), ({"field": [1]}, {"field_0": "1", "field_1": ""}, False), ] for initial, data, expected_result in tests: with self.subTest(initial=initial, data=data): obj = IntegerArrayModel(**initial) form = Form(data, instance=obj) self.assertIs(form.has_changed(), expected_result) class TestSplitFormWidget(PostgreSQLWidgetTestCase): def test_get_context(self): self.assertEqual( SplitArrayWidget(forms.TextInput(), size=2).get_context( "name", ["val1", "val2"] ), { "widget": { "name": "name", "is_hidden": False, "required": False, "value": "['val1', 'val2']", "attrs": {}, "template_name": "postgres/widgets/split_array.html", "subwidgets": [ { "name": "name_0", "is_hidden": False, "required": False, "value": "val1", "attrs": {}, "template_name": "django/forms/widgets/text.html", "type": "text", }, { "name": "name_1", "is_hidden": False, "required": False, "value": "val2", "attrs": {}, "template_name": "django/forms/widgets/text.html", "type": "text", }, ], } }, ) def test_checkbox_get_context_attrs(self): context = SplitArrayWidget( forms.CheckboxInput(), size=2, ).get_context("name", [True, False]) self.assertEqual(context["widget"]["value"], "[True, False]") self.assertEqual( [subwidget["attrs"] for subwidget in context["widget"]["subwidgets"]], [{"checked": True}, {}], ) def test_render(self): self.check_html( SplitArrayWidget(forms.TextInput(), size=2), "array", None, """ <input name="array_0" type="text"> <input name="array_1" type="text"> """, ) def test_render_attrs(self): self.check_html( SplitArrayWidget(forms.TextInput(), size=2), "array", ["val1", "val2"], attrs={"id": "foo"}, html=( """ <input id="foo_0" name="array_0" type="text" value="val1"> <input id="foo_1" name="array_1" type="text" value="val2"> """ ), ) def test_value_omitted_from_data(self): widget = SplitArrayWidget(forms.TextInput(), size=2) self.assertIs(widget.value_omitted_from_data({}, {}, "field"), True) self.assertIs( widget.value_omitted_from_data({"field_0": "value"}, {}, "field"), False ) self.assertIs( widget.value_omitted_from_data({"field_1": "value"}, {}, "field"), False ) self.assertIs( widget.value_omitted_from_data( {"field_0": "value", "field_1": "value"}, {}, "field" ), False, )
a05422df4e697360360c6b760db8f5877410d32e89ceec6de9e2a1c670a6f2d4
from django.test import modify_settings from . import PostgreSQLTestCase from .models import CharFieldModel, TextFieldModel try: from django.contrib.postgres.search import ( TrigramDistance, TrigramSimilarity, TrigramWordDistance, TrigramWordSimilarity, ) except ImportError: pass @modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"}) class TrigramTest(PostgreSQLTestCase): Model = CharFieldModel @classmethod def setUpTestData(cls): cls.Model.objects.bulk_create( [ cls.Model(field="Matthew"), cls.Model(field="Cat sat on mat."), cls.Model(field="Dog sat on rug."), ] ) def test_trigram_search(self): self.assertQuerysetEqual( self.Model.objects.filter(field__trigram_similar="Mathew"), ["Matthew"], transform=lambda instance: instance.field, ) def test_trigram_word_search(self): obj = self.Model.objects.create( field="Gumby rides on the path of Middlesbrough", ) self.assertSequenceEqual( self.Model.objects.filter(field__trigram_word_similar="Middlesborough"), [obj], ) def test_trigram_similarity(self): search = "Bat sat on cat." # Round result of similarity because PostgreSQL uses greater precision. self.assertQuerysetEqual( self.Model.objects.filter( field__trigram_similar=search, ) .annotate(similarity=TrigramSimilarity("field", search)) .order_by("-similarity"), [("Cat sat on mat.", 0.625), ("Dog sat on rug.", 0.333333)], transform=lambda instance: (instance.field, round(instance.similarity, 6)), ordered=True, ) def test_trigram_word_similarity(self): search = "mat" self.assertSequenceEqual( self.Model.objects.filter( field__trigram_word_similar=search, ) .annotate( word_similarity=TrigramWordSimilarity(search, "field"), ) .values("field", "word_similarity") .order_by("-word_similarity"), [ {"field": "Cat sat on mat.", "word_similarity": 1.0}, {"field": "Matthew", "word_similarity": 0.75}, ], ) def test_trigram_similarity_alternate(self): # Round result of distance because PostgreSQL uses greater precision. self.assertQuerysetEqual( self.Model.objects.annotate( distance=TrigramDistance("field", "Bat sat on cat."), ) .filter(distance__lte=0.7) .order_by("distance"), [("Cat sat on mat.", 0.375), ("Dog sat on rug.", 0.666667)], transform=lambda instance: (instance.field, round(instance.distance, 6)), ordered=True, ) def test_trigram_word_similarity_alternate(self): self.assertSequenceEqual( self.Model.objects.annotate( word_distance=TrigramWordDistance("mat", "field"), ) .filter( word_distance__lte=0.7, ) .values("field", "word_distance") .order_by("word_distance"), [ {"field": "Cat sat on mat.", "word_distance": 0}, {"field": "Matthew", "word_distance": 0.25}, ], ) class TrigramTextFieldTest(TrigramTest): """ TextField has the same behavior as CharField regarding trigram lookups. """ Model = TextFieldModel
2d0d04f89b43f5fd7a337f599262b276f078f1c87f274a40eb93f99fb02fc2f3
import datetime import json from decimal import Decimal from django import forms from django.core import exceptions, serializers from django.db.models import DateField, DateTimeField, F, Func, Value from django.http import QueryDict from django.test import override_settings from django.test.utils import isolate_apps from django.utils import timezone from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase from .models import ( BigAutoFieldModel, PostgreSQLModel, RangeLookupsModel, RangesModel, SmallAutoFieldModel, ) try: from psycopg2.extras import DateRange, DateTimeTZRange, NumericRange from django.contrib.postgres import fields as pg_fields from django.contrib.postgres import forms as pg_forms from django.contrib.postgres.validators import ( RangeMaxValueValidator, RangeMinValueValidator, ) except ImportError: pass @isolate_apps("postgres_tests") class BasicTests(PostgreSQLSimpleTestCase): def test_get_field_display(self): class Model(PostgreSQLModel): field = pg_fields.IntegerRangeField( choices=[ ["1-50", [((1, 25), "1-25"), ([26, 50], "26-50")]], ((51, 100), "51-100"), ], ) tests = ( ((1, 25), "1-25"), ([26, 50], "26-50"), ((51, 100), "51-100"), ((1, 2), "(1, 2)"), ([1, 2], "[1, 2]"), ) for value, display in tests: with self.subTest(value=value, display=display): instance = Model(field=value) self.assertEqual(instance.get_field_display(), display) def test_discrete_range_fields_unsupported_default_bounds(self): discrete_range_types = [ pg_fields.BigIntegerRangeField, pg_fields.IntegerRangeField, pg_fields.DateRangeField, ] for field_type in discrete_range_types: msg = f"Cannot use 'default_bounds' with {field_type.__name__}." with self.assertRaisesMessage(TypeError, msg): field_type(choices=[((51, 100), "51-100")], default_bounds="[]") def test_continuous_range_fields_default_bounds(self): continuous_range_types = [ pg_fields.DecimalRangeField, pg_fields.DateTimeRangeField, ] for field_type in continuous_range_types: field = field_type(choices=[((51, 100), "51-100")], default_bounds="[]") self.assertEqual(field.default_bounds, "[]") def test_invalid_default_bounds(self): tests = [")]", ")[", "](", "])", "([", "[(", "x", "", None] msg = "default_bounds must be one of '[)', '(]', '()', or '[]'." for invalid_bounds in tests: with self.assertRaisesMessage(ValueError, msg): pg_fields.DecimalRangeField(default_bounds=invalid_bounds) def test_deconstruct(self): field = pg_fields.DecimalRangeField() *_, kwargs = field.deconstruct() self.assertEqual(kwargs, {}) field = pg_fields.DecimalRangeField(default_bounds="[]") *_, kwargs = field.deconstruct() self.assertEqual(kwargs, {"default_bounds": "[]"}) class TestSaveLoad(PostgreSQLTestCase): def test_all_fields(self): now = timezone.now() instance = RangesModel( ints=NumericRange(0, 10), bigints=NumericRange(10, 20), decimals=NumericRange(20, 30), timestamps=DateTimeTZRange(now - datetime.timedelta(hours=1), now), dates=DateRange(now.date() - datetime.timedelta(days=1), now.date()), ) instance.save() loaded = RangesModel.objects.get() self.assertEqual(instance.ints, loaded.ints) self.assertEqual(instance.bigints, loaded.bigints) self.assertEqual(instance.decimals, loaded.decimals) self.assertEqual(instance.timestamps, loaded.timestamps) self.assertEqual(instance.dates, loaded.dates) def test_range_object(self): r = NumericRange(0, 10) instance = RangesModel(ints=r) instance.save() loaded = RangesModel.objects.get() self.assertEqual(r, loaded.ints) def test_tuple(self): instance = RangesModel(ints=(0, 10)) instance.save() loaded = RangesModel.objects.get() self.assertEqual(NumericRange(0, 10), loaded.ints) def test_tuple_range_with_default_bounds(self): range_ = (timezone.now(), timezone.now() + datetime.timedelta(hours=1)) RangesModel.objects.create(timestamps_closed_bounds=range_, timestamps=range_) loaded = RangesModel.objects.get() self.assertEqual( loaded.timestamps_closed_bounds, DateTimeTZRange(range_[0], range_[1], "[]"), ) self.assertEqual( loaded.timestamps, DateTimeTZRange(range_[0], range_[1], "[)"), ) def test_range_object_boundaries(self): r = NumericRange(0, 10, "[]") instance = RangesModel(decimals=r) instance.save() loaded = RangesModel.objects.get() self.assertEqual(r, loaded.decimals) self.assertIn(10, loaded.decimals) def test_range_object_boundaries_range_with_default_bounds(self): range_ = DateTimeTZRange( timezone.now(), timezone.now() + datetime.timedelta(hours=1), bounds="()", ) RangesModel.objects.create(timestamps_closed_bounds=range_) loaded = RangesModel.objects.get() self.assertEqual(loaded.timestamps_closed_bounds, range_) def test_unbounded(self): r = NumericRange(None, None, "()") instance = RangesModel(decimals=r) instance.save() loaded = RangesModel.objects.get() self.assertEqual(r, loaded.decimals) def test_empty(self): r = NumericRange(empty=True) instance = RangesModel(ints=r) instance.save() loaded = RangesModel.objects.get() self.assertEqual(r, loaded.ints) def test_null(self): instance = RangesModel(ints=None) instance.save() loaded = RangesModel.objects.get() self.assertIsNone(loaded.ints) def test_model_set_on_base_field(self): instance = RangesModel() field = instance._meta.get_field("ints") self.assertEqual(field.model, RangesModel) self.assertEqual(field.base_field.model, RangesModel) class TestRangeContainsLookup(PostgreSQLTestCase): @classmethod def setUpTestData(cls): cls.timestamps = [ datetime.datetime(year=2016, month=1, day=1), datetime.datetime(year=2016, month=1, day=2, hour=1), datetime.datetime(year=2016, month=1, day=2, hour=12), datetime.datetime(year=2016, month=1, day=3), datetime.datetime(year=2016, month=1, day=3, hour=1), datetime.datetime(year=2016, month=2, day=2), ] cls.aware_timestamps = [ timezone.make_aware(timestamp) for timestamp in cls.timestamps ] cls.dates = [ datetime.date(year=2016, month=1, day=1), datetime.date(year=2016, month=1, day=2), datetime.date(year=2016, month=1, day=3), datetime.date(year=2016, month=1, day=4), datetime.date(year=2016, month=2, day=2), datetime.date(year=2016, month=2, day=3), ] cls.obj = RangesModel.objects.create( dates=(cls.dates[0], cls.dates[3]), dates_inner=(cls.dates[1], cls.dates[2]), timestamps=(cls.timestamps[0], cls.timestamps[3]), timestamps_inner=(cls.timestamps[1], cls.timestamps[2]), ) cls.aware_obj = RangesModel.objects.create( dates=(cls.dates[0], cls.dates[3]), dates_inner=(cls.dates[1], cls.dates[2]), timestamps=(cls.aware_timestamps[0], cls.aware_timestamps[3]), timestamps_inner=(cls.timestamps[1], cls.timestamps[2]), ) # Objects that don't match any queries. for i in range(3, 4): RangesModel.objects.create( dates=(cls.dates[i], cls.dates[i + 1]), timestamps=(cls.timestamps[i], cls.timestamps[i + 1]), ) RangesModel.objects.create( dates=(cls.dates[i], cls.dates[i + 1]), timestamps=(cls.aware_timestamps[i], cls.aware_timestamps[i + 1]), ) def test_datetime_range_contains(self): filter_args = ( self.timestamps[1], self.aware_timestamps[1], (self.timestamps[1], self.timestamps[2]), (self.aware_timestamps[1], self.aware_timestamps[2]), Value(self.dates[0]), Func(F("dates"), function="lower", output_field=DateTimeField()), F("timestamps_inner"), ) for filter_arg in filter_args: with self.subTest(filter_arg=filter_arg): self.assertCountEqual( RangesModel.objects.filter(**{"timestamps__contains": filter_arg}), [self.obj, self.aware_obj], ) def test_date_range_contains(self): filter_args = ( self.timestamps[1], (self.dates[1], self.dates[2]), Value(self.dates[0], output_field=DateField()), Func(F("timestamps"), function="lower", output_field=DateField()), F("dates_inner"), ) for filter_arg in filter_args: with self.subTest(filter_arg=filter_arg): self.assertCountEqual( RangesModel.objects.filter(**{"dates__contains": filter_arg}), [self.obj, self.aware_obj], ) class TestQuerying(PostgreSQLTestCase): @classmethod def setUpTestData(cls): cls.objs = RangesModel.objects.bulk_create( [ RangesModel(ints=NumericRange(0, 10)), RangesModel(ints=NumericRange(5, 15)), RangesModel(ints=NumericRange(None, 0)), RangesModel(ints=NumericRange(empty=True)), RangesModel(ints=None), ] ) def test_exact(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__exact=NumericRange(0, 10)), [self.objs[0]], ) def test_isnull(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__isnull=True), [self.objs[4]], ) def test_isempty(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__isempty=True), [self.objs[3]], ) def test_contains(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__contains=8), [self.objs[0], self.objs[1]], ) def test_contains_range(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__contains=NumericRange(3, 8)), [self.objs[0]], ) def test_contained_by(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__contained_by=NumericRange(0, 20)), [self.objs[0], self.objs[1], self.objs[3]], ) def test_overlap(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__overlap=NumericRange(3, 8)), [self.objs[0], self.objs[1]], ) def test_fully_lt(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__fully_lt=NumericRange(5, 10)), [self.objs[2]], ) def test_fully_gt(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__fully_gt=NumericRange(5, 10)), [], ) def test_not_lt(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__not_lt=NumericRange(5, 10)), [self.objs[1]], ) def test_not_gt(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__not_gt=NumericRange(5, 10)), [self.objs[0], self.objs[2]], ) def test_adjacent_to(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__adjacent_to=NumericRange(0, 5)), [self.objs[1], self.objs[2]], ) def test_startswith(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__startswith=0), [self.objs[0]], ) def test_endswith(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__endswith=0), [self.objs[2]], ) def test_startswith_chaining(self): self.assertSequenceEqual( RangesModel.objects.filter(ints__startswith__gte=0), [self.objs[0], self.objs[1]], ) def test_bound_type(self): decimals = RangesModel.objects.bulk_create( [ RangesModel(decimals=NumericRange(None, 10)), RangesModel(decimals=NumericRange(10, None)), RangesModel(decimals=NumericRange(5, 15)), RangesModel(decimals=NumericRange(5, 15, "(]")), ] ) tests = [ ("lower_inc", True, [decimals[1], decimals[2]]), ("lower_inc", False, [decimals[0], decimals[3]]), ("lower_inf", True, [decimals[0]]), ("lower_inf", False, [decimals[1], decimals[2], decimals[3]]), ("upper_inc", True, [decimals[3]]), ("upper_inc", False, [decimals[0], decimals[1], decimals[2]]), ("upper_inf", True, [decimals[1]]), ("upper_inf", False, [decimals[0], decimals[2], decimals[3]]), ] for lookup, filter_arg, excepted_result in tests: with self.subTest(lookup=lookup, filter_arg=filter_arg): self.assertSequenceEqual( RangesModel.objects.filter(**{"decimals__%s" % lookup: filter_arg}), excepted_result, ) class TestQueryingWithRanges(PostgreSQLTestCase): def test_date_range(self): objs = [ RangeLookupsModel.objects.create(date="2015-01-01"), RangeLookupsModel.objects.create(date="2015-05-05"), ] self.assertSequenceEqual( RangeLookupsModel.objects.filter( date__contained_by=DateRange("2015-01-01", "2015-05-04") ), [objs[0]], ) def test_date_range_datetime_field(self): objs = [ RangeLookupsModel.objects.create(timestamp="2015-01-01"), RangeLookupsModel.objects.create(timestamp="2015-05-05"), ] self.assertSequenceEqual( RangeLookupsModel.objects.filter( timestamp__date__contained_by=DateRange("2015-01-01", "2015-05-04") ), [objs[0]], ) def test_datetime_range(self): objs = [ RangeLookupsModel.objects.create(timestamp="2015-01-01T09:00:00"), RangeLookupsModel.objects.create(timestamp="2015-05-05T17:00:00"), ] self.assertSequenceEqual( RangeLookupsModel.objects.filter( timestamp__contained_by=DateTimeTZRange( "2015-01-01T09:00", "2015-05-04T23:55" ) ), [objs[0]], ) def test_small_integer_field_contained_by(self): objs = [ RangeLookupsModel.objects.create(small_integer=8), RangeLookupsModel.objects.create(small_integer=4), RangeLookupsModel.objects.create(small_integer=-1), ] self.assertSequenceEqual( RangeLookupsModel.objects.filter( small_integer__contained_by=NumericRange(4, 6) ), [objs[1]], ) def test_integer_range(self): objs = [ RangeLookupsModel.objects.create(integer=5), RangeLookupsModel.objects.create(integer=99), RangeLookupsModel.objects.create(integer=-1), ] self.assertSequenceEqual( RangeLookupsModel.objects.filter(integer__contained_by=NumericRange(1, 98)), [objs[0]], ) def test_biginteger_range(self): objs = [ RangeLookupsModel.objects.create(big_integer=5), RangeLookupsModel.objects.create(big_integer=99), RangeLookupsModel.objects.create(big_integer=-1), ] self.assertSequenceEqual( RangeLookupsModel.objects.filter( big_integer__contained_by=NumericRange(1, 98) ), [objs[0]], ) def test_decimal_field_contained_by(self): objs = [ RangeLookupsModel.objects.create(decimal_field=Decimal("1.33")), RangeLookupsModel.objects.create(decimal_field=Decimal("2.88")), RangeLookupsModel.objects.create(decimal_field=Decimal("99.17")), ] self.assertSequenceEqual( RangeLookupsModel.objects.filter( decimal_field__contained_by=NumericRange( Decimal("1.89"), Decimal("7.91") ), ), [objs[1]], ) def test_float_range(self): objs = [ RangeLookupsModel.objects.create(float=5), RangeLookupsModel.objects.create(float=99), RangeLookupsModel.objects.create(float=-1), ] self.assertSequenceEqual( RangeLookupsModel.objects.filter(float__contained_by=NumericRange(1, 98)), [objs[0]], ) def test_small_auto_field_contained_by(self): objs = SmallAutoFieldModel.objects.bulk_create( [SmallAutoFieldModel() for i in range(1, 5)] ) self.assertSequenceEqual( SmallAutoFieldModel.objects.filter( id__contained_by=NumericRange(objs[1].pk, objs[3].pk), ), objs[1:3], ) def test_auto_field_contained_by(self): objs = RangeLookupsModel.objects.bulk_create( [RangeLookupsModel() for i in range(1, 5)] ) self.assertSequenceEqual( RangeLookupsModel.objects.filter( id__contained_by=NumericRange(objs[1].pk, objs[3].pk), ), objs[1:3], ) def test_big_auto_field_contained_by(self): objs = BigAutoFieldModel.objects.bulk_create( [BigAutoFieldModel() for i in range(1, 5)] ) self.assertSequenceEqual( BigAutoFieldModel.objects.filter( id__contained_by=NumericRange(objs[1].pk, objs[3].pk), ), objs[1:3], ) def test_f_ranges(self): parent = RangesModel.objects.create(decimals=NumericRange(0, 10)) objs = [ RangeLookupsModel.objects.create(float=5, parent=parent), RangeLookupsModel.objects.create(float=99, parent=parent), ] self.assertSequenceEqual( RangeLookupsModel.objects.filter(float__contained_by=F("parent__decimals")), [objs[0]], ) def test_exclude(self): objs = [ RangeLookupsModel.objects.create(float=5), RangeLookupsModel.objects.create(float=99), RangeLookupsModel.objects.create(float=-1), ] self.assertSequenceEqual( RangeLookupsModel.objects.exclude(float__contained_by=NumericRange(0, 100)), [objs[2]], ) class TestSerialization(PostgreSQLSimpleTestCase): test_data = ( '[{"fields": {"ints": "{\\"upper\\": \\"10\\", \\"lower\\": \\"0\\", ' '\\"bounds\\": \\"[)\\"}", "decimals": "{\\"empty\\": true}", ' '"bigints": null, "timestamps": ' '"{\\"upper\\": \\"2014-02-02T12:12:12+00:00\\", ' '\\"lower\\": \\"2014-01-01T00:00:00+00:00\\", \\"bounds\\": \\"[)\\"}", ' '"timestamps_inner": null, ' '"timestamps_closed_bounds": "{\\"upper\\": \\"2014-02-02T12:12:12+00:00\\", ' '\\"lower\\": \\"2014-01-01T00:00:00+00:00\\", \\"bounds\\": \\"()\\"}", ' '"dates": "{\\"upper\\": \\"2014-02-02\\", \\"lower\\": \\"2014-01-01\\", ' '\\"bounds\\": \\"[)\\"}", "dates_inner": null }, ' '"model": "postgres_tests.rangesmodel", "pk": null}]' ) lower_date = datetime.date(2014, 1, 1) upper_date = datetime.date(2014, 2, 2) lower_dt = datetime.datetime(2014, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc) upper_dt = datetime.datetime(2014, 2, 2, 12, 12, 12, tzinfo=datetime.timezone.utc) def test_dumping(self): instance = RangesModel( ints=NumericRange(0, 10), decimals=NumericRange(empty=True), timestamps=DateTimeTZRange(self.lower_dt, self.upper_dt), timestamps_closed_bounds=DateTimeTZRange( self.lower_dt, self.upper_dt, bounds="()", ), dates=DateRange(self.lower_date, self.upper_date), ) data = serializers.serialize("json", [instance]) dumped = json.loads(data) for field in ("ints", "dates", "timestamps", "timestamps_closed_bounds"): dumped[0]["fields"][field] = json.loads(dumped[0]["fields"][field]) check = json.loads(self.test_data) for field in ("ints", "dates", "timestamps", "timestamps_closed_bounds"): check[0]["fields"][field] = json.loads(check[0]["fields"][field]) self.assertEqual(dumped, check) def test_loading(self): instance = list(serializers.deserialize("json", self.test_data))[0].object self.assertEqual(instance.ints, NumericRange(0, 10)) self.assertEqual(instance.decimals, NumericRange(empty=True)) self.assertIsNone(instance.bigints) self.assertEqual(instance.dates, DateRange(self.lower_date, self.upper_date)) self.assertEqual( instance.timestamps, DateTimeTZRange(self.lower_dt, self.upper_dt) ) self.assertEqual( instance.timestamps_closed_bounds, DateTimeTZRange(self.lower_dt, self.upper_dt, bounds="()"), ) def test_serialize_range_with_null(self): instance = RangesModel(ints=NumericRange(None, 10)) data = serializers.serialize("json", [instance]) new_instance = list(serializers.deserialize("json", data))[0].object self.assertEqual(new_instance.ints, NumericRange(None, 10)) instance = RangesModel(ints=NumericRange(10, None)) data = serializers.serialize("json", [instance]) new_instance = list(serializers.deserialize("json", data))[0].object self.assertEqual(new_instance.ints, NumericRange(10, None)) class TestChecks(PostgreSQLSimpleTestCase): def test_choices_tuple_list(self): class Model(PostgreSQLModel): field = pg_fields.IntegerRangeField( choices=[ ["1-50", [((1, 25), "1-25"), ([26, 50], "26-50")]], ((51, 100), "51-100"), ], ) self.assertEqual(Model._meta.get_field("field").check(), []) class TestValidators(PostgreSQLSimpleTestCase): def test_max(self): validator = RangeMaxValueValidator(5) validator(NumericRange(0, 5)) msg = "Ensure that this range is completely less than or equal to 5." with self.assertRaises(exceptions.ValidationError) as cm: validator(NumericRange(0, 10)) self.assertEqual(cm.exception.messages[0], msg) self.assertEqual(cm.exception.code, "max_value") with self.assertRaisesMessage(exceptions.ValidationError, msg): validator(NumericRange(0, None)) # an unbound range def test_min(self): validator = RangeMinValueValidator(5) validator(NumericRange(10, 15)) msg = "Ensure that this range is completely greater than or equal to 5." with self.assertRaises(exceptions.ValidationError) as cm: validator(NumericRange(0, 10)) self.assertEqual(cm.exception.messages[0], msg) self.assertEqual(cm.exception.code, "min_value") with self.assertRaisesMessage(exceptions.ValidationError, msg): validator(NumericRange(None, 10)) # an unbound range class TestFormField(PostgreSQLSimpleTestCase): def test_valid_integer(self): field = pg_forms.IntegerRangeField() value = field.clean(["1", "2"]) self.assertEqual(value, NumericRange(1, 2)) def test_valid_decimal(self): field = pg_forms.DecimalRangeField() value = field.clean(["1.12345", "2.001"]) self.assertEqual(value, NumericRange(Decimal("1.12345"), Decimal("2.001"))) def test_valid_timestamps(self): field = pg_forms.DateTimeRangeField() value = field.clean(["01/01/2014 00:00:00", "02/02/2014 12:12:12"]) lower = datetime.datetime(2014, 1, 1, 0, 0, 0) upper = datetime.datetime(2014, 2, 2, 12, 12, 12) self.assertEqual(value, DateTimeTZRange(lower, upper)) def test_valid_dates(self): field = pg_forms.DateRangeField() value = field.clean(["01/01/2014", "02/02/2014"]) lower = datetime.date(2014, 1, 1) upper = datetime.date(2014, 2, 2) self.assertEqual(value, DateRange(lower, upper)) def test_using_split_datetime_widget(self): class SplitDateTimeRangeField(pg_forms.DateTimeRangeField): base_field = forms.SplitDateTimeField class SplitForm(forms.Form): field = SplitDateTimeRangeField() form = SplitForm() self.assertHTMLEqual( str(form), """ <div> <fieldset> <legend>Field:</legend> <input id="id_field_0_0" name="field_0_0" type="text"> <input id="id_field_0_1" name="field_0_1" type="text"> <input id="id_field_1_0" name="field_1_0" type="text"> <input id="id_field_1_1" name="field_1_1" type="text"> </fieldset> </div> """, ) form = SplitForm( { "field_0_0": "01/01/2014", "field_0_1": "00:00:00", "field_1_0": "02/02/2014", "field_1_1": "12:12:12", } ) self.assertTrue(form.is_valid()) lower = datetime.datetime(2014, 1, 1, 0, 0, 0) upper = datetime.datetime(2014, 2, 2, 12, 12, 12) self.assertEqual(form.cleaned_data["field"], DateTimeTZRange(lower, upper)) def test_none(self): field = pg_forms.IntegerRangeField(required=False) value = field.clean(["", ""]) self.assertIsNone(value) def test_datetime_form_as_table(self): class DateTimeRangeForm(forms.Form): datetime_field = pg_forms.DateTimeRangeField(show_hidden_initial=True) form = DateTimeRangeForm() self.assertHTMLEqual( form.as_table(), """ <tr><th> <label>Datetime field:</label> </th><td> <input type="text" name="datetime_field_0" id="id_datetime_field_0"> <input type="text" name="datetime_field_1" id="id_datetime_field_1"> <input type="hidden" name="initial-datetime_field_0" id="initial-id_datetime_field_0"> <input type="hidden" name="initial-datetime_field_1" id="initial-id_datetime_field_1"> </td></tr> """, ) form = DateTimeRangeForm( { "datetime_field_0": "2010-01-01 11:13:00", "datetime_field_1": "2020-12-12 16:59:00", } ) self.assertHTMLEqual( form.as_table(), """ <tr><th> <label>Datetime field:</label> </th><td> <input type="text" name="datetime_field_0" value="2010-01-01 11:13:00" id="id_datetime_field_0"> <input type="text" name="datetime_field_1" value="2020-12-12 16:59:00" id="id_datetime_field_1"> <input type="hidden" name="initial-datetime_field_0" value="2010-01-01 11:13:00" id="initial-id_datetime_field_0"> <input type="hidden" name="initial-datetime_field_1" value="2020-12-12 16:59:00" id="initial-id_datetime_field_1"></td></tr> """, ) def test_datetime_form_initial_data(self): class DateTimeRangeForm(forms.Form): datetime_field = pg_forms.DateTimeRangeField(show_hidden_initial=True) data = QueryDict(mutable=True) data.update( { "datetime_field_0": "2010-01-01 11:13:00", "datetime_field_1": "", "initial-datetime_field_0": "2010-01-01 10:12:00", "initial-datetime_field_1": "", } ) form = DateTimeRangeForm(data=data) self.assertTrue(form.has_changed()) data["initial-datetime_field_0"] = "2010-01-01 11:13:00" form = DateTimeRangeForm(data=data) self.assertFalse(form.has_changed()) def test_rendering(self): class RangeForm(forms.Form): ints = pg_forms.IntegerRangeField() self.assertHTMLEqual( str(RangeForm()), """ <div> <fieldset> <legend>Ints:</legend> <input id="id_ints_0" name="ints_0" type="number"> <input id="id_ints_1" name="ints_1" type="number"> </fieldset> </div> """, ) def test_integer_lower_bound_higher(self): field = pg_forms.IntegerRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["10", "2"]) self.assertEqual( cm.exception.messages[0], "The start of the range must not exceed the end of the range.", ) self.assertEqual(cm.exception.code, "bound_ordering") def test_integer_open(self): field = pg_forms.IntegerRangeField() value = field.clean(["", "0"]) self.assertEqual(value, NumericRange(None, 0)) def test_integer_incorrect_data_type(self): field = pg_forms.IntegerRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean("1") self.assertEqual(cm.exception.messages[0], "Enter two whole numbers.") self.assertEqual(cm.exception.code, "invalid") def test_integer_invalid_lower(self): field = pg_forms.IntegerRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["a", "2"]) self.assertEqual(cm.exception.messages[0], "Enter a whole number.") def test_integer_invalid_upper(self): field = pg_forms.IntegerRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["1", "b"]) self.assertEqual(cm.exception.messages[0], "Enter a whole number.") def test_integer_required(self): field = pg_forms.IntegerRangeField(required=True) with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["", ""]) self.assertEqual(cm.exception.messages[0], "This field is required.") value = field.clean([1, ""]) self.assertEqual(value, NumericRange(1, None)) def test_decimal_lower_bound_higher(self): field = pg_forms.DecimalRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["1.8", "1.6"]) self.assertEqual( cm.exception.messages[0], "The start of the range must not exceed the end of the range.", ) self.assertEqual(cm.exception.code, "bound_ordering") def test_decimal_open(self): field = pg_forms.DecimalRangeField() value = field.clean(["", "3.1415926"]) self.assertEqual(value, NumericRange(None, Decimal("3.1415926"))) def test_decimal_incorrect_data_type(self): field = pg_forms.DecimalRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean("1.6") self.assertEqual(cm.exception.messages[0], "Enter two numbers.") self.assertEqual(cm.exception.code, "invalid") def test_decimal_invalid_lower(self): field = pg_forms.DecimalRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["a", "3.1415926"]) self.assertEqual(cm.exception.messages[0], "Enter a number.") def test_decimal_invalid_upper(self): field = pg_forms.DecimalRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["1.61803399", "b"]) self.assertEqual(cm.exception.messages[0], "Enter a number.") def test_decimal_required(self): field = pg_forms.DecimalRangeField(required=True) with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["", ""]) self.assertEqual(cm.exception.messages[0], "This field is required.") value = field.clean(["1.61803399", ""]) self.assertEqual(value, NumericRange(Decimal("1.61803399"), None)) def test_date_lower_bound_higher(self): field = pg_forms.DateRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["2013-04-09", "1976-04-16"]) self.assertEqual( cm.exception.messages[0], "The start of the range must not exceed the end of the range.", ) self.assertEqual(cm.exception.code, "bound_ordering") def test_date_open(self): field = pg_forms.DateRangeField() value = field.clean(["", "2013-04-09"]) self.assertEqual(value, DateRange(None, datetime.date(2013, 4, 9))) def test_date_incorrect_data_type(self): field = pg_forms.DateRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean("1") self.assertEqual(cm.exception.messages[0], "Enter two valid dates.") self.assertEqual(cm.exception.code, "invalid") def test_date_invalid_lower(self): field = pg_forms.DateRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["a", "2013-04-09"]) self.assertEqual(cm.exception.messages[0], "Enter a valid date.") def test_date_invalid_upper(self): field = pg_forms.DateRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["2013-04-09", "b"]) self.assertEqual(cm.exception.messages[0], "Enter a valid date.") def test_date_required(self): field = pg_forms.DateRangeField(required=True) with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["", ""]) self.assertEqual(cm.exception.messages[0], "This field is required.") value = field.clean(["1976-04-16", ""]) self.assertEqual(value, DateRange(datetime.date(1976, 4, 16), None)) def test_date_has_changed_first(self): self.assertTrue( pg_forms.DateRangeField().has_changed( ["2010-01-01", "2020-12-12"], ["2010-01-31", "2020-12-12"], ) ) def test_date_has_changed_last(self): self.assertTrue( pg_forms.DateRangeField().has_changed( ["2010-01-01", "2020-12-12"], ["2010-01-01", "2020-12-31"], ) ) def test_datetime_lower_bound_higher(self): field = pg_forms.DateTimeRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["2006-10-25 14:59", "2006-10-25 14:58"]) self.assertEqual( cm.exception.messages[0], "The start of the range must not exceed the end of the range.", ) self.assertEqual(cm.exception.code, "bound_ordering") def test_datetime_open(self): field = pg_forms.DateTimeRangeField() value = field.clean(["", "2013-04-09 11:45"]) self.assertEqual( value, DateTimeTZRange(None, datetime.datetime(2013, 4, 9, 11, 45)) ) def test_datetime_incorrect_data_type(self): field = pg_forms.DateTimeRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean("2013-04-09 11:45") self.assertEqual(cm.exception.messages[0], "Enter two valid date/times.") self.assertEqual(cm.exception.code, "invalid") def test_datetime_invalid_lower(self): field = pg_forms.DateTimeRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["45", "2013-04-09 11:45"]) self.assertEqual(cm.exception.messages[0], "Enter a valid date/time.") def test_datetime_invalid_upper(self): field = pg_forms.DateTimeRangeField() with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["2013-04-09 11:45", "sweet pickles"]) self.assertEqual(cm.exception.messages[0], "Enter a valid date/time.") def test_datetime_required(self): field = pg_forms.DateTimeRangeField(required=True) with self.assertRaises(exceptions.ValidationError) as cm: field.clean(["", ""]) self.assertEqual(cm.exception.messages[0], "This field is required.") value = field.clean(["2013-04-09 11:45", ""]) self.assertEqual( value, DateTimeTZRange(datetime.datetime(2013, 4, 9, 11, 45), None) ) @override_settings(USE_TZ=True, TIME_ZONE="Africa/Johannesburg") def test_datetime_prepare_value(self): field = pg_forms.DateTimeRangeField() value = field.prepare_value( DateTimeTZRange( datetime.datetime(2015, 5, 22, 16, 6, 33, tzinfo=datetime.timezone.utc), None, ) ) self.assertEqual(value, [datetime.datetime(2015, 5, 22, 18, 6, 33), None]) def test_datetime_has_changed_first(self): self.assertTrue( pg_forms.DateTimeRangeField().has_changed( ["2010-01-01 00:00", "2020-12-12 00:00"], ["2010-01-31 23:00", "2020-12-12 00:00"], ) ) def test_datetime_has_changed_last(self): self.assertTrue( pg_forms.DateTimeRangeField().has_changed( ["2010-01-01 00:00", "2020-12-12 00:00"], ["2010-01-01 00:00", "2020-12-31 23:00"], ) ) def test_model_field_formfield_integer(self): model_field = pg_fields.IntegerRangeField() form_field = model_field.formfield() self.assertIsInstance(form_field, pg_forms.IntegerRangeField) self.assertEqual(form_field.range_kwargs, {}) def test_model_field_formfield_biginteger(self): model_field = pg_fields.BigIntegerRangeField() form_field = model_field.formfield() self.assertIsInstance(form_field, pg_forms.IntegerRangeField) self.assertEqual(form_field.range_kwargs, {}) def test_model_field_formfield_float(self): model_field = pg_fields.DecimalRangeField(default_bounds="()") form_field = model_field.formfield() self.assertIsInstance(form_field, pg_forms.DecimalRangeField) self.assertEqual(form_field.range_kwargs, {"bounds": "()"}) def test_model_field_formfield_date(self): model_field = pg_fields.DateRangeField() form_field = model_field.formfield() self.assertIsInstance(form_field, pg_forms.DateRangeField) self.assertEqual(form_field.range_kwargs, {}) def test_model_field_formfield_datetime(self): model_field = pg_fields.DateTimeRangeField() form_field = model_field.formfield() self.assertIsInstance(form_field, pg_forms.DateTimeRangeField) self.assertEqual( form_field.range_kwargs, {"bounds": pg_fields.ranges.CANONICAL_RANGE_BOUNDS}, ) def test_model_field_formfield_datetime_default_bounds(self): model_field = pg_fields.DateTimeRangeField(default_bounds="[]") form_field = model_field.formfield() self.assertIsInstance(form_field, pg_forms.DateTimeRangeField) self.assertEqual(form_field.range_kwargs, {"bounds": "[]"}) def test_model_field_with_default_bounds(self): field = pg_forms.DateTimeRangeField(default_bounds="[]") value = field.clean(["2014-01-01 00:00:00", "2014-02-03 12:13:14"]) lower = datetime.datetime(2014, 1, 1, 0, 0, 0) upper = datetime.datetime(2014, 2, 3, 12, 13, 14) self.assertEqual(value, DateTimeTZRange(lower, upper, "[]")) def test_has_changed(self): for field, value in ( (pg_forms.DateRangeField(), ["2010-01-01", "2020-12-12"]), (pg_forms.DateTimeRangeField(), ["2010-01-01 11:13", "2020-12-12 14:52"]), (pg_forms.IntegerRangeField(), [1, 2]), (pg_forms.DecimalRangeField(), ["1.12345", "2.001"]), ): with self.subTest(field=field.__class__.__name__): self.assertTrue(field.has_changed(None, value)) self.assertTrue(field.has_changed([value[0], ""], value)) self.assertTrue(field.has_changed(["", value[1]], value)) self.assertFalse(field.has_changed(value, value)) class TestWidget(PostgreSQLSimpleTestCase): def test_range_widget(self): f = pg_forms.ranges.DateTimeRangeField() self.assertHTMLEqual( f.widget.render("datetimerange", ""), '<input type="text" name="datetimerange_0">' '<input type="text" name="datetimerange_1">', ) self.assertHTMLEqual( f.widget.render("datetimerange", None), '<input type="text" name="datetimerange_0">' '<input type="text" name="datetimerange_1">', ) dt_range = DateTimeTZRange( datetime.datetime(2006, 1, 10, 7, 30), datetime.datetime(2006, 2, 12, 9, 50) ) self.assertHTMLEqual( f.widget.render("datetimerange", dt_range), '<input type="text" name="datetimerange_0" value="2006-01-10 07:30:00">' '<input type="text" name="datetimerange_1" value="2006-02-12 09:50:00">', ) def test_range_widget_render_tuple_value(self): field = pg_forms.ranges.DateTimeRangeField() dt_range_tuple = ( datetime.datetime(2022, 4, 22, 10, 24), datetime.datetime(2022, 5, 12, 9, 25), ) self.assertHTMLEqual( field.widget.render("datetimerange", dt_range_tuple), '<input type="text" name="datetimerange_0" value="2022-04-22 10:24:00">' '<input type="text" name="datetimerange_1" value="2022-05-12 09:25:00">', )
69a6c3907983b6b5cb000807d01f587549c1767fb3382ce37e005e6eb458f900
import unittest from migrations.test_base import OperationTestBase from django.db import IntegrityError, NotSupportedError, connection, transaction from django.db.migrations.state import ProjectState from django.db.models import CheckConstraint, Index, Q, UniqueConstraint from django.db.utils import ProgrammingError from django.test import modify_settings, override_settings from django.test.utils import CaptureQueriesContext from . import PostgreSQLTestCase try: from django.contrib.postgres.indexes import BrinIndex, BTreeIndex from django.contrib.postgres.operations import ( AddConstraintNotValid, AddIndexConcurrently, BloomExtension, CreateCollation, CreateExtension, RemoveCollation, RemoveIndexConcurrently, ValidateConstraint, ) except ImportError: pass @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests.") @modify_settings(INSTALLED_APPS={"append": "migrations"}) class AddIndexConcurrentlyTests(OperationTestBase): app_label = "test_add_concurrently" def test_requires_atomic_false(self): project_state = self.set_up_test_model(self.app_label) new_state = project_state.clone() operation = AddIndexConcurrently( "Pony", Index(fields=["pink"], name="pony_pink_idx"), ) msg = ( "The AddIndexConcurrently operation cannot be executed inside " "a transaction (set atomic = False on the migration)." ) with self.assertRaisesMessage(NotSupportedError, msg): with connection.schema_editor(atomic=True) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) def test_add(self): project_state = self.set_up_test_model(self.app_label, index=False) table_name = "%s_pony" % self.app_label index = Index(fields=["pink"], name="pony_pink_idx") new_state = project_state.clone() operation = AddIndexConcurrently("Pony", index) self.assertEqual( operation.describe(), "Concurrently create index pony_pink_idx on field(s) pink of model Pony", ) operation.state_forwards(self.app_label, new_state) self.assertEqual( len(new_state.models[self.app_label, "pony"].options["indexes"]), 1 ) self.assertIndexNotExists(table_name, ["pink"]) # Add index. with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertIndexExists(table_name, ["pink"]) # Reversal. with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertIndexNotExists(table_name, ["pink"]) # Deconstruction. name, args, kwargs = operation.deconstruct() self.assertEqual(name, "AddIndexConcurrently") self.assertEqual(args, []) self.assertEqual(kwargs, {"model_name": "Pony", "index": index}) def test_add_other_index_type(self): project_state = self.set_up_test_model(self.app_label, index=False) table_name = "%s_pony" % self.app_label new_state = project_state.clone() operation = AddIndexConcurrently( "Pony", BrinIndex(fields=["pink"], name="pony_pink_brin_idx"), ) self.assertIndexNotExists(table_name, ["pink"]) # Add index. with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertIndexExists(table_name, ["pink"], index_type="brin") # Reversal. with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertIndexNotExists(table_name, ["pink"]) def test_add_with_options(self): project_state = self.set_up_test_model(self.app_label, index=False) table_name = "%s_pony" % self.app_label new_state = project_state.clone() index = BTreeIndex(fields=["pink"], name="pony_pink_btree_idx", fillfactor=70) operation = AddIndexConcurrently("Pony", index) self.assertIndexNotExists(table_name, ["pink"]) # Add index. with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertIndexExists(table_name, ["pink"], index_type="btree") # Reversal. with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertIndexNotExists(table_name, ["pink"]) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests.") @modify_settings(INSTALLED_APPS={"append": "migrations"}) class RemoveIndexConcurrentlyTests(OperationTestBase): app_label = "test_rm_concurrently" def test_requires_atomic_false(self): project_state = self.set_up_test_model(self.app_label, index=True) new_state = project_state.clone() operation = RemoveIndexConcurrently("Pony", "pony_pink_idx") msg = ( "The RemoveIndexConcurrently operation cannot be executed inside " "a transaction (set atomic = False on the migration)." ) with self.assertRaisesMessage(NotSupportedError, msg): with connection.schema_editor(atomic=True) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) def test_remove(self): project_state = self.set_up_test_model(self.app_label, index=True) table_name = "%s_pony" % self.app_label self.assertTableExists(table_name) new_state = project_state.clone() operation = RemoveIndexConcurrently("Pony", "pony_pink_idx") self.assertEqual( operation.describe(), "Concurrently remove index pony_pink_idx from Pony", ) operation.state_forwards(self.app_label, new_state) self.assertEqual( len(new_state.models[self.app_label, "pony"].options["indexes"]), 0 ) self.assertIndexExists(table_name, ["pink"]) # Remove index. with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertIndexNotExists(table_name, ["pink"]) # Reversal. with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertIndexExists(table_name, ["pink"]) # Deconstruction. name, args, kwargs = operation.deconstruct() self.assertEqual(name, "RemoveIndexConcurrently") self.assertEqual(args, []) self.assertEqual(kwargs, {"model_name": "Pony", "name": "pony_pink_idx"}) class NoMigrationRouter: def allow_migrate(self, db, app_label, **hints): return False @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests.") class CreateExtensionTests(PostgreSQLTestCase): app_label = "test_allow_create_extention" @override_settings(DATABASE_ROUTERS=[NoMigrationRouter()]) def test_no_allow_migrate(self): operation = CreateExtension("tablefunc") project_state = ProjectState() new_state = project_state.clone() # Don't create an extension. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertEqual(len(captured_queries), 0) # Reversal. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertEqual(len(captured_queries), 0) def test_allow_migrate(self): operation = CreateExtension("tablefunc") self.assertEqual( operation.migration_name_fragment, "create_extension_tablefunc" ) project_state = ProjectState() new_state = project_state.clone() # Create an extension. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertEqual(len(captured_queries), 4) self.assertIn("CREATE EXTENSION IF NOT EXISTS", captured_queries[1]["sql"]) # Reversal. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertEqual(len(captured_queries), 2) self.assertIn("DROP EXTENSION IF EXISTS", captured_queries[1]["sql"]) def test_create_existing_extension(self): operation = BloomExtension() self.assertEqual(operation.migration_name_fragment, "create_extension_bloom") project_state = ProjectState() new_state = project_state.clone() # Don't create an existing extension. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertEqual(len(captured_queries), 3) self.assertIn("SELECT", captured_queries[0]["sql"]) def test_drop_nonexistent_extension(self): operation = CreateExtension("tablefunc") project_state = ProjectState() new_state = project_state.clone() # Don't drop a nonexistent extension. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, project_state, new_state ) self.assertEqual(len(captured_queries), 1) self.assertIn("SELECT", captured_queries[0]["sql"]) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests.") class CreateCollationTests(PostgreSQLTestCase): app_label = "test_allow_create_collation" @override_settings(DATABASE_ROUTERS=[NoMigrationRouter()]) def test_no_allow_migrate(self): operation = CreateCollation("C_test", locale="C") project_state = ProjectState() new_state = project_state.clone() # Don't create a collation. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertEqual(len(captured_queries), 0) # Reversal. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertEqual(len(captured_queries), 0) def test_create(self): operation = CreateCollation("C_test", locale="C") self.assertEqual(operation.migration_name_fragment, "create_collation_c_test") self.assertEqual(operation.describe(), "Create collation C_test") project_state = ProjectState() new_state = project_state.clone() # Create a collation. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertEqual(len(captured_queries), 1) self.assertIn("CREATE COLLATION", captured_queries[0]["sql"]) # Creating the same collation raises an exception. with self.assertRaisesMessage(ProgrammingError, "already exists"): with connection.schema_editor(atomic=True) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) # Reversal. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertEqual(len(captured_queries), 1) self.assertIn("DROP COLLATION", captured_queries[0]["sql"]) # Deconstruction. name, args, kwargs = operation.deconstruct() self.assertEqual(name, "CreateCollation") self.assertEqual(args, []) self.assertEqual(kwargs, {"name": "C_test", "locale": "C"}) def test_create_non_deterministic_collation(self): operation = CreateCollation( "case_insensitive_test", "und-u-ks-level2", provider="icu", deterministic=False, ) project_state = ProjectState() new_state = project_state.clone() # Create a collation. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertEqual(len(captured_queries), 1) self.assertIn("CREATE COLLATION", captured_queries[0]["sql"]) # Reversal. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertEqual(len(captured_queries), 1) self.assertIn("DROP COLLATION", captured_queries[0]["sql"]) # Deconstruction. name, args, kwargs = operation.deconstruct() self.assertEqual(name, "CreateCollation") self.assertEqual(args, []) self.assertEqual( kwargs, { "name": "case_insensitive_test", "locale": "und-u-ks-level2", "provider": "icu", "deterministic": False, }, ) def test_create_collation_alternate_provider(self): operation = CreateCollation( "german_phonebook_test", provider="icu", locale="de-u-co-phonebk", ) project_state = ProjectState() new_state = project_state.clone() # Create an collation. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertEqual(len(captured_queries), 1) self.assertIn("CREATE COLLATION", captured_queries[0]["sql"]) # Reversal. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertEqual(len(captured_queries), 1) self.assertIn("DROP COLLATION", captured_queries[0]["sql"]) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests.") class RemoveCollationTests(PostgreSQLTestCase): app_label = "test_allow_remove_collation" @override_settings(DATABASE_ROUTERS=[NoMigrationRouter()]) def test_no_allow_migrate(self): operation = RemoveCollation("C_test", locale="C") project_state = ProjectState() new_state = project_state.clone() # Don't create a collation. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertEqual(len(captured_queries), 0) # Reversal. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertEqual(len(captured_queries), 0) def test_remove(self): operation = CreateCollation("C_test", locale="C") project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) operation = RemoveCollation("C_test", locale="C") self.assertEqual(operation.migration_name_fragment, "remove_collation_c_test") self.assertEqual(operation.describe(), "Remove collation C_test") project_state = ProjectState() new_state = project_state.clone() # Remove a collation. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) self.assertEqual(len(captured_queries), 1) self.assertIn("DROP COLLATION", captured_queries[0]["sql"]) # Removing a nonexistent collation raises an exception. with self.assertRaisesMessage(ProgrammingError, "does not exist"): with connection.schema_editor(atomic=True) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) # Reversal. with CaptureQueriesContext(connection) as captured_queries: with connection.schema_editor(atomic=False) as editor: operation.database_backwards( self.app_label, editor, new_state, project_state ) self.assertEqual(len(captured_queries), 1) self.assertIn("CREATE COLLATION", captured_queries[0]["sql"]) # Deconstruction. name, args, kwargs = operation.deconstruct() self.assertEqual(name, "RemoveCollation") self.assertEqual(args, []) self.assertEqual(kwargs, {"name": "C_test", "locale": "C"}) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests.") @modify_settings(INSTALLED_APPS={"append": "migrations"}) class AddConstraintNotValidTests(OperationTestBase): app_label = "test_add_constraint_not_valid" def test_non_check_constraint_not_supported(self): constraint = UniqueConstraint(fields=["pink"], name="pony_pink_uniq") msg = "AddConstraintNotValid.constraint must be a check constraint." with self.assertRaisesMessage(TypeError, msg): AddConstraintNotValid(model_name="pony", constraint=constraint) def test_add(self): table_name = f"{self.app_label}_pony" constraint_name = "pony_pink_gte_check" constraint = CheckConstraint(check=Q(pink__gte=4), name=constraint_name) operation = AddConstraintNotValid("Pony", constraint=constraint) project_state, new_state = self.make_test_state(self.app_label, operation) self.assertEqual( operation.describe(), f"Create not valid constraint {constraint_name} on model Pony", ) self.assertEqual( operation.migration_name_fragment, f"pony_{constraint_name}_not_valid", ) self.assertEqual( len(new_state.models[self.app_label, "pony"].options["constraints"]), 1, ) self.assertConstraintNotExists(table_name, constraint_name) Pony = new_state.apps.get_model(self.app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) Pony.objects.create(pink=2, weight=1.0) # Add constraint. with connection.schema_editor(atomic=True) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) msg = f'check constraint "{constraint_name}"' with self.assertRaisesMessage(IntegrityError, msg), transaction.atomic(): Pony.objects.create(pink=3, weight=1.0) self.assertConstraintExists(table_name, constraint_name) # Reversal. with connection.schema_editor(atomic=True) as editor: operation.database_backwards( self.app_label, editor, project_state, new_state ) self.assertConstraintNotExists(table_name, constraint_name) Pony.objects.create(pink=3, weight=1.0) # Deconstruction. name, args, kwargs = operation.deconstruct() self.assertEqual(name, "AddConstraintNotValid") self.assertEqual(args, []) self.assertEqual(kwargs, {"model_name": "Pony", "constraint": constraint}) @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific tests.") @modify_settings(INSTALLED_APPS={"append": "migrations"}) class ValidateConstraintTests(OperationTestBase): app_label = "test_validate_constraint" def test_validate(self): constraint_name = "pony_pink_gte_check" constraint = CheckConstraint(check=Q(pink__gte=4), name=constraint_name) operation = AddConstraintNotValid("Pony", constraint=constraint) project_state, new_state = self.make_test_state(self.app_label, operation) Pony = new_state.apps.get_model(self.app_label, "Pony") obj = Pony.objects.create(pink=2, weight=1.0) # Add constraint. with connection.schema_editor(atomic=True) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() operation = ValidateConstraint("Pony", name=constraint_name) operation.state_forwards(self.app_label, new_state) self.assertEqual( operation.describe(), f"Validate constraint {constraint_name} on model Pony", ) self.assertEqual( operation.migration_name_fragment, f"pony_validate_{constraint_name}", ) # Validate constraint. with connection.schema_editor(atomic=True) as editor: msg = f'check constraint "{constraint_name}"' with self.assertRaisesMessage(IntegrityError, msg): operation.database_forwards( self.app_label, editor, project_state, new_state ) obj.pink = 5 obj.save() with connection.schema_editor(atomic=True) as editor: operation.database_forwards( self.app_label, editor, project_state, new_state ) # Reversal is a noop. with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( self.app_label, editor, new_state, project_state ) # Deconstruction. name, args, kwargs = operation.deconstruct() self.assertEqual(name, "ValidateConstraint") self.assertEqual(args, []) self.assertEqual(kwargs, {"model_name": "Pony", "name": constraint_name})
bb7d1a2cb0840acaabe488cc5453b87d5517f51fffd8f423f8ca0f17c5da6e86
from unittest import mock from django.contrib.postgres.indexes import ( BloomIndex, BrinIndex, BTreeIndex, GinIndex, GistIndex, HashIndex, OpClass, PostgresIndex, SpGistIndex, ) from django.db import NotSupportedError, connection from django.db.models import CharField, F, Index, Q from django.db.models.functions import Cast, Collate, Length, Lower from django.test import skipUnlessDBFeature from django.test.utils import modify_settings, register_lookup from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase from .fields import SearchVector, SearchVectorField from .models import CharFieldModel, IntegerArrayModel, Scene, TextFieldModel class IndexTestMixin: def test_name_auto_generation(self): index = self.index_class(fields=["field"]) index.set_name_with_model(CharFieldModel) self.assertRegex( index.name, r"postgres_te_field_[0-9a-f]{6}_%s" % self.index_class.suffix ) def test_deconstruction_no_customization(self): index = self.index_class( fields=["title"], name="test_title_%s" % self.index_class.suffix ) path, args, kwargs = index.deconstruct() self.assertEqual( path, "django.contrib.postgres.indexes.%s" % self.index_class.__name__ ) self.assertEqual(args, ()) self.assertEqual( kwargs, {"fields": ["title"], "name": "test_title_%s" % self.index_class.suffix}, ) def test_deconstruction_with_expressions_no_customization(self): name = f"test_title_{self.index_class.suffix}" index = self.index_class(Lower("title"), name=name) path, args, kwargs = index.deconstruct() self.assertEqual( path, f"django.contrib.postgres.indexes.{self.index_class.__name__}", ) self.assertEqual(args, (Lower("title"),)) self.assertEqual(kwargs, {"name": name}) class BloomIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = BloomIndex def test_suffix(self): self.assertEqual(BloomIndex.suffix, "bloom") def test_deconstruction(self): index = BloomIndex(fields=["title"], name="test_bloom", length=80, columns=[4]) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.BloomIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "test_bloom", "length": 80, "columns": [4], }, ) def test_invalid_fields(self): msg = "Bloom indexes support a maximum of 32 fields." with self.assertRaisesMessage(ValueError, msg): BloomIndex(fields=["title"] * 33, name="test_bloom") def test_invalid_columns(self): msg = "BloomIndex.columns must be a list or tuple." with self.assertRaisesMessage(ValueError, msg): BloomIndex(fields=["title"], name="test_bloom", columns="x") msg = "BloomIndex.columns cannot have more values than fields." with self.assertRaisesMessage(ValueError, msg): BloomIndex(fields=["title"], name="test_bloom", columns=[4, 3]) def test_invalid_columns_value(self): msg = "BloomIndex.columns must contain integers from 1 to 4095." for length in (0, 4096): with self.subTest(length), self.assertRaisesMessage(ValueError, msg): BloomIndex(fields=["title"], name="test_bloom", columns=[length]) def test_invalid_length(self): msg = "BloomIndex.length must be None or an integer from 1 to 4096." for length in (0, 4097): with self.subTest(length), self.assertRaisesMessage(ValueError, msg): BloomIndex(fields=["title"], name="test_bloom", length=length) class BrinIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = BrinIndex def test_suffix(self): self.assertEqual(BrinIndex.suffix, "brin") def test_deconstruction(self): index = BrinIndex( fields=["title"], name="test_title_brin", autosummarize=True, pages_per_range=16, ) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.BrinIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "test_title_brin", "autosummarize": True, "pages_per_range": 16, }, ) def test_invalid_pages_per_range(self): with self.assertRaisesMessage( ValueError, "pages_per_range must be None or a positive integer" ): BrinIndex(fields=["title"], name="test_title_brin", pages_per_range=0) class BTreeIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = BTreeIndex def test_suffix(self): self.assertEqual(BTreeIndex.suffix, "btree") def test_deconstruction(self): index = BTreeIndex(fields=["title"], name="test_title_btree", fillfactor=80) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.BTreeIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, {"fields": ["title"], "name": "test_title_btree", "fillfactor": 80} ) class GinIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = GinIndex def test_suffix(self): self.assertEqual(GinIndex.suffix, "gin") def test_deconstruction(self): index = GinIndex( fields=["title"], name="test_title_gin", fastupdate=True, gin_pending_list_limit=128, ) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.GinIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "test_title_gin", "fastupdate": True, "gin_pending_list_limit": 128, }, ) class GistIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = GistIndex def test_suffix(self): self.assertEqual(GistIndex.suffix, "gist") def test_deconstruction(self): index = GistIndex( fields=["title"], name="test_title_gist", buffering=False, fillfactor=80 ) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.GistIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, { "fields": ["title"], "name": "test_title_gist", "buffering": False, "fillfactor": 80, }, ) class HashIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = HashIndex def test_suffix(self): self.assertEqual(HashIndex.suffix, "hash") def test_deconstruction(self): index = HashIndex(fields=["title"], name="test_title_hash", fillfactor=80) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.HashIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, {"fields": ["title"], "name": "test_title_hash", "fillfactor": 80} ) class SpGistIndexTests(IndexTestMixin, PostgreSQLSimpleTestCase): index_class = SpGistIndex def test_suffix(self): self.assertEqual(SpGistIndex.suffix, "spgist") def test_deconstruction(self): index = SpGistIndex(fields=["title"], name="test_title_spgist", fillfactor=80) path, args, kwargs = index.deconstruct() self.assertEqual(path, "django.contrib.postgres.indexes.SpGistIndex") self.assertEqual(args, ()) self.assertEqual( kwargs, {"fields": ["title"], "name": "test_title_spgist", "fillfactor": 80} ) @modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"}) class SchemaTests(PostgreSQLTestCase): get_opclass_query = """ SELECT opcname, c.relname FROM pg_opclass AS oc JOIN pg_index as i on oc.oid = ANY(i.indclass) JOIN pg_class as c on c.oid = i.indexrelid WHERE c.relname = %s """ def get_constraints(self, table): """ Get the indexes on the table using a new cursor. """ with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def test_gin_index(self): # Ensure the table is there and doesn't have an index. self.assertNotIn( "field", self.get_constraints(IntegerArrayModel._meta.db_table) ) # Add the index index_name = "integer_array_model_field_gin" index = GinIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(IntegerArrayModel, index) constraints = self.get_constraints(IntegerArrayModel._meta.db_table) # Check gin index was added self.assertEqual(constraints[index_name]["type"], GinIndex.suffix) # Drop the index with connection.schema_editor() as editor: editor.remove_index(IntegerArrayModel, index) self.assertNotIn( index_name, self.get_constraints(IntegerArrayModel._meta.db_table) ) def test_gin_fastupdate(self): index_name = "integer_array_gin_fastupdate" index = GinIndex(fields=["field"], name=index_name, fastupdate=False) with connection.schema_editor() as editor: editor.add_index(IntegerArrayModel, index) constraints = self.get_constraints(IntegerArrayModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], "gin") self.assertEqual(constraints[index_name]["options"], ["fastupdate=off"]) with connection.schema_editor() as editor: editor.remove_index(IntegerArrayModel, index) self.assertNotIn( index_name, self.get_constraints(IntegerArrayModel._meta.db_table) ) def test_partial_gin_index(self): with register_lookup(CharField, Length): index_name = "char_field_gin_partial_idx" index = GinIndex( fields=["field"], name=index_name, condition=Q(field__length=40) ) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], "gin") with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_partial_gin_index_with_tablespace(self): with register_lookup(CharField, Length): index_name = "char_field_gin_partial_idx" index = GinIndex( fields=["field"], name=index_name, condition=Q(field__length=40), db_tablespace="pg_default", ) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) self.assertIn( 'TABLESPACE "pg_default" ', str(index.create_sql(CharFieldModel, editor)), ) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], "gin") with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_gin_parameters(self): index_name = "integer_array_gin_params" index = GinIndex( fields=["field"], name=index_name, fastupdate=True, gin_pending_list_limit=64, db_tablespace="pg_default", ) with connection.schema_editor() as editor: editor.add_index(IntegerArrayModel, index) self.assertIn( ") WITH (gin_pending_list_limit = 64, fastupdate = on) TABLESPACE", str(index.create_sql(IntegerArrayModel, editor)), ) constraints = self.get_constraints(IntegerArrayModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], "gin") self.assertEqual( constraints[index_name]["options"], ["gin_pending_list_limit=64", "fastupdate=on"], ) with connection.schema_editor() as editor: editor.remove_index(IntegerArrayModel, index) self.assertNotIn( index_name, self.get_constraints(IntegerArrayModel._meta.db_table) ) def test_trigram_op_class_gin_index(self): index_name = "trigram_op_class_gin" index = GinIndex(OpClass(F("scene"), name="gin_trgm_ops"), name=index_name) with connection.schema_editor() as editor: editor.add_index(Scene, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [index_name]) self.assertCountEqual(cursor.fetchall(), [("gin_trgm_ops", index_name)]) constraints = self.get_constraints(Scene._meta.db_table) self.assertIn(index_name, constraints) self.assertIn(constraints[index_name]["type"], GinIndex.suffix) with connection.schema_editor() as editor: editor.remove_index(Scene, index) self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table)) def test_cast_search_vector_gin_index(self): index_name = "cast_search_vector_gin" index = GinIndex(Cast("field", SearchVectorField()), name=index_name) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) sql = index.create_sql(TextFieldModel, editor) table = TextFieldModel._meta.db_table constraints = self.get_constraints(table) self.assertIn(index_name, constraints) self.assertIn(constraints[index_name]["type"], GinIndex.suffix) self.assertIs(sql.references_column(table, "field"), True) self.assertIn("::tsvector", str(sql)) with connection.schema_editor() as editor: editor.remove_index(TextFieldModel, index) self.assertNotIn(index_name, self.get_constraints(table)) def test_bloom_index(self): index_name = "char_field_model_field_bloom" index = BloomIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], BloomIndex.suffix) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_bloom_parameters(self): index_name = "char_field_model_field_bloom_params" index = BloomIndex(fields=["field"], name=index_name, length=512, columns=[3]) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], BloomIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["length=512", "col1=3"]) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_brin_index(self): index_name = "char_field_model_field_brin" index = BrinIndex(fields=["field"], name=index_name, pages_per_range=4) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], BrinIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["pages_per_range=4"]) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_brin_parameters(self): index_name = "char_field_brin_params" index = BrinIndex(fields=["field"], name=index_name, autosummarize=True) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], BrinIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["autosummarize=on"]) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_btree_index(self): # Ensure the table is there and doesn't have an index. self.assertNotIn("field", self.get_constraints(CharFieldModel._meta.db_table)) # Add the index. index_name = "char_field_model_field_btree" index = BTreeIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) # The index was added. self.assertEqual(constraints[index_name]["type"], BTreeIndex.suffix) # Drop the index. with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_btree_parameters(self): index_name = "integer_array_btree_fillfactor" index = BTreeIndex(fields=["field"], name=index_name, fillfactor=80) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], BTreeIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["fillfactor=80"]) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_gist_index(self): # Ensure the table is there and doesn't have an index. self.assertNotIn("field", self.get_constraints(CharFieldModel._meta.db_table)) # Add the index. index_name = "char_field_model_field_gist" index = GistIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) # The index was added. self.assertEqual(constraints[index_name]["type"], GistIndex.suffix) # Drop the index. with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_gist_parameters(self): index_name = "integer_array_gist_buffering" index = GistIndex( fields=["field"], name=index_name, buffering=True, fillfactor=80 ) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], GistIndex.suffix) self.assertEqual( constraints[index_name]["options"], ["buffering=on", "fillfactor=80"] ) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_gist_include(self): index_name = "scene_gist_include_setting" index = GistIndex(name=index_name, fields=["scene"], include=["setting"]) with connection.schema_editor() as editor: editor.add_index(Scene, index) constraints = self.get_constraints(Scene._meta.db_table) self.assertIn(index_name, constraints) self.assertEqual(constraints[index_name]["type"], GistIndex.suffix) self.assertEqual(constraints[index_name]["columns"], ["scene", "setting"]) with connection.schema_editor() as editor: editor.remove_index(Scene, index) self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table)) def test_tsvector_op_class_gist_index(self): index_name = "tsvector_op_class_gist" index = GistIndex( OpClass( SearchVector("scene", "setting", config="english"), name="tsvector_ops", ), name=index_name, ) with connection.schema_editor() as editor: editor.add_index(Scene, index) sql = index.create_sql(Scene, editor) table = Scene._meta.db_table constraints = self.get_constraints(table) self.assertIn(index_name, constraints) self.assertIn(constraints[index_name]["type"], GistIndex.suffix) self.assertIs(sql.references_column(table, "scene"), True) self.assertIs(sql.references_column(table, "setting"), True) with connection.schema_editor() as editor: editor.remove_index(Scene, index) self.assertNotIn(index_name, self.get_constraints(table)) def test_hash_index(self): # Ensure the table is there and doesn't have an index. self.assertNotIn("field", self.get_constraints(CharFieldModel._meta.db_table)) # Add the index. index_name = "char_field_model_field_hash" index = HashIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) # The index was added. self.assertEqual(constraints[index_name]["type"], HashIndex.suffix) # Drop the index. with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_hash_parameters(self): index_name = "integer_array_hash_fillfactor" index = HashIndex(fields=["field"], name=index_name, fillfactor=80) with connection.schema_editor() as editor: editor.add_index(CharFieldModel, index) constraints = self.get_constraints(CharFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], HashIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["fillfactor=80"]) with connection.schema_editor() as editor: editor.remove_index(CharFieldModel, index) self.assertNotIn( index_name, self.get_constraints(CharFieldModel._meta.db_table) ) def test_spgist_index(self): # Ensure the table is there and doesn't have an index. self.assertNotIn("field", self.get_constraints(TextFieldModel._meta.db_table)) # Add the index. index_name = "text_field_model_field_spgist" index = SpGistIndex(fields=["field"], name=index_name) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) constraints = self.get_constraints(TextFieldModel._meta.db_table) # The index was added. self.assertEqual(constraints[index_name]["type"], SpGistIndex.suffix) # Drop the index. with connection.schema_editor() as editor: editor.remove_index(TextFieldModel, index) self.assertNotIn( index_name, self.get_constraints(TextFieldModel._meta.db_table) ) def test_spgist_parameters(self): index_name = "text_field_model_spgist_fillfactor" index = SpGistIndex(fields=["field"], name=index_name, fillfactor=80) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) constraints = self.get_constraints(TextFieldModel._meta.db_table) self.assertEqual(constraints[index_name]["type"], SpGistIndex.suffix) self.assertEqual(constraints[index_name]["options"], ["fillfactor=80"]) with connection.schema_editor() as editor: editor.remove_index(TextFieldModel, index) self.assertNotIn( index_name, self.get_constraints(TextFieldModel._meta.db_table) ) @skipUnlessDBFeature("supports_covering_spgist_indexes") def test_spgist_include(self): index_name = "scene_spgist_include_setting" index = SpGistIndex(name=index_name, fields=["scene"], include=["setting"]) with connection.schema_editor() as editor: editor.add_index(Scene, index) constraints = self.get_constraints(Scene._meta.db_table) self.assertIn(index_name, constraints) self.assertEqual(constraints[index_name]["type"], SpGistIndex.suffix) self.assertEqual(constraints[index_name]["columns"], ["scene", "setting"]) with connection.schema_editor() as editor: editor.remove_index(Scene, index) self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table)) def test_spgist_include_not_supported(self): index_name = "spgist_include_exception" index = SpGistIndex(fields=["scene"], name=index_name, include=["setting"]) msg = "Covering SP-GiST indexes require PostgreSQL 14+." with self.assertRaisesMessage(NotSupportedError, msg): with mock.patch( "django.db.backends.postgresql.features.DatabaseFeatures." "supports_covering_spgist_indexes", False, ): with connection.schema_editor() as editor: editor.add_index(Scene, index) self.assertNotIn(index_name, self.get_constraints(Scene._meta.db_table)) def test_custom_suffix(self): class CustomSuffixIndex(PostgresIndex): suffix = "sfx" def create_sql(self, model, schema_editor, using="gin", **kwargs): return super().create_sql(model, schema_editor, using=using, **kwargs) index = CustomSuffixIndex(fields=["field"], name="custom_suffix_idx") self.assertEqual(index.suffix, "sfx") with connection.schema_editor() as editor: self.assertIn( " USING gin ", str(index.create_sql(CharFieldModel, editor)), ) def test_op_class(self): index_name = "test_op_class" index = Index( OpClass(Lower("field"), name="text_pattern_ops"), name=index_name, ) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [index_name]) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)]) def test_op_class_descending_collation(self): collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("This backend does not support case-insensitive collations.") index_name = "test_op_class_descending_collation" index = Index( Collate( OpClass(Lower("field"), name="text_pattern_ops").desc(nulls_last=True), collation=collation, ), name=index_name, ) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) self.assertIn( "COLLATE %s" % editor.quote_name(collation), str(index.create_sql(TextFieldModel, editor)), ) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [index_name]) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)]) table = TextFieldModel._meta.db_table constraints = self.get_constraints(table) self.assertIn(index_name, constraints) self.assertEqual(constraints[index_name]["orders"], ["DESC"]) with connection.schema_editor() as editor: editor.remove_index(TextFieldModel, index) self.assertNotIn(index_name, self.get_constraints(table)) def test_op_class_descending_partial(self): index_name = "test_op_class_descending_partial" index = Index( OpClass(Lower("field"), name="text_pattern_ops").desc(), name=index_name, condition=Q(field__contains="China"), ) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [index_name]) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)]) constraints = self.get_constraints(TextFieldModel._meta.db_table) self.assertIn(index_name, constraints) self.assertEqual(constraints[index_name]["orders"], ["DESC"]) def test_op_class_descending_partial_tablespace(self): index_name = "test_op_class_descending_partial_tablespace" index = Index( OpClass(Lower("field").desc(), name="text_pattern_ops"), name=index_name, condition=Q(field__contains="China"), db_tablespace="pg_default", ) with connection.schema_editor() as editor: editor.add_index(TextFieldModel, index) self.assertIn( 'TABLESPACE "pg_default" ', str(index.create_sql(TextFieldModel, editor)), ) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [index_name]) self.assertCountEqual(cursor.fetchall(), [("text_pattern_ops", index_name)]) constraints = self.get_constraints(TextFieldModel._meta.db_table) self.assertIn(index_name, constraints) self.assertEqual(constraints[index_name]["orders"], ["DESC"])
2f1b76f05420999637de634d62364d05eb4d51f99eba81d15f3fd0cc62da2df5
import datetime from unittest import mock from django.contrib.postgres.indexes import OpClass from django.core.exceptions import ValidationError from django.db import IntegrityError, NotSupportedError, connection, transaction from django.db.models import ( CheckConstraint, Deferrable, F, Func, IntegerField, Q, UniqueConstraint, ) from django.db.models.fields.json import KeyTextTransform from django.db.models.functions import Cast, Left, Lower from django.test import ignore_warnings, modify_settings, skipUnlessDBFeature from django.utils import timezone from django.utils.deprecation import RemovedInDjango50Warning from . import PostgreSQLTestCase from .models import HotelReservation, IntegerArrayModel, RangesModel, Room, Scene try: from psycopg2.extras import DateRange, NumericRange from django.contrib.postgres.constraints import ExclusionConstraint from django.contrib.postgres.fields import ( DateTimeRangeField, RangeBoundary, RangeOperators, ) except ImportError: pass @modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"}) class SchemaTests(PostgreSQLTestCase): get_opclass_query = """ SELECT opcname, c.relname FROM pg_opclass AS oc JOIN pg_index as i on oc.oid = ANY(i.indclass) JOIN pg_class as c on c.oid = i.indexrelid WHERE c.relname = %s """ def get_constraints(self, table): """Get the constraints on the table using a new cursor.""" with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def test_check_constraint_range_value(self): constraint_name = "ints_between" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = CheckConstraint( check=Q(ints__contained_by=NumericRange(10, 30)), name=constraint_name, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(20, 50)) RangesModel.objects.create(ints=(10, 30)) def test_check_constraint_daterange_contains(self): constraint_name = "dates_contains" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = CheckConstraint( check=Q(dates__contains=F("dates_inner")), name=constraint_name, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) date_1 = datetime.date(2016, 1, 1) date_2 = datetime.date(2016, 1, 4) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create( dates=(date_1, date_2), dates_inner=(date_1, date_2.replace(day=5)), ) RangesModel.objects.create( dates=(date_1, date_2), dates_inner=(date_1, date_2), ) def test_check_constraint_datetimerange_contains(self): constraint_name = "timestamps_contains" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = CheckConstraint( check=Q(timestamps__contains=F("timestamps_inner")), name=constraint_name, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) datetime_1 = datetime.datetime(2016, 1, 1) datetime_2 = datetime.datetime(2016, 1, 2, 12) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create( timestamps=(datetime_1, datetime_2), timestamps_inner=(datetime_1, datetime_2.replace(hour=13)), ) RangesModel.objects.create( timestamps=(datetime_1, datetime_2), timestamps_inner=(datetime_1, datetime_2), ) def test_opclass(self): constraint = UniqueConstraint( name="test_opclass", fields=["scene"], opclasses=["varchar_pattern_ops"], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) self.assertIn(constraint.name, self.get_constraints(Scene._meta.db_table)) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) self.assertEqual( cursor.fetchall(), [("varchar_pattern_ops", constraint.name)], ) # Drop the constraint. with connection.schema_editor() as editor: editor.remove_constraint(Scene, constraint) self.assertNotIn(constraint.name, self.get_constraints(Scene._meta.db_table)) def test_opclass_multiple_columns(self): constraint = UniqueConstraint( name="test_opclass_multiple", fields=["scene", "setting"], opclasses=["varchar_pattern_ops", "text_pattern_ops"], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) expected_opclasses = ( ("varchar_pattern_ops", constraint.name), ("text_pattern_ops", constraint.name), ) self.assertCountEqual(cursor.fetchall(), expected_opclasses) def test_opclass_partial(self): constraint = UniqueConstraint( name="test_opclass_partial", fields=["scene"], opclasses=["varchar_pattern_ops"], condition=Q(setting__contains="Sir Bedemir's Castle"), ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) self.assertCountEqual( cursor.fetchall(), [("varchar_pattern_ops", constraint.name)], ) @skipUnlessDBFeature("supports_covering_indexes") def test_opclass_include(self): constraint = UniqueConstraint( name="test_opclass_include", fields=["scene"], opclasses=["varchar_pattern_ops"], include=["setting"], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) self.assertCountEqual( cursor.fetchall(), [("varchar_pattern_ops", constraint.name)], ) @skipUnlessDBFeature("supports_expression_indexes") def test_opclass_func(self): constraint = UniqueConstraint( OpClass(Lower("scene"), name="text_pattern_ops"), name="test_opclass_func", ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) constraints = self.get_constraints(Scene._meta.db_table) self.assertIs(constraints[constraint.name]["unique"], True) self.assertIn(constraint.name, constraints) with editor.connection.cursor() as cursor: cursor.execute(self.get_opclass_query, [constraint.name]) self.assertEqual( cursor.fetchall(), [("text_pattern_ops", constraint.name)], ) Scene.objects.create(scene="Scene 10", setting="The dark forest of Ewing") with self.assertRaises(IntegrityError), transaction.atomic(): Scene.objects.create(scene="ScEnE 10", setting="Sir Bedemir's Castle") Scene.objects.create(scene="Scene 5", setting="Sir Bedemir's Castle") # Drop the constraint. with connection.schema_editor() as editor: editor.remove_constraint(Scene, constraint) self.assertNotIn(constraint.name, self.get_constraints(Scene._meta.db_table)) Scene.objects.create(scene="ScEnE 10", setting="Sir Bedemir's Castle") @modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"}) class ExclusionConstraintTests(PostgreSQLTestCase): def get_constraints(self, table): """Get the constraints on the table using a new cursor.""" with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def test_invalid_condition(self): msg = "ExclusionConstraint.condition must be a Q instance." with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( index_type="GIST", name="exclude_invalid_condition", expressions=[(F("datespan"), RangeOperators.OVERLAPS)], condition=F("invalid"), ) def test_invalid_index_type(self): msg = "Exclusion constraints only support GiST or SP-GiST indexes." with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( index_type="gin", name="exclude_invalid_index_type", expressions=[(F("datespan"), RangeOperators.OVERLAPS)], ) def test_invalid_expressions(self): msg = "The expressions must be a list of 2-tuples." for expressions in (["foo"], [("foo")], [("foo_1", "foo_2", "foo_3")]): with self.subTest(expressions), self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( index_type="GIST", name="exclude_invalid_expressions", expressions=expressions, ) def test_empty_expressions(self): msg = "At least one expression is required to define an exclusion constraint." for empty_expressions in (None, []): with self.subTest(empty_expressions), self.assertRaisesMessage( ValueError, msg ): ExclusionConstraint( index_type="GIST", name="exclude_empty_expressions", expressions=empty_expressions, ) def test_invalid_deferrable(self): msg = "ExclusionConstraint.deferrable must be a Deferrable instance." with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name="exclude_invalid_deferrable", expressions=[(F("datespan"), RangeOperators.OVERLAPS)], deferrable="invalid", ) def test_deferrable_with_condition(self): msg = "ExclusionConstraint with conditions cannot be deferred." with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name="exclude_invalid_condition", expressions=[(F("datespan"), RangeOperators.OVERLAPS)], condition=Q(cancelled=False), deferrable=Deferrable.DEFERRED, ) def test_invalid_include_type(self): msg = "ExclusionConstraint.include must be a list or tuple." with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name="exclude_invalid_include", expressions=[(F("datespan"), RangeOperators.OVERLAPS)], include="invalid", ) @ignore_warnings(category=RemovedInDjango50Warning) def test_invalid_opclasses_type(self): msg = "ExclusionConstraint.opclasses must be a list or tuple." with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name="exclude_invalid_opclasses", expressions=[(F("datespan"), RangeOperators.OVERLAPS)], opclasses="invalid", ) @ignore_warnings(category=RemovedInDjango50Warning) def test_opclasses_and_expressions_same_length(self): msg = ( "ExclusionConstraint.expressions and " "ExclusionConstraint.opclasses must have the same number of " "elements." ) with self.assertRaisesMessage(ValueError, msg): ExclusionConstraint( name="exclude_invalid_expressions_opclasses_length", expressions=[(F("datespan"), RangeOperators.OVERLAPS)], opclasses=["foo", "bar"], ) def test_repr(self): constraint = ExclusionConstraint( name="exclude_overlapping", expressions=[ (F("datespan"), RangeOperators.OVERLAPS), (F("room"), RangeOperators.EQUAL), ], ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type='GIST' expressions=[" "(F(datespan), '&&'), (F(room), '=')] name='exclude_overlapping'>", ) constraint = ExclusionConstraint( name="exclude_overlapping", expressions=[(F("datespan"), RangeOperators.ADJACENT_TO)], condition=Q(cancelled=False), index_type="SPGiST", ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type='SPGiST' expressions=[" "(F(datespan), '-|-')] name='exclude_overlapping' " "condition=(AND: ('cancelled', False))>", ) constraint = ExclusionConstraint( name="exclude_overlapping", expressions=[(F("datespan"), RangeOperators.ADJACENT_TO)], deferrable=Deferrable.IMMEDIATE, ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type='GIST' expressions=[" "(F(datespan), '-|-')] name='exclude_overlapping' " "deferrable=Deferrable.IMMEDIATE>", ) constraint = ExclusionConstraint( name="exclude_overlapping", expressions=[(F("datespan"), RangeOperators.ADJACENT_TO)], include=["cancelled", "room"], ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type='GIST' expressions=[" "(F(datespan), '-|-')] name='exclude_overlapping' " "include=('cancelled', 'room')>", ) constraint = ExclusionConstraint( name="exclude_overlapping", expressions=[ (OpClass("datespan", name="range_ops"), RangeOperators.ADJACENT_TO), ], ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type='GIST' expressions=[" "(OpClass(F(datespan), name=range_ops), '-|-')] " "name='exclude_overlapping'>", ) def test_eq(self): constraint_1 = ExclusionConstraint( name="exclude_overlapping", expressions=[ (F("datespan"), RangeOperators.OVERLAPS), (F("room"), RangeOperators.EQUAL), ], condition=Q(cancelled=False), ) constraint_2 = ExclusionConstraint( name="exclude_overlapping", expressions=[ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], ) constraint_3 = ExclusionConstraint( name="exclude_overlapping", expressions=[("datespan", RangeOperators.OVERLAPS)], condition=Q(cancelled=False), ) constraint_4 = ExclusionConstraint( name="exclude_overlapping", expressions=[ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], deferrable=Deferrable.DEFERRED, ) constraint_5 = ExclusionConstraint( name="exclude_overlapping", expressions=[ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], deferrable=Deferrable.IMMEDIATE, ) constraint_6 = ExclusionConstraint( name="exclude_overlapping", expressions=[ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], deferrable=Deferrable.IMMEDIATE, include=["cancelled"], ) constraint_7 = ExclusionConstraint( name="exclude_overlapping", expressions=[ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], include=["cancelled"], ) with ignore_warnings(category=RemovedInDjango50Warning): constraint_8 = ExclusionConstraint( name="exclude_overlapping", expressions=[ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], include=["cancelled"], opclasses=["range_ops", "range_ops"], ) constraint_9 = ExclusionConstraint( name="exclude_overlapping", expressions=[ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], opclasses=["range_ops", "range_ops"], ) self.assertNotEqual(constraint_2, constraint_9) self.assertNotEqual(constraint_7, constraint_8) self.assertEqual(constraint_1, constraint_1) self.assertEqual(constraint_1, mock.ANY) self.assertNotEqual(constraint_1, constraint_2) self.assertNotEqual(constraint_1, constraint_3) self.assertNotEqual(constraint_1, constraint_4) self.assertNotEqual(constraint_2, constraint_3) self.assertNotEqual(constraint_2, constraint_4) self.assertNotEqual(constraint_2, constraint_7) self.assertNotEqual(constraint_4, constraint_5) self.assertNotEqual(constraint_5, constraint_6) self.assertNotEqual(constraint_1, object()) def test_deconstruct(self): constraint = ExclusionConstraint( name="exclude_overlapping", expressions=[ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], ) path, args, kwargs = constraint.deconstruct() self.assertEqual( path, "django.contrib.postgres.constraints.ExclusionConstraint" ) self.assertEqual(args, ()) self.assertEqual( kwargs, { "name": "exclude_overlapping", "expressions": [ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], }, ) def test_deconstruct_index_type(self): constraint = ExclusionConstraint( name="exclude_overlapping", index_type="SPGIST", expressions=[ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], ) path, args, kwargs = constraint.deconstruct() self.assertEqual( path, "django.contrib.postgres.constraints.ExclusionConstraint" ) self.assertEqual(args, ()) self.assertEqual( kwargs, { "name": "exclude_overlapping", "index_type": "SPGIST", "expressions": [ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], }, ) def test_deconstruct_condition(self): constraint = ExclusionConstraint( name="exclude_overlapping", expressions=[ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], condition=Q(cancelled=False), ) path, args, kwargs = constraint.deconstruct() self.assertEqual( path, "django.contrib.postgres.constraints.ExclusionConstraint" ) self.assertEqual(args, ()) self.assertEqual( kwargs, { "name": "exclude_overlapping", "expressions": [ ("datespan", RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], "condition": Q(cancelled=False), }, ) def test_deconstruct_deferrable(self): constraint = ExclusionConstraint( name="exclude_overlapping", expressions=[("datespan", RangeOperators.OVERLAPS)], deferrable=Deferrable.DEFERRED, ) path, args, kwargs = constraint.deconstruct() self.assertEqual( path, "django.contrib.postgres.constraints.ExclusionConstraint" ) self.assertEqual(args, ()) self.assertEqual( kwargs, { "name": "exclude_overlapping", "expressions": [("datespan", RangeOperators.OVERLAPS)], "deferrable": Deferrable.DEFERRED, }, ) def test_deconstruct_include(self): constraint = ExclusionConstraint( name="exclude_overlapping", expressions=[("datespan", RangeOperators.OVERLAPS)], include=["cancelled", "room"], ) path, args, kwargs = constraint.deconstruct() self.assertEqual( path, "django.contrib.postgres.constraints.ExclusionConstraint" ) self.assertEqual(args, ()) self.assertEqual( kwargs, { "name": "exclude_overlapping", "expressions": [("datespan", RangeOperators.OVERLAPS)], "include": ("cancelled", "room"), }, ) @ignore_warnings(category=RemovedInDjango50Warning) def test_deconstruct_opclasses(self): constraint = ExclusionConstraint( name="exclude_overlapping", expressions=[("datespan", RangeOperators.OVERLAPS)], opclasses=["range_ops"], ) path, args, kwargs = constraint.deconstruct() self.assertEqual( path, "django.contrib.postgres.constraints.ExclusionConstraint" ) self.assertEqual(args, ()) self.assertEqual( kwargs, { "name": "exclude_overlapping", "expressions": [("datespan", RangeOperators.OVERLAPS)], "opclasses": ["range_ops"], }, ) def _test_range_overlaps(self, constraint): # Create exclusion constraint. self.assertNotIn( constraint.name, self.get_constraints(HotelReservation._meta.db_table) ) with connection.schema_editor() as editor: editor.add_constraint(HotelReservation, constraint) self.assertIn( constraint.name, self.get_constraints(HotelReservation._meta.db_table) ) # Add initial reservations. room101 = Room.objects.create(number=101) room102 = Room.objects.create(number=102) datetimes = [ timezone.datetime(2018, 6, 20), timezone.datetime(2018, 6, 24), timezone.datetime(2018, 6, 26), timezone.datetime(2018, 6, 28), timezone.datetime(2018, 6, 29), ] reservation = HotelReservation.objects.create( datespan=DateRange(datetimes[0].date(), datetimes[1].date()), start=datetimes[0], end=datetimes[1], room=room102, ) constraint.validate(HotelReservation, reservation) HotelReservation.objects.create( datespan=DateRange(datetimes[1].date(), datetimes[3].date()), start=datetimes[1], end=datetimes[3], room=room102, ) HotelReservation.objects.create( datespan=DateRange(datetimes[3].date(), datetimes[4].date()), start=datetimes[3], end=datetimes[4], room=room102, cancelled=True, ) # Overlap dates. with self.assertRaises(IntegrityError), transaction.atomic(): reservation = HotelReservation( datespan=(datetimes[1].date(), datetimes[2].date()), start=datetimes[1], end=datetimes[2], room=room102, ) msg = f"Constraint “{constraint.name}” is violated." with self.assertRaisesMessage(ValidationError, msg): constraint.validate(HotelReservation, reservation) reservation.save() # Valid range. other_valid_reservations = [ # Other room. HotelReservation( datespan=(datetimes[1].date(), datetimes[2].date()), start=datetimes[1], end=datetimes[2], room=room101, ), # Cancelled reservation. HotelReservation( datespan=(datetimes[1].date(), datetimes[1].date()), start=datetimes[1], end=datetimes[2], room=room102, cancelled=True, ), # Other adjacent dates. HotelReservation( datespan=(datetimes[3].date(), datetimes[4].date()), start=datetimes[3], end=datetimes[4], room=room102, ), ] for reservation in other_valid_reservations: constraint.validate(HotelReservation, reservation) HotelReservation.objects.bulk_create(other_valid_reservations) # Excluded fields. constraint.validate( HotelReservation, HotelReservation( datespan=(datetimes[1].date(), datetimes[2].date()), start=datetimes[1], end=datetimes[2], room=room102, ), exclude={"room"}, ) constraint.validate( HotelReservation, HotelReservation( datespan=(datetimes[1].date(), datetimes[2].date()), start=datetimes[1], end=datetimes[2], room=room102, ), exclude={"datespan", "start", "end", "room"}, ) @ignore_warnings(category=RemovedInDjango50Warning) def test_range_overlaps_custom_opclasses(self): class TsTzRange(Func): function = "TSTZRANGE" output_field = DateTimeRangeField() constraint = ExclusionConstraint( name="exclude_overlapping_reservations_custom", expressions=[ (TsTzRange("start", "end", RangeBoundary()), RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], condition=Q(cancelled=False), opclasses=["range_ops", "gist_int4_ops"], ) self._test_range_overlaps(constraint) def test_range_overlaps_custom(self): class TsTzRange(Func): function = "TSTZRANGE" output_field = DateTimeRangeField() constraint = ExclusionConstraint( name="exclude_overlapping_reservations_custom_opclass", expressions=[ ( OpClass(TsTzRange("start", "end", RangeBoundary()), "range_ops"), RangeOperators.OVERLAPS, ), (OpClass("room", "gist_int4_ops"), RangeOperators.EQUAL), ], condition=Q(cancelled=False), ) self._test_range_overlaps(constraint) def test_range_overlaps(self): constraint = ExclusionConstraint( name="exclude_overlapping_reservations", expressions=[ (F("datespan"), RangeOperators.OVERLAPS), ("room", RangeOperators.EQUAL), ], condition=Q(cancelled=False), ) self._test_range_overlaps(constraint) def test_range_adjacent(self): constraint_name = "ints_adjacent" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(10, 20)) RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) # Drop the constraint. with connection.schema_editor() as editor: editor.remove_constraint(RangesModel, constraint) self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) def test_validate_range_adjacent(self): constraint = ExclusionConstraint( name="ints_adjacent", expressions=[("ints", RangeOperators.ADJACENT_TO)], violation_error_message="Custom error message.", ) range_obj = RangesModel.objects.create(ints=(20, 50)) constraint.validate(RangesModel, range_obj) msg = "Custom error message." with self.assertRaisesMessage(ValidationError, msg): constraint.validate(RangesModel, RangesModel(ints=(10, 20))) constraint.validate(RangesModel, RangesModel(ints=(10, 19))) constraint.validate(RangesModel, RangesModel(ints=(51, 60))) constraint.validate(RangesModel, RangesModel(ints=(10, 20)), exclude={"ints"}) def test_expressions_with_params(self): constraint_name = "scene_left_equal" self.assertNotIn(constraint_name, self.get_constraints(Scene._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[(Left("scene", 4), RangeOperators.EQUAL)], ) with connection.schema_editor() as editor: editor.add_constraint(Scene, constraint) self.assertIn(constraint_name, self.get_constraints(Scene._meta.db_table)) def test_expressions_with_key_transform(self): constraint_name = "exclude_overlapping_reservations_smoking" constraint = ExclusionConstraint( name=constraint_name, expressions=[ (F("datespan"), RangeOperators.OVERLAPS), (KeyTextTransform("smoking", "requirements"), RangeOperators.EQUAL), ], ) with connection.schema_editor() as editor: editor.add_constraint(HotelReservation, constraint) self.assertIn( constraint_name, self.get_constraints(HotelReservation._meta.db_table), ) def test_index_transform(self): constraint_name = "first_index_equal" constraint = ExclusionConstraint( name=constraint_name, expressions=[("field__0", RangeOperators.EQUAL)], ) with connection.schema_editor() as editor: editor.add_constraint(IntegerArrayModel, constraint) self.assertIn( constraint_name, self.get_constraints(IntegerArrayModel._meta.db_table), ) def test_range_adjacent_initially_deferred(self): constraint_name = "ints_adjacent_deferred" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], deferrable=Deferrable.DEFERRED, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) adjacent_range = RangesModel.objects.create(ints=(10, 20)) # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name(constraint_name) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) # Remove adjacent range before the end of transaction. adjacent_range.delete() RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) def test_range_adjacent_gist_include(self): constraint_name = "ints_adjacent_gist_include" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], index_type="gist", include=["decimals", "ints"], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(10, 20)) RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) @skipUnlessDBFeature("supports_covering_spgist_indexes") def test_range_adjacent_spgist_include(self): constraint_name = "ints_adjacent_spgist_include" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], index_type="spgist", include=["decimals", "ints"], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) RangesModel.objects.create(ints=(20, 50)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(10, 20)) RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) def test_range_adjacent_gist_include_condition(self): constraint_name = "ints_adjacent_gist_include_condition" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], index_type="gist", include=["decimals"], condition=Q(id__gte=100), ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) @skipUnlessDBFeature("supports_covering_spgist_indexes") def test_range_adjacent_spgist_include_condition(self): constraint_name = "ints_adjacent_spgist_include_condition" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], index_type="spgist", include=["decimals"], condition=Q(id__gte=100), ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_range_adjacent_gist_include_deferrable(self): constraint_name = "ints_adjacent_gist_include_deferrable" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], index_type="gist", include=["decimals"], deferrable=Deferrable.DEFERRED, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) @skipUnlessDBFeature("supports_covering_spgist_indexes") def test_range_adjacent_spgist_include_deferrable(self): constraint_name = "ints_adjacent_spgist_include_deferrable" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], index_type="spgist", include=["decimals"], deferrable=Deferrable.DEFERRED, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_spgist_include_not_supported(self): constraint_name = "ints_adjacent_spgist_include_not_supported" constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], index_type="spgist", include=["id"], ) msg = ( "Covering exclusion constraints using an SP-GiST index require " "PostgreSQL 14+." ) with connection.schema_editor() as editor: with mock.patch( "django.db.backends.postgresql.features.DatabaseFeatures." "supports_covering_spgist_indexes", False, ): with self.assertRaisesMessage(NotSupportedError, msg): editor.add_constraint(RangesModel, constraint) def test_range_adjacent_opclass(self): constraint_name = "ints_adjacent_opclass" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[ (OpClass("ints", name="range_ops"), RangeOperators.ADJACENT_TO), ], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) constraints = self.get_constraints(RangesModel._meta.db_table) self.assertIn(constraint_name, constraints) with editor.connection.cursor() as cursor: cursor.execute(SchemaTests.get_opclass_query, [constraint_name]) self.assertEqual( cursor.fetchall(), [("range_ops", constraint_name)], ) RangesModel.objects.create(ints=(20, 50)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(10, 20)) RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) # Drop the constraint. with connection.schema_editor() as editor: editor.remove_constraint(RangesModel, constraint) self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) def test_range_adjacent_opclass_condition(self): constraint_name = "ints_adjacent_opclass_condition" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[ (OpClass("ints", name="range_ops"), RangeOperators.ADJACENT_TO), ], condition=Q(id__gte=100), ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_range_adjacent_opclass_deferrable(self): constraint_name = "ints_adjacent_opclass_deferrable" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[ (OpClass("ints", name="range_ops"), RangeOperators.ADJACENT_TO), ], deferrable=Deferrable.DEFERRED, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_range_adjacent_gist_opclass_include(self): constraint_name = "ints_adjacent_gist_opclass_include" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[ (OpClass("ints", name="range_ops"), RangeOperators.ADJACENT_TO), ], index_type="gist", include=["decimals"], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) @skipUnlessDBFeature("supports_covering_spgist_indexes") def test_range_adjacent_spgist_opclass_include(self): constraint_name = "ints_adjacent_spgist_opclass_include" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[ (OpClass("ints", name="range_ops"), RangeOperators.ADJACENT_TO), ], index_type="spgist", include=["decimals"], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) def test_range_equal_cast(self): constraint_name = "exclusion_equal_room_cast" self.assertNotIn(constraint_name, self.get_constraints(Room._meta.db_table)) constraint = ExclusionConstraint( name=constraint_name, expressions=[(Cast("number", IntegerField()), RangeOperators.EQUAL)], ) with connection.schema_editor() as editor: editor.add_constraint(Room, constraint) self.assertIn(constraint_name, self.get_constraints(Room._meta.db_table)) @modify_settings(INSTALLED_APPS={"append": "django.contrib.postgres"}) class ExclusionConstraintOpclassesDepracationTests(PostgreSQLTestCase): def get_constraints(self, table): """Get the constraints on the table using a new cursor.""" with connection.cursor() as cursor: return connection.introspection.get_constraints(cursor, table) def test_warning(self): msg = ( "The opclasses argument is deprecated in favor of using " "django.contrib.postgres.indexes.OpClass in " "ExclusionConstraint.expressions." ) with self.assertWarnsMessage(RemovedInDjango50Warning, msg): ExclusionConstraint( name="exclude_overlapping", expressions=[(F("datespan"), RangeOperators.ADJACENT_TO)], opclasses=["range_ops"], ) @ignore_warnings(category=RemovedInDjango50Warning) def test_repr(self): constraint = ExclusionConstraint( name="exclude_overlapping", expressions=[(F("datespan"), RangeOperators.ADJACENT_TO)], opclasses=["range_ops"], ) self.assertEqual( repr(constraint), "<ExclusionConstraint: index_type='GIST' expressions=[" "(F(datespan), '-|-')] name='exclude_overlapping' " "opclasses=['range_ops']>", ) @ignore_warnings(category=RemovedInDjango50Warning) def test_range_adjacent_opclasses(self): constraint_name = "ints_adjacent_opclasses" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], opclasses=["range_ops"], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) constraints = self.get_constraints(RangesModel._meta.db_table) self.assertIn(constraint_name, constraints) with editor.connection.cursor() as cursor: cursor.execute(SchemaTests.get_opclass_query, [constraint.name]) self.assertEqual( cursor.fetchall(), [("range_ops", constraint.name)], ) RangesModel.objects.create(ints=(20, 50)) with self.assertRaises(IntegrityError), transaction.atomic(): RangesModel.objects.create(ints=(10, 20)) RangesModel.objects.create(ints=(10, 19)) RangesModel.objects.create(ints=(51, 60)) # Drop the constraint. with connection.schema_editor() as editor: editor.remove_constraint(RangesModel, constraint) self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) @ignore_warnings(category=RemovedInDjango50Warning) def test_range_adjacent_opclasses_condition(self): constraint_name = "ints_adjacent_opclasses_condition" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], opclasses=["range_ops"], condition=Q(id__gte=100), ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) @ignore_warnings(category=RemovedInDjango50Warning) def test_range_adjacent_opclasses_deferrable(self): constraint_name = "ints_adjacent_opclasses_deferrable" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], opclasses=["range_ops"], deferrable=Deferrable.DEFERRED, ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) @ignore_warnings(category=RemovedInDjango50Warning) def test_range_adjacent_gist_opclasses_include(self): constraint_name = "ints_adjacent_gist_opclasses_include" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], index_type="gist", opclasses=["range_ops"], include=["decimals"], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table)) @ignore_warnings(category=RemovedInDjango50Warning) @skipUnlessDBFeature("supports_covering_spgist_indexes") def test_range_adjacent_spgist_opclasses_include(self): constraint_name = "ints_adjacent_spgist_opclasses_include" self.assertNotIn( constraint_name, self.get_constraints(RangesModel._meta.db_table) ) constraint = ExclusionConstraint( name=constraint_name, expressions=[("ints", RangeOperators.ADJACENT_TO)], index_type="spgist", opclasses=["range_ops"], include=["decimals"], ) with connection.schema_editor() as editor: editor.add_constraint(RangesModel, constraint) self.assertIn(constraint_name, self.get_constraints(RangesModel._meta.db_table))
18b5909772228aa2949c19f8b6863759c1952b7b6a2107da648796e3ed3f68c6
import datetime from xml.dom import minidom from django.contrib.sites.models import Site from django.contrib.syndication import views from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, override_settings from django.test.utils import requires_tz_support from django.utils import timezone from django.utils.feedgenerator import ( Atom1Feed, Rss201rev2Feed, rfc2822_date, rfc3339_date, ) from .models import Article, Entry TZ = timezone.get_default_timezone() class FeedTestCase(TestCase): @classmethod def setUpTestData(cls): cls.e1 = Entry.objects.create( title="My first entry", updated=datetime.datetime(1980, 1, 1, 12, 30), published=datetime.datetime(1986, 9, 25, 20, 15, 00), ) cls.e2 = Entry.objects.create( title="My second entry", updated=datetime.datetime(2008, 1, 2, 12, 30), published=datetime.datetime(2006, 3, 17, 18, 0), ) cls.e3 = Entry.objects.create( title="My third entry", updated=datetime.datetime(2008, 1, 2, 13, 30), published=datetime.datetime(2005, 6, 14, 10, 45), ) cls.e4 = Entry.objects.create( title="A & B < C > D", updated=datetime.datetime(2008, 1, 3, 13, 30), published=datetime.datetime(2005, 11, 25, 12, 11, 23), ) cls.e5 = Entry.objects.create( title="My last entry", updated=datetime.datetime(2013, 1, 20, 0, 0), published=datetime.datetime(2013, 3, 25, 20, 0), ) cls.a1 = Article.objects.create( title="My first article", entry=cls.e1, updated=datetime.datetime(1986, 11, 21, 9, 12, 18), published=datetime.datetime(1986, 10, 21, 9, 12, 18), ) def assertChildNodes(self, elem, expected): actual = {n.nodeName for n in elem.childNodes} expected = set(expected) self.assertEqual(actual, expected) def assertChildNodeContent(self, elem, expected): for k, v in expected.items(): self.assertEqual(elem.getElementsByTagName(k)[0].firstChild.wholeText, v) def assertCategories(self, elem, expected): self.assertEqual( { i.firstChild.wholeText for i in elem.childNodes if i.nodeName == "category" }, set(expected), ) @override_settings(ROOT_URLCONF="syndication_tests.urls") class SyndicationFeedTest(FeedTestCase): """ Tests for the high-level syndication feed framework. """ @classmethod def setUpClass(cls): super().setUpClass() # This cleanup is necessary because contrib.sites cache # makes tests interfere with each other, see #11505 Site.objects.clear_cache() def test_rss2_feed(self): """ Test the structure and content of feeds generated by Rss201rev2Feed. """ response = self.client.get("/syndication/rss2/") doc = minidom.parseString(response.content) # Making sure there's only 1 `rss` element and that the correct # RSS version was specified. feed_elem = doc.getElementsByTagName("rss") self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute("version"), "2.0") self.assertEqual( feed.getElementsByTagName("language")[0].firstChild.nodeValue, "en" ) # Making sure there's only one `channel` element w/in the # `rss` element. chan_elem = feed.getElementsByTagName("channel") self.assertEqual(len(chan_elem), 1) chan = chan_elem[0] # Find the last build date d = Entry.objects.latest("published").published last_build_date = rfc2822_date(timezone.make_aware(d, TZ)) self.assertChildNodes( chan, [ "title", "link", "description", "language", "lastBuildDate", "item", "atom:link", "ttl", "copyright", "category", ], ) self.assertChildNodeContent( chan, { "title": "My blog", "description": "A more thorough description of my blog.", "link": "http://example.com/blog/", "language": "en", "lastBuildDate": last_build_date, "ttl": "600", "copyright": "Copyright (c) 2007, Sally Smith", }, ) self.assertCategories(chan, ["python", "django"]) # Ensure the content of the channel is correct self.assertChildNodeContent( chan, { "title": "My blog", "link": "http://example.com/blog/", }, ) # Check feed_url is passed self.assertEqual( chan.getElementsByTagName("atom:link")[0].getAttribute("href"), "http://example.com/syndication/rss2/", ) # Find the pubdate of the first feed item d = Entry.objects.get(pk=self.e1.pk).published pub_date = rfc2822_date(timezone.make_aware(d, TZ)) items = chan.getElementsByTagName("item") self.assertEqual(len(items), Entry.objects.count()) self.assertChildNodeContent( items[0], { "title": "My first entry", "description": "Overridden description: My first entry", "link": "http://example.com/blog/%s/" % self.e1.pk, "guid": "http://example.com/blog/%s/" % self.e1.pk, "pubDate": pub_date, "author": "[email protected] (Sally Smith)", "comments": "/blog/%s/comments" % self.e1.pk, }, ) self.assertCategories(items[0], ["python", "testing"]) for item in items: self.assertChildNodes( item, [ "title", "link", "description", "guid", "category", "pubDate", "author", "comments", ], ) # Assert that <guid> does not have any 'isPermaLink' attribute self.assertIsNone( item.getElementsByTagName("guid")[0].attributes.get("isPermaLink") ) def test_rss2_feed_with_callable_object(self): response = self.client.get("/syndication/rss2/with-callable-object/") doc = minidom.parseString(response.content) chan = doc.getElementsByTagName("rss")[0].getElementsByTagName("channel")[0] self.assertChildNodeContent(chan, {"ttl": "700"}) def test_rss2_feed_with_decorated_methods(self): response = self.client.get("/syndication/rss2/with-decorated-methods/") doc = minidom.parseString(response.content) chan = doc.getElementsByTagName("rss")[0].getElementsByTagName("channel")[0] self.assertCategories(chan, ["javascript", "vue"]) self.assertChildNodeContent( chan, { "title": "Overridden title -- decorated by @wraps.", "description": "Overridden description -- decorated by @wraps.", "ttl": "800 -- decorated by @wraps.", "copyright": "Copyright (c) 2022, John Doe -- decorated by @wraps.", }, ) items = chan.getElementsByTagName("item") self.assertChildNodeContent( items[0], { "title": ( f"Overridden item title: {self.e1.title} -- decorated by @wraps." ), "description": "Overridden item description -- decorated by @wraps.", }, ) def test_rss2_feed_with_wrong_decorated_methods(self): msg = ( "Feed method 'item_description' decorated by 'wrapper' needs to use " "@functools.wraps." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get("/syndication/rss2/with-wrong-decorated-methods/") def test_rss2_feed_guid_permalink_false(self): """ Test if the 'isPermaLink' attribute of <guid> element of an item in the RSS feed is 'false'. """ response = self.client.get("/syndication/rss2/guid_ispermalink_false/") doc = minidom.parseString(response.content) chan = doc.getElementsByTagName("rss")[0].getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") for item in items: self.assertEqual( item.getElementsByTagName("guid")[0] .attributes.get("isPermaLink") .value, "false", ) def test_rss2_feed_guid_permalink_true(self): """ Test if the 'isPermaLink' attribute of <guid> element of an item in the RSS feed is 'true'. """ response = self.client.get("/syndication/rss2/guid_ispermalink_true/") doc = minidom.parseString(response.content) chan = doc.getElementsByTagName("rss")[0].getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") for item in items: self.assertEqual( item.getElementsByTagName("guid")[0] .attributes.get("isPermaLink") .value, "true", ) def test_rss2_single_enclosure(self): response = self.client.get("/syndication/rss2/single-enclosure/") doc = minidom.parseString(response.content) chan = doc.getElementsByTagName("rss")[0].getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") for item in items: enclosures = item.getElementsByTagName("enclosure") self.assertEqual(len(enclosures), 1) def test_rss2_multiple_enclosures(self): with self.assertRaisesMessage( ValueError, "RSS feed items may only have one enclosure, see " "http://www.rssboard.org/rss-profile#element-channel-item-enclosure", ): self.client.get("/syndication/rss2/multiple-enclosure/") def test_rss091_feed(self): """ Test the structure and content of feeds generated by RssUserland091Feed. """ response = self.client.get("/syndication/rss091/") doc = minidom.parseString(response.content) # Making sure there's only 1 `rss` element and that the correct # RSS version was specified. feed_elem = doc.getElementsByTagName("rss") self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute("version"), "0.91") # Making sure there's only one `channel` element w/in the # `rss` element. chan_elem = feed.getElementsByTagName("channel") self.assertEqual(len(chan_elem), 1) chan = chan_elem[0] self.assertChildNodes( chan, [ "title", "link", "description", "language", "lastBuildDate", "item", "atom:link", "ttl", "copyright", "category", ], ) # Ensure the content of the channel is correct self.assertChildNodeContent( chan, { "title": "My blog", "link": "http://example.com/blog/", }, ) self.assertCategories(chan, ["python", "django"]) # Check feed_url is passed self.assertEqual( chan.getElementsByTagName("atom:link")[0].getAttribute("href"), "http://example.com/syndication/rss091/", ) items = chan.getElementsByTagName("item") self.assertEqual(len(items), Entry.objects.count()) self.assertChildNodeContent( items[0], { "title": "My first entry", "description": "Overridden description: My first entry", "link": "http://example.com/blog/%s/" % self.e1.pk, }, ) for item in items: self.assertChildNodes(item, ["title", "link", "description"]) self.assertCategories(item, []) def test_atom_feed(self): """ Test the structure and content of feeds generated by Atom1Feed. """ response = self.client.get("/syndication/atom/") feed = minidom.parseString(response.content).firstChild self.assertEqual(feed.nodeName, "feed") self.assertEqual(feed.getAttribute("xmlns"), "http://www.w3.org/2005/Atom") self.assertChildNodes( feed, [ "title", "subtitle", "link", "id", "updated", "entry", "rights", "category", "author", ], ) for link in feed.getElementsByTagName("link"): if link.getAttribute("rel") == "self": self.assertEqual( link.getAttribute("href"), "http://example.com/syndication/atom/" ) entries = feed.getElementsByTagName("entry") self.assertEqual(len(entries), Entry.objects.count()) for entry in entries: self.assertChildNodes( entry, [ "title", "link", "id", "summary", "category", "updated", "published", "rights", "author", ], ) summary = entry.getElementsByTagName("summary")[0] self.assertEqual(summary.getAttribute("type"), "html") def test_atom_feed_published_and_updated_elements(self): """ The published and updated elements are not the same and now adhere to RFC 4287. """ response = self.client.get("/syndication/atom/") feed = minidom.parseString(response.content).firstChild entries = feed.getElementsByTagName("entry") published = entries[0].getElementsByTagName("published")[0].firstChild.wholeText updated = entries[0].getElementsByTagName("updated")[0].firstChild.wholeText self.assertNotEqual(published, updated) def test_atom_single_enclosure(self): response = self.client.get("/syndication/atom/single-enclosure/") feed = minidom.parseString(response.content).firstChild items = feed.getElementsByTagName("entry") for item in items: links = item.getElementsByTagName("link") links = [link for link in links if link.getAttribute("rel") == "enclosure"] self.assertEqual(len(links), 1) def test_atom_multiple_enclosures(self): response = self.client.get("/syndication/atom/multiple-enclosure/") feed = minidom.parseString(response.content).firstChild items = feed.getElementsByTagName("entry") for item in items: links = item.getElementsByTagName("link") links = [link for link in links if link.getAttribute("rel") == "enclosure"] self.assertEqual(len(links), 2) def test_latest_post_date(self): """ Both the published and updated dates are considered when determining the latest post date. """ # this feed has a `published` element with the latest date response = self.client.get("/syndication/atom/") feed = minidom.parseString(response.content).firstChild updated = feed.getElementsByTagName("updated")[0].firstChild.wholeText d = Entry.objects.latest("published").published latest_published = rfc3339_date(timezone.make_aware(d, TZ)) self.assertEqual(updated, latest_published) # this feed has an `updated` element with the latest date response = self.client.get("/syndication/latest/") feed = minidom.parseString(response.content).firstChild updated = feed.getElementsByTagName("updated")[0].firstChild.wholeText d = Entry.objects.exclude(title="My last entry").latest("updated").updated latest_updated = rfc3339_date(timezone.make_aware(d, TZ)) self.assertEqual(updated, latest_updated) def test_custom_feed_generator(self): response = self.client.get("/syndication/custom/") feed = minidom.parseString(response.content).firstChild self.assertEqual(feed.nodeName, "feed") self.assertEqual(feed.getAttribute("django"), "rocks") self.assertChildNodes( feed, [ "title", "subtitle", "link", "id", "updated", "entry", "spam", "rights", "category", "author", ], ) entries = feed.getElementsByTagName("entry") self.assertEqual(len(entries), Entry.objects.count()) for entry in entries: self.assertEqual(entry.getAttribute("bacon"), "yum") self.assertChildNodes( entry, [ "title", "link", "id", "summary", "ministry", "rights", "author", "updated", "published", "category", ], ) summary = entry.getElementsByTagName("summary")[0] self.assertEqual(summary.getAttribute("type"), "html") def test_feed_generator_language_attribute(self): response = self.client.get("/syndication/language/") feed = minidom.parseString(response.content).firstChild self.assertEqual( feed.firstChild.getElementsByTagName("language")[0].firstChild.nodeValue, "de", ) def test_title_escaping(self): """ Titles are escaped correctly in RSS feeds. """ response = self.client.get("/syndication/rss2/") doc = minidom.parseString(response.content) for item in doc.getElementsByTagName("item"): link = item.getElementsByTagName("link")[0] if link.firstChild.wholeText == "http://example.com/blog/4/": title = item.getElementsByTagName("title")[0] self.assertEqual(title.firstChild.wholeText, "A &amp; B &lt; C &gt; D") def test_naive_datetime_conversion(self): """ Datetimes are correctly converted to the local time zone. """ # Naive date times passed in get converted to the local time zone, so # check the received zone offset against the local offset. response = self.client.get("/syndication/naive-dates/") doc = minidom.parseString(response.content) updated = doc.getElementsByTagName("updated")[0].firstChild.wholeText d = Entry.objects.latest("published").published latest = rfc3339_date(timezone.make_aware(d, TZ)) self.assertEqual(updated, latest) def test_aware_datetime_conversion(self): """ Datetimes with timezones don't get trodden on. """ response = self.client.get("/syndication/aware-dates/") doc = minidom.parseString(response.content) published = doc.getElementsByTagName("published")[0].firstChild.wholeText self.assertEqual(published[-6:], "+00:42") def test_feed_no_content_self_closing_tag(self): tests = [ (Atom1Feed, "link"), (Rss201rev2Feed, "atom:link"), ] for feedgenerator, tag in tests: with self.subTest(feedgenerator=feedgenerator.__name__): feed = feedgenerator( title="title", link="https://example.com", description="self closing tags test", feed_url="https://feed.url.com", ) doc = feed.writeString("utf-8") self.assertIn(f'<{tag} href="https://feed.url.com" rel="self"/>', doc) @requires_tz_support def test_feed_last_modified_time_naive_date(self): """ Tests the Last-Modified header with naive publication dates. """ response = self.client.get("/syndication/naive-dates/") self.assertEqual( response.headers["Last-Modified"], "Tue, 26 Mar 2013 01:00:00 GMT" ) def test_feed_last_modified_time(self): """ Tests the Last-Modified header with aware publication dates. """ response = self.client.get("/syndication/aware-dates/") self.assertEqual( response.headers["Last-Modified"], "Mon, 25 Mar 2013 19:18:00 GMT" ) # No last-modified when feed has no item_pubdate response = self.client.get("/syndication/no_pubdate/") self.assertFalse(response.has_header("Last-Modified")) def test_feed_url(self): """ The feed_url can be overridden. """ response = self.client.get("/syndication/feedurl/") doc = minidom.parseString(response.content) for link in doc.getElementsByTagName("link"): if link.getAttribute("rel") == "self": self.assertEqual( link.getAttribute("href"), "http://example.com/customfeedurl/" ) def test_secure_urls(self): """ Test URLs are prefixed with https:// when feed is requested over HTTPS. """ response = self.client.get( "/syndication/rss2/", **{ "wsgi.url_scheme": "https", }, ) doc = minidom.parseString(response.content) chan = doc.getElementsByTagName("channel")[0] self.assertEqual( chan.getElementsByTagName("link")[0].firstChild.wholeText[0:5], "https" ) atom_link = chan.getElementsByTagName("atom:link")[0] self.assertEqual(atom_link.getAttribute("href")[0:5], "https") for link in doc.getElementsByTagName("link"): if link.getAttribute("rel") == "self": self.assertEqual(link.getAttribute("href")[0:5], "https") def test_item_link_error(self): """ An ImproperlyConfigured is raised if no link could be found for the item(s). """ msg = ( "Give your Article class a get_absolute_url() method, or define " "an item_link() method in your Feed class." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get("/syndication/articles/") def test_template_feed(self): """ The item title and description can be overridden with templates. """ response = self.client.get("/syndication/template/") doc = minidom.parseString(response.content) feed = doc.getElementsByTagName("rss")[0] chan = feed.getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") self.assertChildNodeContent( items[0], { "title": "Title in your templates: My first entry\n", "description": "Description in your templates: My first entry\n", "link": "http://example.com/blog/%s/" % self.e1.pk, }, ) def test_template_context_feed(self): """ Custom context data can be passed to templates for title and description. """ response = self.client.get("/syndication/template_context/") doc = minidom.parseString(response.content) feed = doc.getElementsByTagName("rss")[0] chan = feed.getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") self.assertChildNodeContent( items[0], { "title": "My first entry (foo is bar)\n", "description": "My first entry (foo is bar)\n", }, ) def test_add_domain(self): """ add_domain() prefixes domains onto the correct URLs. """ prefix_domain_mapping = ( (("example.com", "/foo/?arg=value"), "http://example.com/foo/?arg=value"), ( ("example.com", "/foo/?arg=value", True), "https://example.com/foo/?arg=value", ), ( ("example.com", "http://djangoproject.com/doc/"), "http://djangoproject.com/doc/", ), ( ("example.com", "https://djangoproject.com/doc/"), "https://djangoproject.com/doc/", ), ( ("example.com", "mailto:[email protected]"), "mailto:[email protected]", ), ( ("example.com", "//example.com/foo/?arg=value"), "http://example.com/foo/?arg=value", ), ) for prefix in prefix_domain_mapping: with self.subTest(prefix=prefix): self.assertEqual(views.add_domain(*prefix[0]), prefix[1]) def test_get_object(self): response = self.client.get("/syndication/rss2/articles/%s/" % self.e1.pk) doc = minidom.parseString(response.content) feed = doc.getElementsByTagName("rss")[0] chan = feed.getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") self.assertChildNodeContent( items[0], { "comments": "/blog/%s/article/%s/comments" % (self.e1.pk, self.a1.pk), "description": "Article description: My first article", "link": "http://example.com/blog/%s/article/%s/" % (self.e1.pk, self.a1.pk), "title": "Title: My first article", "pubDate": rfc2822_date(timezone.make_aware(self.a1.published, TZ)), }, ) def test_get_non_existent_object(self): response = self.client.get("/syndication/rss2/articles/0/") self.assertEqual(response.status_code, 404)
cdecb5fd664139af48fcd505fbff3f3f292a22cf2a3e44fe4cc839bdc5125c90
from functools import wraps from django.contrib.syndication import views from django.utils import feedgenerator from django.utils.timezone import get_fixed_timezone from .models import Article, Entry def wraps_decorator(f): @wraps(f) def wrapper(*args, **kwargs): value = f(*args, **kwargs) return f"{value} -- decorated by @wraps." return wrapper def common_decorator(f): def wrapper(*args, **kwargs): value = f(*args, **kwargs) return f"{value} -- common decorated." return wrapper class TestRss2Feed(views.Feed): title = "My blog" description = "A more thorough description of my blog." link = "/blog/" feed_guid = "/foo/bar/1234" author_name = "Sally Smith" author_email = "[email protected]" author_link = "http://www.example.com/" categories = ("python", "django") feed_copyright = "Copyright (c) 2007, Sally Smith" ttl = 600 def items(self): return Entry.objects.all() def item_description(self, item): return "Overridden description: %s" % item def item_pubdate(self, item): return item.published def item_updateddate(self, item): return item.updated def item_comments(self, item): return "%scomments" % item.get_absolute_url() item_author_name = "Sally Smith" item_author_email = "[email protected]" item_author_link = "http://www.example.com/" item_categories = ("python", "testing") item_copyright = "Copyright (c) 2007, Sally Smith" class TestRss2FeedWithCallableObject(TestRss2Feed): class TimeToLive: def __call__(self): return 700 ttl = TimeToLive() class TestRss2FeedWithDecoratedMethod(TestRss2Feed): class TimeToLive: @wraps_decorator def __call__(self): return 800 @staticmethod @wraps_decorator def feed_copyright(): return "Copyright (c) 2022, John Doe" ttl = TimeToLive() @staticmethod def categories(): return ("javascript", "vue") @wraps_decorator def title(self): return "Overridden title" @wraps_decorator def item_title(self, item): return f"Overridden item title: {item.title}" @wraps_decorator def description(self, obj): return "Overridden description" @wraps_decorator def item_description(self): return "Overridden item description" class TestRss2FeedWithWrongDecoratedMethod(TestRss2Feed): @common_decorator def item_description(self, item): return f"Overridden item description: {item.title}" class TestRss2FeedWithGuidIsPermaLinkTrue(TestRss2Feed): def item_guid_is_permalink(self, item): return True class TestRss2FeedWithGuidIsPermaLinkFalse(TestRss2Feed): def item_guid(self, item): return str(item.pk) def item_guid_is_permalink(self, item): return False class TestRss091Feed(TestRss2Feed): feed_type = feedgenerator.RssUserland091Feed class TestNoPubdateFeed(views.Feed): title = "Test feed" link = "/feed/" def items(self): return Entry.objects.all() class TestAtomFeed(TestRss2Feed): feed_type = feedgenerator.Atom1Feed subtitle = TestRss2Feed.description class TestLatestFeed(TestRss2Feed): """ A feed where the latest entry date is an `updated` element. """ feed_type = feedgenerator.Atom1Feed subtitle = TestRss2Feed.description def items(self): return Entry.objects.exclude(title="My last entry") class ArticlesFeed(TestRss2Feed): """ A feed to test no link being defined. Articles have no get_absolute_url() method, and item_link() is not defined. """ def items(self): return Article.objects.all() class TestSingleEnclosureRSSFeed(TestRss2Feed): """ A feed to test that RSS feeds work with a single enclosure. """ def item_enclosure_url(self, item): return "http://example.com" def item_enclosure_size(self, item): return 0 def item_mime_type(self, item): return "image/png" class TestMultipleEnclosureRSSFeed(TestRss2Feed): """ A feed to test that RSS feeds raise an exception with multiple enclosures. """ def item_enclosures(self, item): return [ feedgenerator.Enclosure("http://example.com/hello.png", 0, "image/png"), feedgenerator.Enclosure("http://example.com/goodbye.png", 0, "image/png"), ] class TemplateFeed(TestRss2Feed): """ A feed to test defining item titles and descriptions with templates. """ title_template = "syndication/title.html" description_template = "syndication/description.html" # Defining a template overrides any item_title definition def item_title(self): return "Not in a template" class TemplateContextFeed(TestRss2Feed): """ A feed to test custom context data in templates for title or description. """ title_template = "syndication/title_context.html" description_template = "syndication/description_context.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["foo"] = "bar" return context class TestLanguageFeed(TestRss2Feed): language = "de" class TestGetObjectFeed(TestRss2Feed): def get_object(self, request, entry_id): return Entry.objects.get(pk=entry_id) def items(self, obj): return Article.objects.filter(entry=obj) def item_link(self, item): return "%sarticle/%s/" % (item.entry.get_absolute_url(), item.pk) def item_comments(self, item): return "%scomments" % self.item_link(item) def item_description(self, item): return "Article description: %s" % item.title def item_title(self, item): return "Title: %s" % item.title class NaiveDatesFeed(TestAtomFeed): """ A feed with naive (non-timezone-aware) dates. """ def item_pubdate(self, item): return item.published class TZAwareDatesFeed(TestAtomFeed): """ A feed with timezone-aware dates. """ def item_pubdate(self, item): # Provide a weird offset so that the test can know it's getting this # specific offset and not accidentally getting on from # settings.TIME_ZONE. return item.published.replace(tzinfo=get_fixed_timezone(42)) class TestFeedUrlFeed(TestAtomFeed): feed_url = "http://example.com/customfeedurl/" class MyCustomAtom1Feed(feedgenerator.Atom1Feed): """ Test of a custom feed generator class. """ def root_attributes(self): attrs = super().root_attributes() attrs["django"] = "rocks" return attrs def add_root_elements(self, handler): super().add_root_elements(handler) handler.addQuickElement("spam", "eggs") def item_attributes(self, item): attrs = super().item_attributes(item) attrs["bacon"] = "yum" return attrs def add_item_elements(self, handler, item): super().add_item_elements(handler, item) handler.addQuickElement("ministry", "silly walks") class TestCustomFeed(TestAtomFeed): feed_type = MyCustomAtom1Feed class TestSingleEnclosureAtomFeed(TestAtomFeed): """ A feed to test that Atom feeds work with a single enclosure. """ def item_enclosure_url(self, item): return "http://example.com" def item_enclosure_size(self, item): return 0 def item_mime_type(self, item): return "image/png" class TestMultipleEnclosureAtomFeed(TestAtomFeed): """ A feed to test that Atom feeds work with multiple enclosures. """ def item_enclosures(self, item): return [ feedgenerator.Enclosure("http://example.com/hello.png", "0", "image/png"), feedgenerator.Enclosure("http://example.com/goodbye.png", "0", "image/png"), ]
a2213e118f8a809923af47c3c9e8bfcd78398c56382e255dadfa95ced4c7dad5
from django.urls import path from . import feeds urlpatterns = [ path("syndication/rss2/", feeds.TestRss2Feed()), path( "syndication/rss2/with-callable-object/", feeds.TestRss2FeedWithCallableObject() ), path( "syndication/rss2/with-decorated-methods/", feeds.TestRss2FeedWithDecoratedMethod(), ), path( "syndication/rss2/with-wrong-decorated-methods/", feeds.TestRss2FeedWithWrongDecoratedMethod(), ), path("syndication/rss2/articles/<int:entry_id>/", feeds.TestGetObjectFeed()), path( "syndication/rss2/guid_ispermalink_true/", feeds.TestRss2FeedWithGuidIsPermaLinkTrue(), ), path( "syndication/rss2/guid_ispermalink_false/", feeds.TestRss2FeedWithGuidIsPermaLinkFalse(), ), path("syndication/rss091/", feeds.TestRss091Feed()), path("syndication/no_pubdate/", feeds.TestNoPubdateFeed()), path("syndication/atom/", feeds.TestAtomFeed()), path("syndication/latest/", feeds.TestLatestFeed()), path("syndication/custom/", feeds.TestCustomFeed()), path("syndication/language/", feeds.TestLanguageFeed()), path("syndication/naive-dates/", feeds.NaiveDatesFeed()), path("syndication/aware-dates/", feeds.TZAwareDatesFeed()), path("syndication/feedurl/", feeds.TestFeedUrlFeed()), path("syndication/articles/", feeds.ArticlesFeed()), path("syndication/template/", feeds.TemplateFeed()), path("syndication/template_context/", feeds.TemplateContextFeed()), path("syndication/rss2/single-enclosure/", feeds.TestSingleEnclosureRSSFeed()), path("syndication/rss2/multiple-enclosure/", feeds.TestMultipleEnclosureRSSFeed()), path("syndication/atom/single-enclosure/", feeds.TestSingleEnclosureAtomFeed()), path("syndication/atom/multiple-enclosure/", feeds.TestMultipleEnclosureAtomFeed()), ]
337a84223090e088c05c4d6ff89b2033cc7c69e56fa7e4e946823b5a05366458
import os import re from io import StringIO from unittest import mock, skipUnless from django.core.management import call_command from django.db import connection from django.db.backends.base.introspection import TableInfo from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from .models import PeopleMoreData, test_collation def inspectdb_tables_only(table_name): """ Limit introspection to tables created for models of this app. Some databases such as Oracle are extremely slow at introspection. """ return table_name.startswith("inspectdb_") def inspectdb_views_only(table_name): return table_name.startswith("inspectdb_") and table_name.endswith( ("_materialized", "_view") ) def special_table_only(table_name): return table_name.startswith("inspectdb_special") class InspectDBTestCase(TestCase): unique_re = re.compile(r".*unique_together = \((.+),\).*") def test_stealth_table_name_filter_option(self): out = StringIO() call_command("inspectdb", table_name_filter=inspectdb_tables_only, stdout=out) error_message = ( "inspectdb has examined a table that should have been filtered out." ) # contrib.contenttypes is one of the apps always installed when running # the Django test suite, check that one of its tables hasn't been # inspected self.assertNotIn( "class DjangoContentType(models.Model):", out.getvalue(), msg=error_message ) def test_table_option(self): """ inspectdb can inspect a subset of tables by passing the table names as arguments. """ out = StringIO() call_command("inspectdb", "inspectdb_people", stdout=out) output = out.getvalue() self.assertIn("class InspectdbPeople(models.Model):", output) self.assertNotIn("InspectdbPeopledata", output) def make_field_type_asserter(self): """ Call inspectdb and return a function to validate a field type in its output. """ out = StringIO() call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() def assertFieldType(name, definition): out_def = re.search(r"^\s*%s = (models.*)$" % name, output, re.MULTILINE)[1] self.assertEqual(definition, out_def) return assertFieldType def test_field_types(self): """Test introspection of various Django field types""" assertFieldType = self.make_field_type_asserter() introspected_field_types = connection.features.introspected_field_types char_field_type = introspected_field_types["CharField"] # Inspecting Oracle DB doesn't produce correct results (#19884): # - it reports fields as blank=True when they aren't. if ( not connection.features.interprets_empty_strings_as_nulls and char_field_type == "CharField" ): assertFieldType("char_field", "models.CharField(max_length=10)") assertFieldType( "null_char_field", "models.CharField(max_length=10, blank=True, null=True)", ) assertFieldType("email_field", "models.CharField(max_length=254)") assertFieldType("file_field", "models.CharField(max_length=100)") assertFieldType("file_path_field", "models.CharField(max_length=100)") assertFieldType("slug_field", "models.CharField(max_length=50)") assertFieldType("text_field", "models.TextField()") assertFieldType("url_field", "models.CharField(max_length=200)") if char_field_type == "TextField": assertFieldType("char_field", "models.TextField()") assertFieldType( "null_char_field", "models.TextField(blank=True, null=True)" ) assertFieldType("email_field", "models.TextField()") assertFieldType("file_field", "models.TextField()") assertFieldType("file_path_field", "models.TextField()") assertFieldType("slug_field", "models.TextField()") assertFieldType("text_field", "models.TextField()") assertFieldType("url_field", "models.TextField()") assertFieldType("date_field", "models.DateField()") assertFieldType("date_time_field", "models.DateTimeField()") if introspected_field_types["GenericIPAddressField"] == "GenericIPAddressField": assertFieldType("gen_ip_address_field", "models.GenericIPAddressField()") elif not connection.features.interprets_empty_strings_as_nulls: assertFieldType("gen_ip_address_field", "models.CharField(max_length=39)") assertFieldType( "time_field", "models.%s()" % introspected_field_types["TimeField"] ) if connection.features.has_native_uuid_field: assertFieldType("uuid_field", "models.UUIDField()") elif not connection.features.interprets_empty_strings_as_nulls: assertFieldType("uuid_field", "models.CharField(max_length=32)") @skipUnlessDBFeature("can_introspect_json_field", "supports_json_field") def test_json_field(self): out = StringIO() call_command("inspectdb", "inspectdb_jsonfieldcolumntype", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn("json_field = models.JSONField()", output) self.assertIn( "null_json_field = models.JSONField(blank=True, null=True)", output ) @skipUnlessDBFeature("supports_collation_on_charfield") @skipUnless(test_collation, "Language collations are not supported.") def test_char_field_db_collation(self): out = StringIO() call_command("inspectdb", "inspectdb_charfielddbcollation", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn( "char_field = models.CharField(max_length=10, " "db_collation='%s')" % test_collation, output, ) else: self.assertIn( "char_field = models.CharField(max_length=10, " "db_collation='%s', blank=True, null=True)" % test_collation, output, ) @skipUnlessDBFeature("supports_collation_on_textfield") @skipUnless(test_collation, "Language collations are not supported.") def test_text_field_db_collation(self): out = StringIO() call_command("inspectdb", "inspectdb_textfielddbcollation", stdout=out) output = out.getvalue() if not connection.features.interprets_empty_strings_as_nulls: self.assertIn( "text_field = models.TextField(db_collation='%s')" % test_collation, output, ) else: self.assertIn( "text_field = models.TextField(db_collation='%s, blank=True, " "null=True)" % test_collation, output, ) def test_number_field_types(self): """Test introspection of various Django field types""" assertFieldType = self.make_field_type_asserter() introspected_field_types = connection.features.introspected_field_types auto_field_type = connection.features.introspected_field_types["AutoField"] if auto_field_type != "AutoField": assertFieldType( "id", "models.%s(primary_key=True) # AutoField?" % auto_field_type ) assertFieldType( "big_int_field", "models.%s()" % introspected_field_types["BigIntegerField"] ) bool_field_type = introspected_field_types["BooleanField"] assertFieldType("bool_field", "models.{}()".format(bool_field_type)) assertFieldType( "null_bool_field", "models.{}(blank=True, null=True)".format(bool_field_type), ) if connection.vendor != "sqlite": assertFieldType( "decimal_field", "models.DecimalField(max_digits=6, decimal_places=1)" ) else: # Guessed arguments on SQLite, see #5014 assertFieldType( "decimal_field", "models.DecimalField(max_digits=10, decimal_places=5) " "# max_digits and decimal_places have been guessed, " "as this database handles decimal fields as float", ) assertFieldType("float_field", "models.FloatField()") assertFieldType( "int_field", "models.%s()" % introspected_field_types["IntegerField"] ) assertFieldType( "pos_int_field", "models.%s()" % introspected_field_types["PositiveIntegerField"], ) assertFieldType( "pos_big_int_field", "models.%s()" % introspected_field_types["PositiveBigIntegerField"], ) assertFieldType( "pos_small_int_field", "models.%s()" % introspected_field_types["PositiveSmallIntegerField"], ) assertFieldType( "small_int_field", "models.%s()" % introspected_field_types["SmallIntegerField"], ) @skipUnlessDBFeature("can_introspect_foreign_keys") def test_attribute_name_not_python_keyword(self): out = StringIO() call_command("inspectdb", table_name_filter=inspectdb_tables_only, stdout=out) output = out.getvalue() error_message = ( "inspectdb generated an attribute name which is a Python keyword" ) # Recursive foreign keys should be set to 'self' self.assertIn("parent = models.ForeignKey('self', models.DO_NOTHING)", output) self.assertNotIn( "from = models.ForeignKey(InspectdbPeople, models.DO_NOTHING)", output, msg=error_message, ) # As InspectdbPeople model is defined after InspectdbMessage, it should # be quoted. self.assertIn( "from_field = models.ForeignKey('InspectdbPeople', models.DO_NOTHING, " "db_column='from_id')", output, ) self.assertIn( "people_pk = models.OneToOneField(InspectdbPeople, models.DO_NOTHING, " "primary_key=True)", output, ) self.assertIn( "people_unique = models.OneToOneField(InspectdbPeople, models.DO_NOTHING)", output, ) @skipUnlessDBFeature("can_introspect_foreign_keys") def test_foreign_key_to_field(self): out = StringIO() call_command("inspectdb", "inspectdb_foreignkeytofield", stdout=out) self.assertIn( "to_field_fk = models.ForeignKey('InspectdbPeoplemoredata', " "models.DO_NOTHING, to_field='people_unique_id')", out.getvalue(), ) def test_digits_column_name_introspection(self): """Introspection of column names consist/start with digits (#16536/#17676)""" char_field_type = connection.features.introspected_field_types["CharField"] out = StringIO() call_command("inspectdb", "inspectdb_digitsincolumnname", stdout=out) output = out.getvalue() error_message = "inspectdb generated a model field name which is a number" self.assertNotIn( " 123 = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_123 = models.%s" % char_field_type, output) error_message = ( "inspectdb generated a model field name which starts with a digit" ) self.assertNotIn( " 4extra = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_4extra = models.%s" % char_field_type, output) self.assertNotIn( " 45extra = models.%s" % char_field_type, output, msg=error_message ) self.assertIn("number_45extra = models.%s" % char_field_type, output) def test_special_column_name_introspection(self): """ Introspection of column names containing special characters, unsuitable for Python identifiers """ out = StringIO() call_command("inspectdb", table_name_filter=special_table_only, stdout=out) output = out.getvalue() base_name = connection.introspection.identifier_converter("Field") integer_field_type = connection.features.introspected_field_types[ "IntegerField" ] self.assertIn("field = models.%s()" % integer_field_type, output) self.assertIn( "field_field = models.%s(db_column='%s_')" % (integer_field_type, base_name), output, ) self.assertIn( "field_field_0 = models.%s(db_column='%s__')" % (integer_field_type, base_name), output, ) self.assertIn( "field_field_1 = models.%s(db_column='__field')" % integer_field_type, output, ) self.assertIn( "prc_x = models.{}(db_column='prc(%) x')".format(integer_field_type), output ) self.assertIn("tamaño = models.%s()" % integer_field_type, output) def test_table_name_introspection(self): """ Introspection of table names containing special characters, unsuitable for Python identifiers """ out = StringIO() call_command("inspectdb", table_name_filter=special_table_only, stdout=out) output = out.getvalue() self.assertIn("class InspectdbSpecialTableName(models.Model):", output) @skipUnlessDBFeature("supports_expression_indexes") def test_table_with_func_unique_constraint(self): out = StringIO() call_command("inspectdb", "inspectdb_funcuniqueconstraint", stdout=out) output = out.getvalue() self.assertIn("class InspectdbFuncuniqueconstraint(models.Model):", output) def test_managed_models(self): """ By default the command generates models with `Meta.managed = False`. """ out = StringIO() call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() self.longMessage = False self.assertIn( " managed = False", output, msg="inspectdb should generate unmanaged models.", ) def test_unique_together_meta(self): out = StringIO() call_command("inspectdb", "inspectdb_uniquetogether", stdout=out) output = out.getvalue() self.assertIn(" unique_together = (('", output) unique_together_match = self.unique_re.findall(output) # There should be one unique_together tuple. self.assertEqual(len(unique_together_match), 1) fields = unique_together_match[0] # Fields with db_column = field name. self.assertIn("('field1', 'field2')", fields) # Fields from columns whose names are Python keywords. self.assertIn("('field1', 'field2')", fields) # Fields whose names normalize to the same Python field name and hence # are given an integer suffix. self.assertIn("('non_unique_column', 'non_unique_column_0')", fields) @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_unsupported_unique_together(self): """Unsupported index types (COALESCE here) are skipped.""" with connection.cursor() as c: c.execute( "CREATE UNIQUE INDEX Findex ON %s " "(id, people_unique_id, COALESCE(message_id, -1))" % PeopleMoreData._meta.db_table ) try: out = StringIO() call_command( "inspectdb", table_name_filter=lambda tn: tn.startswith( PeopleMoreData._meta.db_table ), stdout=out, ) output = out.getvalue() self.assertIn("# A unique constraint could not be introspected.", output) self.assertEqual( self.unique_re.findall(output), ["('id', 'people_unique')"] ) finally: with connection.cursor() as c: c.execute("DROP INDEX Findex") @skipUnless( connection.vendor == "sqlite", "Only patched sqlite's DatabaseIntrospection.data_types_reverse for this test", ) def test_custom_fields(self): """ Introspection of columns with a custom field (#21090) """ out = StringIO() with mock.patch( "django.db.connection.introspection.data_types_reverse." "base_data_types_reverse", { "text": "myfields.TextField", "bigint": "BigIntegerField", }, ): call_command("inspectdb", "inspectdb_columntypes", stdout=out) output = out.getvalue() self.assertIn("text_field = myfields.TextField()", output) self.assertIn("big_int_field = models.BigIntegerField()", output) def test_introspection_errors(self): """ Introspection errors should not crash the command, and the error should be visible in the output. """ out = StringIO() with mock.patch( "django.db.connection.introspection.get_table_list", return_value=[TableInfo(name="nonexistent", type="t")], ): call_command("inspectdb", stdout=out) output = out.getvalue() self.assertIn("# Unable to inspect table 'nonexistent'", output) # The error message depends on the backend self.assertIn("# The error was:", output) class InspectDBTransactionalTests(TransactionTestCase): available_apps = ["inspectdb"] def test_include_views(self): """inspectdb --include-views creates models for database views.""" with connection.cursor() as cursor: cursor.execute( "CREATE VIEW inspectdb_people_view AS " "SELECT id, name FROM inspectdb_people" ) out = StringIO() view_model = "class InspectdbPeopleView(models.Model):" view_managed = "managed = False # Created from a view." try: call_command( "inspectdb", table_name_filter=inspectdb_views_only, stdout=out, ) no_views_output = out.getvalue() self.assertNotIn(view_model, no_views_output) self.assertNotIn(view_managed, no_views_output) call_command( "inspectdb", table_name_filter=inspectdb_views_only, include_views=True, stdout=out, ) with_views_output = out.getvalue() self.assertIn(view_model, with_views_output) self.assertIn(view_managed, with_views_output) finally: with connection.cursor() as cursor: cursor.execute("DROP VIEW inspectdb_people_view") @skipUnlessDBFeature("can_introspect_materialized_views") def test_include_materialized_views(self): """inspectdb --include-views creates models for materialized views.""" with connection.cursor() as cursor: cursor.execute( "CREATE MATERIALIZED VIEW inspectdb_people_materialized AS " "SELECT id, name FROM inspectdb_people" ) out = StringIO() view_model = "class InspectdbPeopleMaterialized(models.Model):" view_managed = "managed = False # Created from a view." try: call_command( "inspectdb", table_name_filter=inspectdb_views_only, stdout=out, ) no_views_output = out.getvalue() self.assertNotIn(view_model, no_views_output) self.assertNotIn(view_managed, no_views_output) call_command( "inspectdb", table_name_filter=inspectdb_views_only, include_views=True, stdout=out, ) with_views_output = out.getvalue() self.assertIn(view_model, with_views_output) self.assertIn(view_managed, with_views_output) finally: with connection.cursor() as cursor: cursor.execute("DROP MATERIALIZED VIEW inspectdb_people_materialized") @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_include_partitions(self): """inspectdb --include-partitions creates models for partitions.""" with connection.cursor() as cursor: cursor.execute( """\ CREATE TABLE inspectdb_partition_parent (name text not null) PARTITION BY LIST (left(upper(name), 1)) """ ) cursor.execute( """\ CREATE TABLE inspectdb_partition_child PARTITION OF inspectdb_partition_parent FOR VALUES IN ('A', 'B', 'C') """ ) out = StringIO() partition_model_parent = "class InspectdbPartitionParent(models.Model):" partition_model_child = "class InspectdbPartitionChild(models.Model):" partition_managed = "managed = False # Created from a partition." try: call_command( "inspectdb", table_name_filter=inspectdb_tables_only, stdout=out ) no_partitions_output = out.getvalue() self.assertIn(partition_model_parent, no_partitions_output) self.assertNotIn(partition_model_child, no_partitions_output) self.assertNotIn(partition_managed, no_partitions_output) call_command( "inspectdb", table_name_filter=inspectdb_tables_only, include_partitions=True, stdout=out, ) with_partitions_output = out.getvalue() self.assertIn(partition_model_parent, with_partitions_output) self.assertIn(partition_model_child, with_partitions_output) self.assertIn(partition_managed, with_partitions_output) finally: with connection.cursor() as cursor: cursor.execute("DROP TABLE IF EXISTS inspectdb_partition_child") cursor.execute("DROP TABLE IF EXISTS inspectdb_partition_parent") @skipUnless(connection.vendor == "postgresql", "PostgreSQL specific SQL") def test_foreign_data_wrapper(self): with connection.cursor() as cursor: cursor.execute("CREATE EXTENSION IF NOT EXISTS file_fdw") cursor.execute( "CREATE SERVER inspectdb_server FOREIGN DATA WRAPPER file_fdw" ) cursor.execute( """\ CREATE FOREIGN TABLE inspectdb_iris_foreign_table ( petal_length real, petal_width real, sepal_length real, sepal_width real ) SERVER inspectdb_server OPTIONS ( filename %s ) """, [os.devnull], ) out = StringIO() foreign_table_model = "class InspectdbIrisForeignTable(models.Model):" foreign_table_managed = "managed = False" try: call_command( "inspectdb", table_name_filter=inspectdb_tables_only, stdout=out, ) output = out.getvalue() self.assertIn(foreign_table_model, output) self.assertIn(foreign_table_managed, output) finally: with connection.cursor() as cursor: cursor.execute( "DROP FOREIGN TABLE IF EXISTS inspectdb_iris_foreign_table" ) cursor.execute("DROP SERVER IF EXISTS inspectdb_server") cursor.execute("DROP EXTENSION IF EXISTS file_fdw") @skipUnlessDBFeature("create_test_table_with_composite_primary_key") def test_composite_primary_key(self): table_name = "test_table_composite_pk" with connection.cursor() as cursor: cursor.execute( connection.features.create_test_table_with_composite_primary_key ) out = StringIO() if connection.vendor == "sqlite": field_type = connection.features.introspected_field_types["AutoField"] else: field_type = connection.features.introspected_field_types["IntegerField"] try: call_command("inspectdb", table_name, stdout=out) output = out.getvalue() self.assertIn( f"column_1 = models.{field_type}(primary_key=True) # The composite " f"primary key (column_1, column_2) found, that is not supported. The " f"first column is selected.", output, ) self.assertIn( "column_2 = models.IntegerField()", output, ) finally: with connection.cursor() as cursor: cursor.execute("DROP TABLE %s" % table_name)
8419b09457ed6842ba4542b54cbd97b57f1c361571cd581995759d2020959197
import asyncio import sys import threading from pathlib import Path from asgiref.testing import ApplicationCommunicator from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler from django.core.asgi import get_asgi_application from django.core.signals import request_finished, request_started from django.db import close_old_connections from django.test import ( AsyncRequestFactory, SimpleTestCase, modify_settings, override_settings, ) from django.utils.http import http_date from .urls import sync_waiter, test_filename TEST_STATIC_ROOT = Path(__file__).parent / "project" / "static" @override_settings(ROOT_URLCONF="asgi.urls") class ASGITest(SimpleTestCase): async_request_factory = AsyncRequestFactory() def setUp(self): request_started.disconnect(close_old_connections) def tearDown(self): request_started.connect(close_old_connections) async def test_get_asgi_application(self): """ get_asgi_application() returns a functioning ASGI callable. """ application = get_asgi_application() # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Read the response. response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", b"12"), (b"Content-Type", b"text/html; charset=utf-8"), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") async def test_file_response(self): """ Makes sure that FileResponse works over ASGI. """ application = get_asgi_application() # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/file/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Get the file content. with open(test_filename, "rb") as test_file: test_file_contents = test_file.read() # Read the response. response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) headers = response_start["headers"] self.assertEqual(len(headers), 3) expected_headers = { b"Content-Length": str(len(test_file_contents)).encode("ascii"), b"Content-Type": b"text/x-python", b"Content-Disposition": b'inline; filename="urls.py"', } for key, value in headers: try: self.assertEqual(value, expected_headers[key]) except AssertionError: # Windows registry may not be configured with correct # mimetypes. if sys.platform == "win32" and key == b"Content-Type": self.assertEqual(value, b"text/plain") else: raise response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], test_file_contents) # Allow response.close() to finish. await communicator.wait() @modify_settings(INSTALLED_APPS={"append": "django.contrib.staticfiles"}) @override_settings( STATIC_URL="static/", STATIC_ROOT=TEST_STATIC_ROOT, STATICFILES_DIRS=[TEST_STATIC_ROOT], STATICFILES_FINDERS=[ "django.contrib.staticfiles.finders.FileSystemFinder", ], ) async def test_static_file_response(self): application = ASGIStaticFilesHandler(get_asgi_application()) # Construct HTTP request. scope = self.async_request_factory._base_scope(path="/static/file.txt") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) # Get the file content. file_path = TEST_STATIC_ROOT / "file.txt" with open(file_path, "rb") as test_file: test_file_contents = test_file.read() # Read the response. stat = file_path.stat() response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", str(len(test_file_contents)).encode("ascii")), (b"Content-Type", b"text/plain"), (b"Content-Disposition", b'inline; filename="file.txt"'), (b"Last-Modified", http_date(stat.st_mtime).encode("ascii")), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], test_file_contents) # Allow response.close() to finish. await communicator.wait() async def test_headers(self): application = get_asgi_application() communicator = ApplicationCommunicator( application, self.async_request_factory._base_scope( path="/meta/", headers=[ [b"content-type", b"text/plain; charset=utf-8"], [b"content-length", b"77"], [b"referer", b"Scotland"], [b"referer", b"Wales"], ], ), ) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) self.assertEqual( set(response_start["headers"]), { (b"Content-Length", b"19"), (b"Content-Type", b"text/plain; charset=utf-8"), }, ) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"From Scotland,Wales") async def test_post_body(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(method="POST", path="/post/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request", "body": b"Echo!"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Echo!") async def test_get_query_string(self): application = get_asgi_application() for query_string in (b"name=Andrew", "name=Andrew"): with self.subTest(query_string=query_string): scope = self.async_request_factory._base_scope( path="/", query_string=query_string, ) communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello Andrew!") async def test_disconnect(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.disconnect"}) with self.assertRaises(asyncio.TimeoutError): await communicator.receive_output() async def test_wrong_connection_type(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/", type="other") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) msg = "Django can only handle ASGI/HTTP connections, not other." with self.assertRaisesMessage(ValueError, msg): await communicator.receive_output() async def test_non_unicode_query_string(self): application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/", query_string=b"\xff") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 400) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"") async def test_request_lifecycle_signals_dispatched_with_thread_sensitive(self): class SignalHandler: """Track threads handler is dispatched on.""" threads = [] def __call__(self, **kwargs): self.threads.append(threading.current_thread()) signal_handler = SignalHandler() request_started.connect(signal_handler) request_finished.connect(signal_handler) # Perform a basic request. application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/") communicator = ApplicationCommunicator(application, scope) await communicator.send_input({"type": "http.request"}) response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") # Give response.close() time to finish. await communicator.wait() # AsyncToSync should have executed the signals in the same thread. request_started_thread, request_finished_thread = signal_handler.threads self.assertEqual(request_started_thread, request_finished_thread) request_started.disconnect(signal_handler) request_finished.disconnect(signal_handler) async def test_concurrent_async_uses_multiple_thread_pools(self): sync_waiter.active_threads.clear() # Send 2 requests concurrently application = get_asgi_application() scope = self.async_request_factory._base_scope(path="/wait/") communicators = [] for _ in range(2): communicators.append(ApplicationCommunicator(application, scope)) await communicators[-1].send_input({"type": "http.request"}) # Each request must complete with a status code of 200 # If requests aren't scheduled concurrently, the barrier in the # sync_wait view will time out, resulting in a 500 status code. for communicator in communicators: response_start = await communicator.receive_output() self.assertEqual(response_start["type"], "http.response.start") self.assertEqual(response_start["status"], 200) response_body = await communicator.receive_output() self.assertEqual(response_body["type"], "http.response.body") self.assertEqual(response_body["body"], b"Hello World!") # Give response.close() time to finish. await communicator.wait() # The requests should have scheduled on different threads. Note # active_threads is a set (a thread can only appear once), therefore # length is a sufficient check. self.assertEqual(len(sync_waiter.active_threads), 2) sync_waiter.active_threads.clear()
d27f89cdf26b618922bb78740e244cb0c770e1231bc8bc18abd9627037b383d5
import threading from django.http import FileResponse, HttpResponse from django.urls import path from django.views.decorators.csrf import csrf_exempt def hello(request): name = request.GET.get("name") or "World" return HttpResponse("Hello %s!" % name) def hello_meta(request): return HttpResponse( "From %s" % request.META.get("HTTP_REFERER") or "", content_type=request.META.get("CONTENT_TYPE"), ) def sync_waiter(request): with sync_waiter.lock: sync_waiter.active_threads.add(threading.current_thread()) sync_waiter.barrier.wait(timeout=0.5) return hello(request) @csrf_exempt def post_echo(request): return HttpResponse(request.body) sync_waiter.active_threads = set() sync_waiter.lock = threading.Lock() sync_waiter.barrier = threading.Barrier(2) test_filename = __file__ urlpatterns = [ path("", hello), path("file/", lambda x: FileResponse(open(test_filename, "rb"))), path("meta/", hello_meta), path("post/", post_echo), path("wait/", sync_waiter), ]
f6a7636ff4693ce21b0bf7fe4ebc84b5965949d8102b97826bcbaf0fa766f28d
""" Unit tests for reverse URL lookups. """ import pickle import sys import threading from admin_scripts.tests import AdminScriptTestCase from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist from django.http import HttpRequest, HttpResponsePermanentRedirect, HttpResponseRedirect from django.shortcuts import redirect from django.test import RequestFactory, SimpleTestCase, TestCase, override_settings from django.test.utils import override_script_prefix from django.urls import ( NoReverseMatch, Resolver404, ResolverMatch, URLPattern, URLResolver, get_callable, get_resolver, get_urlconf, include, path, re_path, resolve, reverse, reverse_lazy, ) from django.urls.resolvers import RegexPattern from . import middleware, urlconf_outer, views from .utils import URLObject from .views import empty_view resolve_test_data = ( # These entries are in the format: # (path, url_name, app_name, namespace, view_name, func, args, kwargs) # Simple case ( "/normal/42/37/", "normal-view", "", "", "normal-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/view_class/42/37/", "view-class", "", "", "view-class", views.view_class_instance, (), {"arg1": "42", "arg2": "37"}, ), ( "/included/normal/42/37/", "inc-normal-view", "included_namespace_urls", "included_namespace_urls", "included_namespace_urls:inc-normal-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/included/view_class/42/37/", "inc-view-class", "included_namespace_urls", "included_namespace_urls", "included_namespace_urls:inc-view-class", views.view_class_instance, (), {"arg1": "42", "arg2": "37"}, ), # Unnamed args are dropped if you have *any* kwargs in a pattern ( "/mixed_args/42/37/", "mixed-args", "", "", "mixed-args", views.empty_view, (), {"extra": True, "arg2": "37"}, ), ( "/included/mixed_args/42/37/", "inc-mixed-args", "included_namespace_urls", "included_namespace_urls", "included_namespace_urls:inc-mixed-args", views.empty_view, (), {"arg2": "37"}, ), ( "/included/12/mixed_args/42/37/", "inc-mixed-args", "included_namespace_urls", "included_namespace_urls", "included_namespace_urls:inc-mixed-args", views.empty_view, (), {"arg2": "37"}, ), # Unnamed views should have None as the url_name. Regression data for #21157. ( "/unnamed/normal/42/37/", None, "", "", "urlpatterns_reverse.views.empty_view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/unnamed/view_class/42/37/", None, "", "", "urlpatterns_reverse.views.ViewClass", views.view_class_instance, (), {"arg1": "42", "arg2": "37"}, ), # If you have no kwargs, you get an args list. ( "/no_kwargs/42/37/", "no-kwargs", "", "", "no-kwargs", views.empty_view, ("42", "37"), {}, ), ( "/included/no_kwargs/42/37/", "inc-no-kwargs", "included_namespace_urls", "included_namespace_urls", "included_namespace_urls:inc-no-kwargs", views.empty_view, ("42", "37"), {}, ), ( "/included/12/no_kwargs/42/37/", "inc-no-kwargs", "included_namespace_urls", "included_namespace_urls", "included_namespace_urls:inc-no-kwargs", views.empty_view, ("12", "42", "37"), {}, ), # Namespaces ( "/test1/inner/42/37/", "urlobject-view", "testapp", "test-ns1", "test-ns1:urlobject-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/included/test3/inner/42/37/", "urlobject-view", "included_namespace_urls:testapp", "included_namespace_urls:test-ns3", "included_namespace_urls:test-ns3:urlobject-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/ns-included1/normal/42/37/", "inc-normal-view", "included_namespace_urls", "inc-ns1", "inc-ns1:inc-normal-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/included/test3/inner/42/37/", "urlobject-view", "included_namespace_urls:testapp", "included_namespace_urls:test-ns3", "included_namespace_urls:test-ns3:urlobject-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/default/inner/42/37/", "urlobject-view", "testapp", "testapp", "testapp:urlobject-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/other2/inner/42/37/", "urlobject-view", "nodefault", "other-ns2", "other-ns2:urlobject-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/other1/inner/42/37/", "urlobject-view", "nodefault", "other-ns1", "other-ns1:urlobject-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), # Nested namespaces ( "/ns-included1/test3/inner/42/37/", "urlobject-view", "included_namespace_urls:testapp", "inc-ns1:test-ns3", "inc-ns1:test-ns3:urlobject-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/ns-included1/ns-included4/ns-included2/test3/inner/42/37/", "urlobject-view", "included_namespace_urls:namespace_urls:included_namespace_urls:testapp", "inc-ns1:inc-ns4:inc-ns2:test-ns3", "inc-ns1:inc-ns4:inc-ns2:test-ns3:urlobject-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/app-included/test3/inner/42/37/", "urlobject-view", "included_namespace_urls:testapp", "inc-app:test-ns3", "inc-app:test-ns3:urlobject-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), ( "/app-included/ns-included4/ns-included2/test3/inner/42/37/", "urlobject-view", "included_namespace_urls:namespace_urls:included_namespace_urls:testapp", "inc-app:inc-ns4:inc-ns2:test-ns3", "inc-app:inc-ns4:inc-ns2:test-ns3:urlobject-view", views.empty_view, (), {"arg1": "42", "arg2": "37"}, ), # Namespaces capturing variables ( "/inc70/", "inner-nothing", "included_urls", "inc-ns5", "inc-ns5:inner-nothing", views.empty_view, (), {"outer": "70"}, ), ( "/inc78/extra/foobar/", "inner-extra", "included_urls", "inc-ns5", "inc-ns5:inner-extra", views.empty_view, (), {"outer": "78", "extra": "foobar"}, ), ) test_data = ( ("places", "/places/3/", [3], {}), ("places", "/places/3/", ["3"], {}), ("places", NoReverseMatch, ["a"], {}), ("places", NoReverseMatch, [], {}), ("places?", "/place/", [], {}), ("places+", "/places/", [], {}), ("places*", "/place/", [], {}), ("places2?", "/", [], {}), ("places2+", "/places/", [], {}), ("places2*", "/", [], {}), ("places3", "/places/4/", [4], {}), ("places3", "/places/harlem/", ["harlem"], {}), ("places3", NoReverseMatch, ["harlem64"], {}), ("places4", "/places/3/", [], {"id": 3}), ("people", NoReverseMatch, [], {}), ("people", "/people/adrian/", ["adrian"], {}), ("people", "/people/adrian/", [], {"name": "adrian"}), ("people", NoReverseMatch, ["name with spaces"], {}), ("people", NoReverseMatch, [], {"name": "name with spaces"}), ("people2", "/people/name/", [], {}), ("people2a", "/people/name/fred/", ["fred"], {}), ("people_backref", "/people/nate-nate/", ["nate"], {}), ("people_backref", "/people/nate-nate/", [], {"name": "nate"}), ("optional", "/optional/fred/", [], {"name": "fred"}), ("optional", "/optional/fred/", ["fred"], {}), ("named_optional", "/optional/1/", [1], {}), ("named_optional", "/optional/1/", [], {"arg1": 1}), ("named_optional", "/optional/1/2/", [1, 2], {}), ("named_optional", "/optional/1/2/", [], {"arg1": 1, "arg2": 2}), ("named_optional_terminated", "/optional/1/", [1], {}), ("named_optional_terminated", "/optional/1/", [], {"arg1": 1}), ("named_optional_terminated", "/optional/1/2/", [1, 2], {}), ("named_optional_terminated", "/optional/1/2/", [], {"arg1": 1, "arg2": 2}), ("hardcoded", "/hardcoded/", [], {}), ("hardcoded2", "/hardcoded/doc.pdf", [], {}), ("people3", "/people/il/adrian/", [], {"state": "il", "name": "adrian"}), ("people3", NoReverseMatch, [], {"state": "il"}), ("people3", NoReverseMatch, [], {"name": "adrian"}), ("people4", NoReverseMatch, [], {"state": "il", "name": "adrian"}), ("people6", "/people/il/test/adrian/", ["il/test", "adrian"], {}), ("people6", "/people//adrian/", ["adrian"], {}), ("range", "/character_set/a/", [], {}), ("range2", "/character_set/x/", [], {}), ("price", "/price/$10/", ["10"], {}), ("price2", "/price/$10/", ["10"], {}), ("price3", "/price/$10/", ["10"], {}), ( "product", "/product/chocolate+($2.00)/", [], {"price": "2.00", "product": "chocolate"}, ), ("headlines", "/headlines/2007.5.21/", [], {"year": 2007, "month": 5, "day": 21}), ( "windows", r"/windows_path/C:%5CDocuments%20and%20Settings%5Cspam/", [], {"drive_name": "C", "path": r"Documents and Settings\spam"}, ), ("special", r"/special_chars/~@+%5C$*%7C/", [r"~@+\$*|"], {}), ("special", r"/special_chars/some%20resource/", [r"some resource"], {}), ("special", r"/special_chars/10%25%20complete/", [r"10% complete"], {}), ("special", r"/special_chars/some%20resource/", [], {"chars": r"some resource"}), ("special", r"/special_chars/10%25%20complete/", [], {"chars": r"10% complete"}), ("special", NoReverseMatch, [""], {}), ("mixed", "/john/0/", [], {"name": "john"}), ("repeats", "/repeats/a/", [], {}), ("repeats2", "/repeats/aa/", [], {}), ("repeats3", "/repeats/aa/", [], {}), ("test", "/test/1", [], {}), ("inner-nothing", "/outer/42/", [], {"outer": "42"}), ("inner-nothing", "/outer/42/", ["42"], {}), ("inner-nothing", NoReverseMatch, ["foo"], {}), ("inner-extra", "/outer/42/extra/inner/", [], {"extra": "inner", "outer": "42"}), ("inner-extra", "/outer/42/extra/inner/", ["42", "inner"], {}), ("inner-extra", NoReverseMatch, ["fred", "inner"], {}), ("inner-no-kwargs", "/outer-no-kwargs/42/inner-no-kwargs/1/", ["42", "1"], {}), ("disjunction", NoReverseMatch, ["foo"], {}), ("inner-disjunction", NoReverseMatch, ["10", "11"], {}), ("extra-places", "/e-places/10/", ["10"], {}), ("extra-people", "/e-people/fred/", ["fred"], {}), ("extra-people", "/e-people/fred/", [], {"name": "fred"}), ("part", "/part/one/", [], {"value": "one"}), ("part", "/prefix/xx/part/one/", [], {"value": "one", "prefix": "xx"}), ("part2", "/part2/one/", [], {"value": "one"}), ("part2", "/part2/", [], {}), ("part2", "/prefix/xx/part2/one/", [], {"value": "one", "prefix": "xx"}), ("part2", "/prefix/xx/part2/", [], {"prefix": "xx"}), # Tests for nested groups. Nested capturing groups will only work if you # *only* supply the correct outer group. ("nested-noncapture", "/nested/noncapture/opt", [], {"p": "opt"}), ("nested-capture", "/nested/capture/opt/", ["opt/"], {}), ("nested-capture", NoReverseMatch, [], {"p": "opt"}), ("nested-mixedcapture", "/nested/capture/mixed/opt", ["opt"], {}), ("nested-mixedcapture", NoReverseMatch, [], {"p": "opt"}), ("nested-namedcapture", "/nested/capture/named/opt/", [], {"outer": "opt/"}), ("nested-namedcapture", NoReverseMatch, [], {"outer": "opt/", "inner": "opt"}), ("nested-namedcapture", NoReverseMatch, [], {"inner": "opt"}), ("non_path_include", "/includes/non_path_include/", [], {}), # Tests for #13154 ("defaults", "/defaults_view1/3/", [], {"arg1": 3, "arg2": 1}), ("defaults", "/defaults_view2/3/", [], {"arg1": 3, "arg2": 2}), ("defaults", NoReverseMatch, [], {"arg1": 3, "arg2": 3}), ("defaults", NoReverseMatch, [], {"arg2": 1}), # Security tests ("security", "/%2Fexample.com/security/", ["/example.com"], {}), ) @override_settings(ROOT_URLCONF="urlpatterns_reverse.no_urls") class NoURLPatternsTests(SimpleTestCase): def test_no_urls_exception(self): """ URLResolver should raise an exception when no urlpatterns exist. """ resolver = URLResolver(RegexPattern(r"^$"), settings.ROOT_URLCONF) with self.assertRaisesMessage( ImproperlyConfigured, "The included URLconf 'urlpatterns_reverse.no_urls' does not " "appear to have any patterns in it. If you see the 'urlpatterns' " "variable with valid patterns in the file then the issue is " "probably caused by a circular import.", ): getattr(resolver, "url_patterns") @override_settings(ROOT_URLCONF="urlpatterns_reverse.urls") class URLPatternReverse(SimpleTestCase): def test_urlpattern_reverse(self): for name, expected, args, kwargs in test_data: with self.subTest(name=name, args=args, kwargs=kwargs): try: got = reverse(name, args=args, kwargs=kwargs) except NoReverseMatch: self.assertEqual(NoReverseMatch, expected) else: self.assertEqual(got, expected) def test_reverse_none(self): # Reversing None should raise an error, not return the last un-named view. with self.assertRaises(NoReverseMatch): reverse(None) def test_mixing_args_and_kwargs(self): msg = "Don't mix *args and **kwargs in call to reverse()!" with self.assertRaisesMessage(ValueError, msg): reverse("name", args=["a"], kwargs={"b": "c"}) @override_script_prefix("/{{invalid}}/") def test_prefix_braces(self): self.assertEqual( "/%7B%7Binvalid%7D%7D/includes/non_path_include/", reverse("non_path_include"), ) def test_prefix_parenthesis(self): # Parentheses are allowed and should not cause errors or be escaped with override_script_prefix("/bogus)/"): self.assertEqual( "/bogus)/includes/non_path_include/", reverse("non_path_include") ) with override_script_prefix("/(bogus)/"): self.assertEqual( "/(bogus)/includes/non_path_include/", reverse("non_path_include") ) @override_script_prefix("/bump%20map/") def test_prefix_format_char(self): self.assertEqual( "/bump%2520map/includes/non_path_include/", reverse("non_path_include") ) @override_script_prefix("/%7Eme/") def test_non_urlsafe_prefix_with_args(self): # Regression for #20022, adjusted for #24013 because ~ is an unreserved # character. Tests whether % is escaped. self.assertEqual("/%257Eme/places/1/", reverse("places", args=[1])) def test_patterns_reported(self): # Regression for #17076 with self.assertRaisesMessage( NoReverseMatch, r"1 pattern(s) tried: ['people/(?P<name>\\w+)/$']" ): # this url exists, but requires an argument reverse("people", args=[]) @override_script_prefix("/script:name/") def test_script_name_escaping(self): self.assertEqual( reverse("optional", args=["foo:bar"]), "/script:name/optional/foo:bar/" ) def test_view_not_found_message(self): msg = ( "Reverse for 'nonexistent-view' not found. 'nonexistent-view' " "is not a valid view function or pattern name." ) with self.assertRaisesMessage(NoReverseMatch, msg): reverse("nonexistent-view") def test_no_args_message(self): msg = "Reverse for 'places' with no arguments not found. 1 pattern(s) tried:" with self.assertRaisesMessage(NoReverseMatch, msg): reverse("places") def test_illegal_args_message(self): msg = ( "Reverse for 'places' with arguments '(1, 2)' not found. 1 pattern(s) " "tried:" ) with self.assertRaisesMessage(NoReverseMatch, msg): reverse("places", args=(1, 2)) def test_illegal_kwargs_message(self): msg = ( "Reverse for 'places' with keyword arguments '{'arg1': 2}' not found. 1 " "pattern(s) tried:" ) with self.assertRaisesMessage(NoReverseMatch, msg): reverse("places", kwargs={"arg1": 2}) class ResolverTests(SimpleTestCase): def test_resolver_repr(self): """ Test repr of URLResolver, especially when urlconf_name is a list (#17892). """ # Pick a resolver from a namespaced URLconf resolver = get_resolver("urlpatterns_reverse.namespace_urls") sub_resolver = resolver.namespace_dict["test-ns1"][1] self.assertIn("<URLPattern list>", repr(sub_resolver)) def test_reverse_lazy_object_coercion_by_resolve(self): """ Verifies lazy object returned by reverse_lazy is coerced to text by resolve(). Previous to #21043, this would raise a TypeError. """ urls = "urlpatterns_reverse.named_urls" proxy_url = reverse_lazy("named-url1", urlconf=urls) resolver = get_resolver(urls) resolver.resolve(proxy_url) def test_resolver_reverse(self): resolver = get_resolver("urlpatterns_reverse.named_urls") test_urls = [ # (name, args, kwargs, expected) ("named-url1", (), {}, ""), ("named-url2", ("arg",), {}, "extra/arg/"), ("named-url2", (), {"extra": "arg"}, "extra/arg/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(resolver.reverse(name, *args, **kwargs), expected) def test_resolver_reverse_conflict(self): """ URL pattern name arguments don't need to be unique. The last registered pattern takes precedence for conflicting names. """ resolver = get_resolver("urlpatterns_reverse.named_urls_conflict") test_urls = [ # (name, args, kwargs, expected) # Without arguments, the last URL in urlpatterns has precedence. ("name-conflict", (), {}, "conflict/"), # With an arg, the last URL in urlpatterns has precedence. ("name-conflict", ("arg",), {}, "conflict-last/arg/"), # With a kwarg, other URL patterns can be reversed. ("name-conflict", (), {"first": "arg"}, "conflict-first/arg/"), ("name-conflict", (), {"middle": "arg"}, "conflict-middle/arg/"), ("name-conflict", (), {"last": "arg"}, "conflict-last/arg/"), # The number and order of the arguments don't interfere with reversing. ("name-conflict", ("arg", "arg"), {}, "conflict/arg/arg/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(resolver.reverse(name, *args, **kwargs), expected) def test_non_regex(self): """ A Resolver404 is raised if resolving doesn't meet the basic requirements of a path to match - i.e., at the very least, it matches the root pattern '^/'. Never return None from resolve() to prevent a TypeError from occurring later (#10834). """ test_urls = ["", "a", "\\", "."] for path_ in test_urls: with self.subTest(path=path_): with self.assertRaises(Resolver404): resolve(path_) def test_404_tried_urls_have_names(self): """ The list of URLs that come back from a Resolver404 exception contains a list in the right format for printing out in the DEBUG 404 page with both the patterns and URL names, if available. """ urls = "urlpatterns_reverse.named_urls" # this list matches the expected URL types and names returned when # you try to resolve a nonexistent URL in the first level of included # URLs in named_urls.py (e.g., '/included/nonexistent-url') url_types_names = [ [{"type": URLPattern, "name": "named-url1"}], [{"type": URLPattern, "name": "named-url2"}], [{"type": URLPattern, "name": None}], [{"type": URLResolver}, {"type": URLPattern, "name": "named-url3"}], [{"type": URLResolver}, {"type": URLPattern, "name": "named-url4"}], [{"type": URLResolver}, {"type": URLPattern, "name": None}], [{"type": URLResolver}, {"type": URLResolver}], ] with self.assertRaisesMessage(Resolver404, "tried") as cm: resolve("/included/nonexistent-url", urlconf=urls) e = cm.exception # make sure we at least matched the root ('/') url resolver: self.assertIn("tried", e.args[0]) self.assertEqual( len(e.args[0]["tried"]), len(url_types_names), "Wrong number of tried URLs returned. Expected %s, got %s." % (len(url_types_names), len(e.args[0]["tried"])), ) for tried, expected in zip(e.args[0]["tried"], url_types_names): for t, e in zip(tried, expected): with self.subTest(t): self.assertIsInstance( t, e["type"] ), "%s is not an instance of %s" % (t, e["type"]) if "name" in e: if not e["name"]: self.assertIsNone( t.name, "Expected no URL name but found %s." % t.name ) else: self.assertEqual( t.name, e["name"], 'Wrong URL name. Expected "%s", got "%s".' % (e["name"], t.name), ) def test_populate_concurrency(self): """ URLResolver._populate() can be called concurrently, but not more than once per thread (#26888). """ resolver = URLResolver(RegexPattern(r"^/"), "urlpatterns_reverse.urls") resolver._local.populating = True thread = threading.Thread(target=resolver._populate) thread.start() thread.join() self.assertNotEqual(resolver._reverse_dict, {}) @override_settings(ROOT_URLCONF="urlpatterns_reverse.reverse_lazy_urls") class ReverseLazyTest(TestCase): def test_redirect_with_lazy_reverse(self): response = self.client.get("/redirect/") self.assertRedirects(response, "/redirected_to/", status_code=302) def test_user_permission_with_lazy_reverse(self): alfred = User.objects.create_user( "alfred", "[email protected]", password="testpw" ) response = self.client.get("/login_required_view/") self.assertRedirects( response, "/login/?next=/login_required_view/", status_code=302 ) self.client.force_login(alfred) response = self.client.get("/login_required_view/") self.assertEqual(response.status_code, 200) def test_inserting_reverse_lazy_into_string(self): self.assertEqual( "Some URL: %s" % reverse_lazy("some-login-page"), "Some URL: /login/" ) def test_build_absolute_uri(self): factory = RequestFactory() request = factory.get("/") self.assertEqual( request.build_absolute_uri(reverse_lazy("some-login-page")), "http://testserver/login/", ) class ReverseLazySettingsTest(AdminScriptTestCase): """ reverse_lazy can be used in settings without causing a circular import error. """ def setUp(self): super().setUp() self.write_settings( "settings.py", extra=( "from django.urls import reverse_lazy\n" "LOGIN_URL = reverse_lazy('login')" ), ) def test_lazy_in_settings(self): out, err = self.run_manage(["check"]) self.assertNoOutput(err) @override_settings(ROOT_URLCONF="urlpatterns_reverse.urls") class ReverseShortcutTests(SimpleTestCase): def test_redirect_to_object(self): # We don't really need a model; just something with a get_absolute_url class FakeObj: def get_absolute_url(self): return "/hi-there/" res = redirect(FakeObj()) self.assertIsInstance(res, HttpResponseRedirect) self.assertEqual(res.url, "/hi-there/") res = redirect(FakeObj(), permanent=True) self.assertIsInstance(res, HttpResponsePermanentRedirect) self.assertEqual(res.url, "/hi-there/") def test_redirect_to_view_name(self): res = redirect("hardcoded2") self.assertEqual(res.url, "/hardcoded/doc.pdf") res = redirect("places", 1) self.assertEqual(res.url, "/places/1/") res = redirect("headlines", year="2008", month="02", day="17") self.assertEqual(res.url, "/headlines/2008.02.17/") with self.assertRaises(NoReverseMatch): redirect("not-a-view") def test_redirect_to_url(self): res = redirect("/foo/") self.assertEqual(res.url, "/foo/") res = redirect("http://example.com/") self.assertEqual(res.url, "http://example.com/") # Assert that we can redirect using UTF-8 strings res = redirect("/æøå/abc/") self.assertEqual(res.url, "/%C3%A6%C3%B8%C3%A5/abc/") # Assert that no imports are attempted when dealing with a relative path # (previously, the below would resolve in a UnicodeEncodeError from __import__ ) res = redirect("/æøå.abc/") self.assertEqual(res.url, "/%C3%A6%C3%B8%C3%A5.abc/") res = redirect("os.path") self.assertEqual(res.url, "os.path") def test_no_illegal_imports(self): # modules that are not listed in urlpatterns should not be importable redirect("urlpatterns_reverse.nonimported_module.view") self.assertNotIn("urlpatterns_reverse.nonimported_module", sys.modules) def test_reverse_by_path_nested(self): # Views added to urlpatterns using include() should be reversible. from .views import nested_view self.assertEqual(reverse(nested_view), "/includes/nested_path/") def test_redirect_view_object(self): from .views import absolute_kwargs_view res = redirect(absolute_kwargs_view) self.assertEqual(res.url, "/absolute_arg_view/") with self.assertRaises(NoReverseMatch): redirect(absolute_kwargs_view, wrong_argument=None) @override_settings(ROOT_URLCONF="urlpatterns_reverse.namespace_urls") class NamespaceTests(SimpleTestCase): def test_ambiguous_object(self): """ Names deployed via dynamic URL objects that require namespaces can't be resolved. """ test_urls = [ ("urlobject-view", [], {}), ("urlobject-view", [37, 42], {}), ("urlobject-view", [], {"arg1": 42, "arg2": 37}), ] for name, args, kwargs in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): with self.assertRaises(NoReverseMatch): reverse(name, args=args, kwargs=kwargs) def test_ambiguous_urlpattern(self): """ Names deployed via dynamic URL objects that require namespaces can't be resolved. """ test_urls = [ ("inner-nothing", [], {}), ("inner-nothing", [37, 42], {}), ("inner-nothing", [], {"arg1": 42, "arg2": 37}), ] for name, args, kwargs in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): with self.assertRaises(NoReverseMatch): reverse(name, args=args, kwargs=kwargs) def test_non_existent_namespace(self): """Nonexistent namespaces raise errors.""" test_urls = [ "blahblah:urlobject-view", "test-ns1:blahblah:urlobject-view", ] for name in test_urls: with self.subTest(name=name): with self.assertRaises(NoReverseMatch): reverse(name) def test_normal_name(self): """Normal lookups work as expected.""" test_urls = [ ("normal-view", [], {}, "/normal/"), ("normal-view", [37, 42], {}, "/normal/37/42/"), ("normal-view", [], {"arg1": 42, "arg2": 37}, "/normal/42/37/"), ("special-view", [], {}, "/+%5C$*/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_simple_included_name(self): """Normal lookups work on names included from other patterns.""" test_urls = [ ("included_namespace_urls:inc-normal-view", [], {}, "/included/normal/"), ( "included_namespace_urls:inc-normal-view", [37, 42], {}, "/included/normal/37/42/", ), ( "included_namespace_urls:inc-normal-view", [], {"arg1": 42, "arg2": 37}, "/included/normal/42/37/", ), ("included_namespace_urls:inc-special-view", [], {}, "/included/+%5C$*/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_namespace_object(self): """Dynamic URL objects can be found using a namespace.""" test_urls = [ ("test-ns1:urlobject-view", [], {}, "/test1/inner/"), ("test-ns1:urlobject-view", [37, 42], {}, "/test1/inner/37/42/"), ( "test-ns1:urlobject-view", [], {"arg1": 42, "arg2": 37}, "/test1/inner/42/37/", ), ("test-ns1:urlobject-special-view", [], {}, "/test1/inner/+%5C$*/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_app_object(self): """ Dynamic URL objects can return a (pattern, app_name) 2-tuple, and include() can set the namespace. """ test_urls = [ ("new-ns1:urlobject-view", [], {}, "/newapp1/inner/"), ("new-ns1:urlobject-view", [37, 42], {}, "/newapp1/inner/37/42/"), ( "new-ns1:urlobject-view", [], {"arg1": 42, "arg2": 37}, "/newapp1/inner/42/37/", ), ("new-ns1:urlobject-special-view", [], {}, "/newapp1/inner/+%5C$*/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_app_object_default_namespace(self): """ Namespace defaults to app_name when including a (pattern, app_name) 2-tuple. """ test_urls = [ ("newapp:urlobject-view", [], {}, "/new-default/inner/"), ("newapp:urlobject-view", [37, 42], {}, "/new-default/inner/37/42/"), ( "newapp:urlobject-view", [], {"arg1": 42, "arg2": 37}, "/new-default/inner/42/37/", ), ("newapp:urlobject-special-view", [], {}, "/new-default/inner/+%5C$*/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_embedded_namespace_object(self): """Namespaces can be installed anywhere in the URL pattern tree.""" test_urls = [ ( "included_namespace_urls:test-ns3:urlobject-view", [], {}, "/included/test3/inner/", ), ( "included_namespace_urls:test-ns3:urlobject-view", [37, 42], {}, "/included/test3/inner/37/42/", ), ( "included_namespace_urls:test-ns3:urlobject-view", [], {"arg1": 42, "arg2": 37}, "/included/test3/inner/42/37/", ), ( "included_namespace_urls:test-ns3:urlobject-special-view", [], {}, "/included/test3/inner/+%5C$*/", ), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_namespace_pattern(self): """Namespaces can be applied to include()'d urlpatterns.""" test_urls = [ ("inc-ns1:inc-normal-view", [], {}, "/ns-included1/normal/"), ("inc-ns1:inc-normal-view", [37, 42], {}, "/ns-included1/normal/37/42/"), ( "inc-ns1:inc-normal-view", [], {"arg1": 42, "arg2": 37}, "/ns-included1/normal/42/37/", ), ("inc-ns1:inc-special-view", [], {}, "/ns-included1/+%5C$*/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_app_name_pattern(self): """ Namespaces can be applied to include()'d urlpatterns that set an app_name attribute. """ test_urls = [ ("app-ns1:inc-normal-view", [], {}, "/app-included1/normal/"), ("app-ns1:inc-normal-view", [37, 42], {}, "/app-included1/normal/37/42/"), ( "app-ns1:inc-normal-view", [], {"arg1": 42, "arg2": 37}, "/app-included1/normal/42/37/", ), ("app-ns1:inc-special-view", [], {}, "/app-included1/+%5C$*/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_namespace_pattern_with_variable_prefix(self): """ Using include() with namespaces when there is a regex variable in front of it. """ test_urls = [ ("inc-outer:inc-normal-view", [], {"outer": 42}, "/ns-outer/42/normal/"), ("inc-outer:inc-normal-view", [42], {}, "/ns-outer/42/normal/"), ( "inc-outer:inc-normal-view", [], {"arg1": 37, "arg2": 4, "outer": 42}, "/ns-outer/42/normal/37/4/", ), ("inc-outer:inc-normal-view", [42, 37, 4], {}, "/ns-outer/42/normal/37/4/"), ("inc-outer:inc-special-view", [], {"outer": 42}, "/ns-outer/42/+%5C$*/"), ("inc-outer:inc-special-view", [42], {}, "/ns-outer/42/+%5C$*/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_multiple_namespace_pattern(self): """Namespaces can be embedded.""" test_urls = [ ("inc-ns1:test-ns3:urlobject-view", [], {}, "/ns-included1/test3/inner/"), ( "inc-ns1:test-ns3:urlobject-view", [37, 42], {}, "/ns-included1/test3/inner/37/42/", ), ( "inc-ns1:test-ns3:urlobject-view", [], {"arg1": 42, "arg2": 37}, "/ns-included1/test3/inner/42/37/", ), ( "inc-ns1:test-ns3:urlobject-special-view", [], {}, "/ns-included1/test3/inner/+%5C$*/", ), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_nested_namespace_pattern(self): """Namespaces can be nested.""" test_urls = [ ( "inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view", [], {}, "/ns-included1/ns-included4/ns-included1/test3/inner/", ), ( "inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view", [37, 42], {}, "/ns-included1/ns-included4/ns-included1/test3/inner/37/42/", ), ( "inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view", [], {"arg1": 42, "arg2": 37}, "/ns-included1/ns-included4/ns-included1/test3/inner/42/37/", ), ( "inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-special-view", [], {}, "/ns-included1/ns-included4/ns-included1/test3/inner/+%5C$*/", ), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_app_lookup_object(self): """A default application namespace can be used for lookup.""" test_urls = [ ("testapp:urlobject-view", [], {}, "/default/inner/"), ("testapp:urlobject-view", [37, 42], {}, "/default/inner/37/42/"), ( "testapp:urlobject-view", [], {"arg1": 42, "arg2": 37}, "/default/inner/42/37/", ), ("testapp:urlobject-special-view", [], {}, "/default/inner/+%5C$*/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_app_lookup_object_with_default(self): """A default application namespace is sensitive to the current app.""" test_urls = [ ("testapp:urlobject-view", [], {}, "test-ns3", "/default/inner/"), ( "testapp:urlobject-view", [37, 42], {}, "test-ns3", "/default/inner/37/42/", ), ( "testapp:urlobject-view", [], {"arg1": 42, "arg2": 37}, "test-ns3", "/default/inner/42/37/", ), ( "testapp:urlobject-special-view", [], {}, "test-ns3", "/default/inner/+%5C$*/", ), ] for name, args, kwargs, current_app, expected in test_urls: with self.subTest( name=name, args=args, kwargs=kwargs, current_app=current_app ): self.assertEqual( reverse(name, args=args, kwargs=kwargs, current_app=current_app), expected, ) def test_app_lookup_object_without_default(self): """ An application namespace without a default is sensitive to the current app. """ test_urls = [ ("nodefault:urlobject-view", [], {}, None, "/other2/inner/"), ("nodefault:urlobject-view", [37, 42], {}, None, "/other2/inner/37/42/"), ( "nodefault:urlobject-view", [], {"arg1": 42, "arg2": 37}, None, "/other2/inner/42/37/", ), ("nodefault:urlobject-special-view", [], {}, None, "/other2/inner/+%5C$*/"), ("nodefault:urlobject-view", [], {}, "other-ns1", "/other1/inner/"), ( "nodefault:urlobject-view", [37, 42], {}, "other-ns1", "/other1/inner/37/42/", ), ( "nodefault:urlobject-view", [], {"arg1": 42, "arg2": 37}, "other-ns1", "/other1/inner/42/37/", ), ( "nodefault:urlobject-special-view", [], {}, "other-ns1", "/other1/inner/+%5C$*/", ), ] for name, args, kwargs, current_app, expected in test_urls: with self.subTest( name=name, args=args, kwargs=kwargs, current_app=current_app ): self.assertEqual( reverse(name, args=args, kwargs=kwargs, current_app=current_app), expected, ) def test_special_chars_namespace(self): test_urls = [ ( "special:included_namespace_urls:inc-normal-view", [], {}, "/+%5C$*/included/normal/", ), ( "special:included_namespace_urls:inc-normal-view", [37, 42], {}, "/+%5C$*/included/normal/37/42/", ), ( "special:included_namespace_urls:inc-normal-view", [], {"arg1": 42, "arg2": 37}, "/+%5C$*/included/normal/42/37/", ), ( "special:included_namespace_urls:inc-special-view", [], {}, "/+%5C$*/included/+%5C$*/", ), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_namespaces_with_variables(self): """Namespace prefixes can capture variables.""" test_urls = [ ("inc-ns5:inner-nothing", [], {"outer": "70"}, "/inc70/"), ( "inc-ns5:inner-extra", [], {"extra": "foobar", "outer": "78"}, "/inc78/extra/foobar/", ), ("inc-ns5:inner-nothing", ["70"], {}, "/inc70/"), ("inc-ns5:inner-extra", ["78", "foobar"], {}, "/inc78/extra/foobar/"), ] for name, args, kwargs, expected in test_urls: with self.subTest(name=name, args=args, kwargs=kwargs): self.assertEqual(reverse(name, args=args, kwargs=kwargs), expected) def test_nested_app_lookup(self): """ A nested current_app should be split in individual namespaces (#24904). """ test_urls = [ ( "inc-ns1:testapp:urlobject-view", [], {}, None, "/ns-included1/test4/inner/", ), ( "inc-ns1:testapp:urlobject-view", [37, 42], {}, None, "/ns-included1/test4/inner/37/42/", ), ( "inc-ns1:testapp:urlobject-view", [], {"arg1": 42, "arg2": 37}, None, "/ns-included1/test4/inner/42/37/", ), ( "inc-ns1:testapp:urlobject-special-view", [], {}, None, "/ns-included1/test4/inner/+%5C$*/", ), ( "inc-ns1:testapp:urlobject-view", [], {}, "inc-ns1:test-ns3", "/ns-included1/test3/inner/", ), ( "inc-ns1:testapp:urlobject-view", [37, 42], {}, "inc-ns1:test-ns3", "/ns-included1/test3/inner/37/42/", ), ( "inc-ns1:testapp:urlobject-view", [], {"arg1": 42, "arg2": 37}, "inc-ns1:test-ns3", "/ns-included1/test3/inner/42/37/", ), ( "inc-ns1:testapp:urlobject-special-view", [], {}, "inc-ns1:test-ns3", "/ns-included1/test3/inner/+%5C$*/", ), ] for name, args, kwargs, current_app, expected in test_urls: with self.subTest( name=name, args=args, kwargs=kwargs, current_app=current_app ): self.assertEqual( reverse(name, args=args, kwargs=kwargs, current_app=current_app), expected, ) def test_current_app_no_partial_match(self): """current_app shouldn't be used unless it matches the whole path.""" test_urls = [ ( "inc-ns1:testapp:urlobject-view", [], {}, "nonexistent:test-ns3", "/ns-included1/test4/inner/", ), ( "inc-ns1:testapp:urlobject-view", [37, 42], {}, "nonexistent:test-ns3", "/ns-included1/test4/inner/37/42/", ), ( "inc-ns1:testapp:urlobject-view", [], {"arg1": 42, "arg2": 37}, "nonexistent:test-ns3", "/ns-included1/test4/inner/42/37/", ), ( "inc-ns1:testapp:urlobject-special-view", [], {}, "nonexistent:test-ns3", "/ns-included1/test4/inner/+%5C$*/", ), ] for name, args, kwargs, current_app, expected in test_urls: with self.subTest( name=name, args=args, kwargs=kwargs, current_app=current_app ): self.assertEqual( reverse(name, args=args, kwargs=kwargs, current_app=current_app), expected, ) @override_settings(ROOT_URLCONF=urlconf_outer.__name__) class RequestURLconfTests(SimpleTestCase): def test_urlconf(self): response = self.client.get("/test/me/") self.assertEqual(response.status_code, 200) self.assertEqual( response.content, b"outer:/test/me/,inner:/inner_urlconf/second_test/" ) response = self.client.get("/inner_urlconf/second_test/") self.assertEqual(response.status_code, 200) response = self.client.get("/second_test/") self.assertEqual(response.status_code, 404) @override_settings( MIDDLEWARE=[ "%s.ChangeURLconfMiddleware" % middleware.__name__, ] ) def test_urlconf_overridden(self): response = self.client.get("/test/me/") self.assertEqual(response.status_code, 404) response = self.client.get("/inner_urlconf/second_test/") self.assertEqual(response.status_code, 404) response = self.client.get("/second_test/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"outer:,inner:/second_test/") @override_settings( MIDDLEWARE=[ "%s.NullChangeURLconfMiddleware" % middleware.__name__, ] ) def test_urlconf_overridden_with_null(self): """ Overriding request.urlconf with None will fall back to the default URLconf. """ response = self.client.get("/test/me/") self.assertEqual(response.status_code, 200) self.assertEqual( response.content, b"outer:/test/me/,inner:/inner_urlconf/second_test/" ) response = self.client.get("/inner_urlconf/second_test/") self.assertEqual(response.status_code, 200) response = self.client.get("/second_test/") self.assertEqual(response.status_code, 404) @override_settings( MIDDLEWARE=[ "%s.ChangeURLconfMiddleware" % middleware.__name__, "%s.ReverseInnerInResponseMiddleware" % middleware.__name__, ] ) def test_reverse_inner_in_response_middleware(self): """ Test reversing an URL from the *overridden* URLconf from inside a response middleware. """ response = self.client.get("/second_test/") self.assertEqual(response.status_code, 200) self.assertEqual(response.content, b"/second_test/") @override_settings( MIDDLEWARE=[ "%s.ChangeURLconfMiddleware" % middleware.__name__, "%s.ReverseOuterInResponseMiddleware" % middleware.__name__, ] ) def test_reverse_outer_in_response_middleware(self): """ Test reversing an URL from the *default* URLconf from inside a response middleware. """ msg = ( "Reverse for 'outer' not found. 'outer' is not a valid view " "function or pattern name." ) with self.assertRaisesMessage(NoReverseMatch, msg): self.client.get("/second_test/") @override_settings( MIDDLEWARE=[ "%s.ChangeURLconfMiddleware" % middleware.__name__, "%s.ReverseInnerInStreaming" % middleware.__name__, ] ) def test_reverse_inner_in_streaming(self): """ Test reversing an URL from the *overridden* URLconf from inside a streaming response. """ response = self.client.get("/second_test/") self.assertEqual(response.status_code, 200) self.assertEqual(b"".join(response), b"/second_test/") @override_settings( MIDDLEWARE=[ "%s.ChangeURLconfMiddleware" % middleware.__name__, "%s.ReverseOuterInStreaming" % middleware.__name__, ] ) def test_reverse_outer_in_streaming(self): """ Test reversing an URL from the *default* URLconf from inside a streaming response. """ message = "Reverse for 'outer' not found." with self.assertRaisesMessage(NoReverseMatch, message): self.client.get("/second_test/") b"".join(self.client.get("/second_test/")) def test_urlconf_is_reset_after_request(self): """The URLconf is reset after each request.""" self.assertIsNone(get_urlconf()) with override_settings( MIDDLEWARE=["%s.ChangeURLconfMiddleware" % middleware.__name__] ): self.client.get(reverse("inner")) self.assertIsNone(get_urlconf()) class ErrorHandlerResolutionTests(SimpleTestCase): """Tests for handler400, handler404 and handler500""" def setUp(self): urlconf = "urlpatterns_reverse.urls_error_handlers" urlconf_callables = "urlpatterns_reverse.urls_error_handlers_callables" self.resolver = URLResolver(RegexPattern(r"^$"), urlconf) self.callable_resolver = URLResolver(RegexPattern(r"^$"), urlconf_callables) def test_named_handlers(self): for code in [400, 404, 500]: with self.subTest(code=code): self.assertEqual(self.resolver.resolve_error_handler(code), empty_view) def test_callable_handlers(self): for code in [400, 404, 500]: with self.subTest(code=code): self.assertEqual( self.callable_resolver.resolve_error_handler(code), empty_view ) @override_settings(ROOT_URLCONF="urlpatterns_reverse.urls_without_handlers") class DefaultErrorHandlerTests(SimpleTestCase): def test_default_handler(self): "If the urls.py doesn't specify handlers, the defaults are used" response = self.client.get("/test/") self.assertEqual(response.status_code, 404) msg = "I don't think I'm getting good value for this view" with self.assertRaisesMessage(ValueError, msg): self.client.get("/bad_view/") @override_settings(ROOT_URLCONF=None) class NoRootUrlConfTests(SimpleTestCase): """Tests for handler404 and handler500 if ROOT_URLCONF is None""" def test_no_handler_exception(self): msg = ( "The included URLconf 'None' does not appear to have any patterns " "in it. If you see the 'urlpatterns' variable with valid patterns " "in the file then the issue is probably caused by a circular " "import." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get("/test/me/") @override_settings(ROOT_URLCONF="urlpatterns_reverse.namespace_urls") class ResolverMatchTests(SimpleTestCase): def test_urlpattern_resolve(self): for ( path_, url_name, app_name, namespace, view_name, func, args, kwargs, ) in resolve_test_data: with self.subTest(path=path_): # Legacy support for extracting "function, args, kwargs". match_func, match_args, match_kwargs = resolve(path_) self.assertEqual(match_func, func) self.assertEqual(match_args, args) self.assertEqual(match_kwargs, kwargs) # ResolverMatch capabilities. match = resolve(path_) self.assertEqual(match.__class__, ResolverMatch) self.assertEqual(match.url_name, url_name) self.assertEqual(match.app_name, app_name) self.assertEqual(match.namespace, namespace) self.assertEqual(match.view_name, view_name) self.assertEqual(match.func, func) self.assertEqual(match.args, args) self.assertEqual(match.kwargs, kwargs) # and for legacy purposes: self.assertEqual(match[0], func) self.assertEqual(match[1], args) self.assertEqual(match[2], kwargs) def test_resolver_match_on_request(self): response = self.client.get("/resolver_match/") resolver_match = response.resolver_match self.assertEqual(resolver_match.url_name, "test-resolver-match") def test_resolver_match_on_request_before_resolution(self): request = HttpRequest() self.assertIsNone(request.resolver_match) def test_repr(self): self.assertEqual( repr(resolve("/no_kwargs/42/37/")), "ResolverMatch(func=urlpatterns_reverse.views.empty_view, " "args=('42', '37'), kwargs={}, url_name='no-kwargs', app_names=[], " "namespaces=[], route='^no_kwargs/([0-9]+)/([0-9]+)/$')", ) def test_repr_extra_kwargs(self): self.assertEqual( repr(resolve("/mixed_args/1986/11/")), "ResolverMatch(func=urlpatterns_reverse.views.empty_view, args=(), " "kwargs={'arg2': '11', 'extra': True}, url_name='mixed-args', " "app_names=[], namespaces=[], " "route='^mixed_args/([0-9]+)/(?P<arg2>[0-9]+)/$', " "captured_kwargs={'arg2': '11'}, extra_kwargs={'extra': True})", ) @override_settings(ROOT_URLCONF="urlpatterns_reverse.reverse_lazy_urls") def test_classbased_repr(self): self.assertEqual( repr(resolve("/redirect/")), "ResolverMatch(func=urlpatterns_reverse.views.LazyRedirectView, " "args=(), kwargs={}, url_name=None, app_names=[], " "namespaces=[], route='redirect/')", ) @override_settings(ROOT_URLCONF="urlpatterns_reverse.urls") def test_repr_functools_partial(self): tests = [ ("partial", "template.html"), ("partial_nested", "nested_partial.html"), ("partial_wrapped", "template.html"), ] for name, template_name in tests: with self.subTest(name=name): func = ( f"functools.partial({views.empty_view!r}, " f"template_name='{template_name}')" ) self.assertEqual( repr(resolve(f"/{name}/")), f"ResolverMatch(func={func}, args=(), kwargs={{}}, " f"url_name='{name}', app_names=[], namespaces=[], " f"route='{name}/')", ) @override_settings(ROOT_URLCONF="urlpatterns.path_urls") def test_pickling(self): msg = "Cannot pickle ResolverMatch." with self.assertRaisesMessage(pickle.PicklingError, msg): pickle.dumps(resolve("/users/")) @override_settings(ROOT_URLCONF="urlpatterns_reverse.erroneous_urls") class ErroneousViewTests(SimpleTestCase): def test_noncallable_view(self): # View is not a callable (explicit import; arbitrary Python object) with self.assertRaisesMessage(TypeError, "view must be a callable"): path("uncallable-object/", views.uncallable) def test_invalid_regex(self): # Regex contains an error (refs #6170) msg = '(regex_error/$" is not a valid regular expression' with self.assertRaisesMessage(ImproperlyConfigured, msg): reverse(views.empty_view) class ViewLoadingTests(SimpleTestCase): def test_view_loading(self): self.assertEqual( get_callable("urlpatterns_reverse.views.empty_view"), empty_view ) self.assertEqual(get_callable(empty_view), empty_view) def test_view_does_not_exist(self): msg = "View does not exist in module urlpatterns_reverse.views." with self.assertRaisesMessage(ViewDoesNotExist, msg): get_callable("urlpatterns_reverse.views.i_should_not_exist") def test_attributeerror_not_hidden(self): msg = "I am here to confuse django.urls.get_callable" with self.assertRaisesMessage(AttributeError, msg): get_callable("urlpatterns_reverse.views_broken.i_am_broken") def test_non_string_value(self): msg = "'1' is not a callable or a dot-notation path" with self.assertRaisesMessage(ViewDoesNotExist, msg): get_callable(1) def test_string_without_dot(self): msg = "Could not import 'test'. The path must be fully qualified." with self.assertRaisesMessage(ImportError, msg): get_callable("test") def test_module_does_not_exist(self): with self.assertRaisesMessage(ImportError, "No module named 'foo'"): get_callable("foo.bar") def test_parent_module_does_not_exist(self): msg = "Parent module urlpatterns_reverse.foo does not exist." with self.assertRaisesMessage(ViewDoesNotExist, msg): get_callable("urlpatterns_reverse.foo.bar") def test_not_callable(self): msg = ( "Could not import 'urlpatterns_reverse.tests.resolve_test_data'. " "View is not callable." ) with self.assertRaisesMessage(ViewDoesNotExist, msg): get_callable("urlpatterns_reverse.tests.resolve_test_data") class IncludeTests(SimpleTestCase): url_patterns = [ path("inner/", views.empty_view, name="urlobject-view"), re_path( r"^inner/(?P<arg1>[0-9]+)/(?P<arg2>[0-9]+)/$", views.empty_view, name="urlobject-view", ), re_path(r"^inner/\+\\\$\*/$", views.empty_view, name="urlobject-special-view"), ] app_urls = URLObject("inc-app") def test_include_urls(self): self.assertEqual(include(self.url_patterns), (self.url_patterns, None, None)) def test_include_namespace(self): msg = ( "Specifying a namespace in include() without providing an " "app_name is not supported." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): include(self.url_patterns, "namespace") def test_include_4_tuple(self): msg = "Passing a 4-tuple to include() is not supported." with self.assertRaisesMessage(ImproperlyConfigured, msg): include((self.url_patterns, "app_name", "namespace", "blah")) def test_include_3_tuple(self): msg = "Passing a 3-tuple to include() is not supported." with self.assertRaisesMessage(ImproperlyConfigured, msg): include((self.url_patterns, "app_name", "namespace")) def test_include_3_tuple_namespace(self): msg = ( "Cannot override the namespace for a dynamic module that provides a " "namespace." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): include((self.url_patterns, "app_name", "namespace"), "namespace") def test_include_2_tuple(self): self.assertEqual( include((self.url_patterns, "app_name")), (self.url_patterns, "app_name", "app_name"), ) def test_include_2_tuple_namespace(self): self.assertEqual( include((self.url_patterns, "app_name"), namespace="namespace"), (self.url_patterns, "app_name", "namespace"), ) def test_include_app_name(self): self.assertEqual(include(self.app_urls), (self.app_urls, "inc-app", "inc-app")) def test_include_app_name_namespace(self): self.assertEqual( include(self.app_urls, "namespace"), (self.app_urls, "inc-app", "namespace") ) @override_settings(ROOT_URLCONF="urlpatterns_reverse.urls") class LookaheadTests(SimpleTestCase): def test_valid_resolve(self): test_urls = [ "/lookahead-/a-city/", "/lookbehind-/a-city/", "/lookahead+/a-city/", "/lookbehind+/a-city/", ] for test_url in test_urls: with self.subTest(url=test_url): self.assertEqual(resolve(test_url).kwargs, {"city": "a-city"}) def test_invalid_resolve(self): test_urls = [ "/lookahead-/not-a-city/", "/lookbehind-/not-a-city/", "/lookahead+/other-city/", "/lookbehind+/other-city/", ] for test_url in test_urls: with self.subTest(url=test_url): with self.assertRaises(Resolver404): resolve(test_url) def test_valid_reverse(self): test_urls = [ ("lookahead-positive", {"city": "a-city"}, "/lookahead+/a-city/"), ("lookahead-negative", {"city": "a-city"}, "/lookahead-/a-city/"), ("lookbehind-positive", {"city": "a-city"}, "/lookbehind+/a-city/"), ("lookbehind-negative", {"city": "a-city"}, "/lookbehind-/a-city/"), ] for name, kwargs, expected in test_urls: with self.subTest(name=name, kwargs=kwargs): self.assertEqual(reverse(name, kwargs=kwargs), expected) def test_invalid_reverse(self): test_urls = [ ("lookahead-positive", {"city": "other-city"}), ("lookahead-negative", {"city": "not-a-city"}), ("lookbehind-positive", {"city": "other-city"}), ("lookbehind-negative", {"city": "not-a-city"}), ] for name, kwargs in test_urls: with self.subTest(name=name, kwargs=kwargs): with self.assertRaises(NoReverseMatch): reverse(name, kwargs=kwargs) @override_settings(ROOT_URLCONF="urlpatterns_reverse.urls") class ReverseResolvedTests(SimpleTestCase): def test_rereverse(self): match = resolve("/resolved/12/") self.assertEqual( reverse(match.url_name, args=match.args, kwargs=match.kwargs), "/resolved/12/", ) match = resolve("/resolved-overridden/12/url/") self.assertEqual( reverse(match.url_name, args=match.args, kwargs=match.captured_kwargs), "/resolved-overridden/12/url/", )
dadaf3bea9990640ad6546abeb6bf2e9a3068a561251c288861e5a8daa60ed7e
""" Tests for django test runner """ import collections.abc import multiprocessing import os import sys import unittest from unittest import mock from admin_scripts.tests import AdminScriptTestCase from django import db from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.management import call_command from django.core.management.base import SystemCheckError from django.test import SimpleTestCase, TransactionTestCase, skipUnlessDBFeature from django.test.runner import ( DiscoverRunner, Shuffler, _init_worker, reorder_test_bin, reorder_tests, shuffle_tests, ) from django.test.testcases import connections_support_transactions from django.test.utils import ( captured_stderr, dependency_ordered, get_unique_databases_and_mirrors, iter_test_cases, ) from django.utils.deprecation import RemovedInDjango50Warning from .models import B, Person, Through class MySuite: def __init__(self): self.tests = [] def addTest(self, test): self.tests.append(test) def __iter__(self): yield from self.tests class TestSuiteTests(SimpleTestCase): def build_test_suite(self, test_classes, suite=None, suite_class=None): if suite_class is None: suite_class = unittest.TestSuite if suite is None: suite = suite_class() loader = unittest.defaultTestLoader for test_class in test_classes: tests = loader.loadTestsFromTestCase(test_class) subsuite = suite_class() # Only use addTest() to simplify testing a custom TestSuite. for test in tests: subsuite.addTest(test) suite.addTest(subsuite) return suite def make_test_suite(self, suite=None, suite_class=None): class Tests1(unittest.TestCase): def test1(self): pass def test2(self): pass class Tests2(unittest.TestCase): def test1(self): pass def test2(self): pass return self.build_test_suite( (Tests1, Tests2), suite=suite, suite_class=suite_class, ) def assertTestNames(self, tests, expected): # Each test.id() has a form like the following: # "test_runner.tests.IterTestCasesTests.test_iter_test_cases.<locals>.Tests1.test1". # It suffices to check only the last two parts. names = [".".join(test.id().split(".")[-2:]) for test in tests] self.assertEqual(names, expected) def test_iter_test_cases_basic(self): suite = self.make_test_suite() tests = iter_test_cases(suite) self.assertTestNames( tests, expected=[ "Tests1.test1", "Tests1.test2", "Tests2.test1", "Tests2.test2", ], ) def test_iter_test_cases_string_input(self): msg = ( "Test 'a' must be a test case or test suite not string (was found " "in 'abc')." ) with self.assertRaisesMessage(TypeError, msg): list(iter_test_cases("abc")) def test_iter_test_cases_iterable_of_tests(self): class Tests(unittest.TestCase): def test1(self): pass def test2(self): pass tests = list(unittest.defaultTestLoader.loadTestsFromTestCase(Tests)) actual_tests = iter_test_cases(tests) self.assertTestNames( actual_tests, expected=[ "Tests.test1", "Tests.test2", ], ) def test_iter_test_cases_custom_test_suite_class(self): suite = self.make_test_suite(suite_class=MySuite) tests = iter_test_cases(suite) self.assertTestNames( tests, expected=[ "Tests1.test1", "Tests1.test2", "Tests2.test1", "Tests2.test2", ], ) def test_iter_test_cases_mixed_test_suite_classes(self): suite = self.make_test_suite(suite=MySuite()) child_suite = list(suite)[0] self.assertNotIsInstance(child_suite, MySuite) tests = list(iter_test_cases(suite)) self.assertEqual(len(tests), 4) self.assertNotIsInstance(tests[0], unittest.TestSuite) def make_tests(self): """Return an iterable of tests.""" suite = self.make_test_suite() tests = list(iter_test_cases(suite)) return tests def test_shuffle_tests(self): tests = self.make_tests() # Choose a seed that shuffles both the classes and methods. shuffler = Shuffler(seed=9) shuffled_tests = shuffle_tests(tests, shuffler) self.assertIsInstance(shuffled_tests, collections.abc.Iterator) self.assertTestNames( shuffled_tests, expected=[ "Tests2.test1", "Tests2.test2", "Tests1.test2", "Tests1.test1", ], ) def test_reorder_test_bin_no_arguments(self): tests = self.make_tests() reordered_tests = reorder_test_bin(tests) self.assertIsInstance(reordered_tests, collections.abc.Iterator) self.assertTestNames( reordered_tests, expected=[ "Tests1.test1", "Tests1.test2", "Tests2.test1", "Tests2.test2", ], ) def test_reorder_test_bin_reverse(self): tests = self.make_tests() reordered_tests = reorder_test_bin(tests, reverse=True) self.assertIsInstance(reordered_tests, collections.abc.Iterator) self.assertTestNames( reordered_tests, expected=[ "Tests2.test2", "Tests2.test1", "Tests1.test2", "Tests1.test1", ], ) def test_reorder_test_bin_random(self): tests = self.make_tests() # Choose a seed that shuffles both the classes and methods. shuffler = Shuffler(seed=9) reordered_tests = reorder_test_bin(tests, shuffler=shuffler) self.assertIsInstance(reordered_tests, collections.abc.Iterator) self.assertTestNames( reordered_tests, expected=[ "Tests2.test1", "Tests2.test2", "Tests1.test2", "Tests1.test1", ], ) def test_reorder_test_bin_random_and_reverse(self): tests = self.make_tests() # Choose a seed that shuffles both the classes and methods. shuffler = Shuffler(seed=9) reordered_tests = reorder_test_bin(tests, shuffler=shuffler, reverse=True) self.assertIsInstance(reordered_tests, collections.abc.Iterator) self.assertTestNames( reordered_tests, expected=[ "Tests1.test1", "Tests1.test2", "Tests2.test2", "Tests2.test1", ], ) def test_reorder_tests_same_type_consecutive(self): """Tests of the same type are made consecutive.""" tests = self.make_tests() # Move the last item to the front. tests.insert(0, tests.pop()) self.assertTestNames( tests, expected=[ "Tests2.test2", "Tests1.test1", "Tests1.test2", "Tests2.test1", ], ) reordered_tests = reorder_tests(tests, classes=[]) self.assertTestNames( reordered_tests, expected=[ "Tests2.test2", "Tests2.test1", "Tests1.test1", "Tests1.test2", ], ) def test_reorder_tests_random(self): tests = self.make_tests() # Choose a seed that shuffles both the classes and methods. shuffler = Shuffler(seed=9) reordered_tests = reorder_tests(tests, classes=[], shuffler=shuffler) self.assertIsInstance(reordered_tests, collections.abc.Iterator) self.assertTestNames( reordered_tests, expected=[ "Tests2.test1", "Tests2.test2", "Tests1.test2", "Tests1.test1", ], ) def test_reorder_tests_random_mixed_classes(self): tests = self.make_tests() # Move the last item to the front. tests.insert(0, tests.pop()) shuffler = Shuffler(seed=9) self.assertTestNames( tests, expected=[ "Tests2.test2", "Tests1.test1", "Tests1.test2", "Tests2.test1", ], ) reordered_tests = reorder_tests(tests, classes=[], shuffler=shuffler) self.assertTestNames( reordered_tests, expected=[ "Tests2.test1", "Tests2.test2", "Tests1.test2", "Tests1.test1", ], ) def test_reorder_tests_reverse_with_duplicates(self): class Tests1(unittest.TestCase): def test1(self): pass class Tests2(unittest.TestCase): def test2(self): pass def test3(self): pass suite = self.build_test_suite((Tests1, Tests2)) subsuite = list(suite)[0] suite.addTest(subsuite) tests = list(iter_test_cases(suite)) self.assertTestNames( tests, expected=[ "Tests1.test1", "Tests2.test2", "Tests2.test3", "Tests1.test1", ], ) reordered_tests = reorder_tests(tests, classes=[]) self.assertTestNames( reordered_tests, expected=[ "Tests1.test1", "Tests2.test2", "Tests2.test3", ], ) reordered_tests = reorder_tests(tests, classes=[], reverse=True) self.assertTestNames( reordered_tests, expected=[ "Tests2.test3", "Tests2.test2", "Tests1.test1", ], ) class DependencyOrderingTests(unittest.TestCase): def test_simple_dependencies(self): raw = [ ("s1", ("s1_db", ["alpha"])), ("s2", ("s2_db", ["bravo"])), ("s3", ("s3_db", ["charlie"])), ] dependencies = { "alpha": ["charlie"], "bravo": ["charlie"], } ordered = dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig, value in ordered] self.assertIn("s1", ordered_sigs) self.assertIn("s2", ordered_sigs) self.assertIn("s3", ordered_sigs) self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s1")) self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s2")) def test_chained_dependencies(self): raw = [ ("s1", ("s1_db", ["alpha"])), ("s2", ("s2_db", ["bravo"])), ("s3", ("s3_db", ["charlie"])), ] dependencies = { "alpha": ["bravo"], "bravo": ["charlie"], } ordered = dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig, value in ordered] self.assertIn("s1", ordered_sigs) self.assertIn("s2", ordered_sigs) self.assertIn("s3", ordered_sigs) # Explicit dependencies self.assertLess(ordered_sigs.index("s2"), ordered_sigs.index("s1")) self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s2")) # Implied dependencies self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s1")) def test_multiple_dependencies(self): raw = [ ("s1", ("s1_db", ["alpha"])), ("s2", ("s2_db", ["bravo"])), ("s3", ("s3_db", ["charlie"])), ("s4", ("s4_db", ["delta"])), ] dependencies = { "alpha": ["bravo", "delta"], "bravo": ["charlie"], "delta": ["charlie"], } ordered = dependency_ordered(raw, dependencies=dependencies) ordered_sigs = [sig for sig, aliases in ordered] self.assertIn("s1", ordered_sigs) self.assertIn("s2", ordered_sigs) self.assertIn("s3", ordered_sigs) self.assertIn("s4", ordered_sigs) # Explicit dependencies self.assertLess(ordered_sigs.index("s2"), ordered_sigs.index("s1")) self.assertLess(ordered_sigs.index("s4"), ordered_sigs.index("s1")) self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s2")) self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s4")) # Implicit dependencies self.assertLess(ordered_sigs.index("s3"), ordered_sigs.index("s1")) def test_circular_dependencies(self): raw = [ ("s1", ("s1_db", ["alpha"])), ("s2", ("s2_db", ["bravo"])), ] dependencies = { "bravo": ["alpha"], "alpha": ["bravo"], } with self.assertRaises(ImproperlyConfigured): dependency_ordered(raw, dependencies=dependencies) def test_own_alias_dependency(self): raw = [("s1", ("s1_db", ["alpha", "bravo"]))] dependencies = {"alpha": ["bravo"]} with self.assertRaises(ImproperlyConfigured): dependency_ordered(raw, dependencies=dependencies) # reordering aliases shouldn't matter raw = [("s1", ("s1_db", ["bravo", "alpha"]))] with self.assertRaises(ImproperlyConfigured): dependency_ordered(raw, dependencies=dependencies) class MockTestRunner: def __init__(self, *args, **kwargs): if parallel := kwargs.get("parallel"): sys.stderr.write(f"parallel={parallel}") MockTestRunner.run_tests = mock.Mock(return_value=[]) class ManageCommandTests(unittest.TestCase): def test_custom_test_runner(self): call_command("test", "sites", testrunner="test_runner.tests.MockTestRunner") MockTestRunner.run_tests.assert_called_with(("sites",)) def test_bad_test_runner(self): with self.assertRaises(AttributeError): call_command("test", "sites", testrunner="test_runner.NonexistentRunner") def test_time_recorded(self): with captured_stderr() as stderr: call_command( "test", "--timing", "sites", testrunner="test_runner.tests.MockTestRunner", ) self.assertIn("Total run took", stderr.getvalue()) # Isolate from the real environment. @mock.patch.dict(os.environ, {}, clear=True) @mock.patch.object(multiprocessing, "cpu_count", return_value=12) class ManageCommandParallelTests(SimpleTestCase): def test_parallel_default(self, *mocked_objects): with captured_stderr() as stderr: call_command( "test", "--parallel", testrunner="test_runner.tests.MockTestRunner", ) self.assertIn("parallel=12", stderr.getvalue()) def test_parallel_auto(self, *mocked_objects): with captured_stderr() as stderr: call_command( "test", "--parallel=auto", testrunner="test_runner.tests.MockTestRunner", ) self.assertIn("parallel=12", stderr.getvalue()) def test_no_parallel(self, *mocked_objects): with captured_stderr() as stderr: call_command("test", testrunner="test_runner.tests.MockTestRunner") # Parallel is disabled by default. self.assertEqual(stderr.getvalue(), "") @mock.patch.object(multiprocessing, "get_start_method", return_value="spawn") def test_parallel_spawn(self, *mocked_objects): with captured_stderr() as stderr: call_command( "test", "--parallel=auto", testrunner="test_runner.tests.MockTestRunner", ) self.assertIn("parallel=1", stderr.getvalue()) @mock.patch.object(multiprocessing, "get_start_method", return_value="spawn") def test_no_parallel_spawn(self, *mocked_objects): with captured_stderr() as stderr: call_command( "test", testrunner="test_runner.tests.MockTestRunner", ) self.assertEqual(stderr.getvalue(), "") @mock.patch.dict(os.environ, {"DJANGO_TEST_PROCESSES": "7"}) def test_no_parallel_django_test_processes_env(self, *mocked_objects): with captured_stderr() as stderr: call_command("test", testrunner="test_runner.tests.MockTestRunner") self.assertEqual(stderr.getvalue(), "") @mock.patch.dict(os.environ, {"DJANGO_TEST_PROCESSES": "invalid"}) def test_django_test_processes_env_non_int(self, *mocked_objects): with self.assertRaises(ValueError): call_command( "test", "--parallel", testrunner="test_runner.tests.MockTestRunner", ) @mock.patch.dict(os.environ, {"DJANGO_TEST_PROCESSES": "7"}) def test_django_test_processes_parallel_default(self, *mocked_objects): for parallel in ["--parallel", "--parallel=auto"]: with self.subTest(parallel=parallel): with captured_stderr() as stderr: call_command( "test", parallel, testrunner="test_runner.tests.MockTestRunner", ) self.assertIn("parallel=7", stderr.getvalue()) class CustomTestRunnerOptionsSettingsTests(AdminScriptTestCase): """ Custom runners can add command line arguments. The runner is specified through a settings file. """ def setUp(self): super().setUp() settings = { "TEST_RUNNER": "'test_runner.runner.CustomOptionsTestRunner'", } self.write_settings("settings.py", sdict=settings) def test_default_options(self): args = ["test", "--settings=test_project.settings"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "1:2:3") def test_default_and_given_options(self): args = ["test", "--settings=test_project.settings", "--option_b=foo"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "1:foo:3") def test_option_name_and_value_separated(self): args = ["test", "--settings=test_project.settings", "--option_b", "foo"] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "1:foo:3") def test_all_options_given(self): args = [ "test", "--settings=test_project.settings", "--option_a=bar", "--option_b=foo", "--option_c=31337", ] out, err = self.run_django_admin(args) self.assertNoOutput(err) self.assertOutput(out, "bar:foo:31337") class CustomTestRunnerOptionsCmdlineTests(AdminScriptTestCase): """ Custom runners can add command line arguments when the runner is specified using --testrunner. """ def setUp(self): super().setUp() self.write_settings("settings.py") def test_testrunner_option(self): args = [ "test", "--testrunner", "test_runner.runner.CustomOptionsTestRunner", "--option_a=bar", "--option_b=foo", "--option_c=31337", ] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "bar:foo:31337") def test_testrunner_equals(self): args = [ "test", "--testrunner=test_runner.runner.CustomOptionsTestRunner", "--option_a=bar", "--option_b=foo", "--option_c=31337", ] out, err = self.run_django_admin(args, "test_project.settings") self.assertNoOutput(err) self.assertOutput(out, "bar:foo:31337") def test_no_testrunner(self): args = ["test", "--testrunner"] out, err = self.run_django_admin(args, "test_project.settings") self.assertIn("usage", err) self.assertNotIn("Traceback", err) self.assertNoOutput(out) class NoInitializeSuiteTestRunnerTests(SimpleTestCase): @mock.patch.object(multiprocessing, "get_start_method", return_value="spawn") @mock.patch( "django.test.runner.ParallelTestSuite.initialize_suite", side_effect=Exception("initialize_suite() is called."), ) def test_no_initialize_suite_test_runner(self, *mocked_objects): """ The test suite's initialize_suite() method must always be called when using spawn. It cannot rely on a test runner implementation. """ class NoInitializeSuiteTestRunner(DiscoverRunner): def setup_test_environment(self, **kwargs): return def setup_databases(self, **kwargs): return def run_checks(self, databases): return def teardown_databases(self, old_config, **kwargs): return def teardown_test_environment(self, **kwargs): return def run_suite(self, suite, **kwargs): kwargs = self.get_test_runner_kwargs() runner = self.test_runner(**kwargs) return runner.run(suite) with self.assertRaisesMessage(Exception, "initialize_suite() is called."): runner = NoInitializeSuiteTestRunner( verbosity=0, interactive=False, parallel=2 ) runner.run_tests( [ "test_runner_apps.sample.tests_sample.TestDjangoTestCase", "test_runner_apps.simple.tests", ] ) class TestRunnerInitializerTests(SimpleTestCase): # Raise an exception to don't actually run tests. @mock.patch.object( multiprocessing, "Pool", side_effect=Exception("multiprocessing.Pool()") ) def test_no_initialize_suite_test_runner(self, mocked_pool): class StubTestRunner(DiscoverRunner): def setup_test_environment(self, **kwargs): return def setup_databases(self, **kwargs): return def run_checks(self, databases): return def teardown_databases(self, old_config, **kwargs): return def teardown_test_environment(self, **kwargs): return def run_suite(self, suite, **kwargs): kwargs = self.get_test_runner_kwargs() runner = self.test_runner(**kwargs) return runner.run(suite) runner = StubTestRunner(verbosity=0, interactive=False, parallel=2) with self.assertRaisesMessage(Exception, "multiprocessing.Pool()"): runner.run_tests( [ "test_runner_apps.sample.tests_sample.TestDjangoTestCase", "test_runner_apps.simple.tests", ] ) # Initializer must be a function. self.assertIs(mocked_pool.call_args.kwargs["initializer"], _init_worker) class Ticket17477RegressionTests(AdminScriptTestCase): def setUp(self): super().setUp() self.write_settings("settings.py") def test_ticket_17477(self): """'manage.py help test' works after r16352.""" args = ["help", "test"] out, err = self.run_manage(args) self.assertNoOutput(err) class SQLiteInMemoryTestDbs(TransactionTestCase): available_apps = ["test_runner"] databases = {"default", "other"} @unittest.skipUnless( all(db.connections[conn].vendor == "sqlite" for conn in db.connections), "This is an sqlite-specific issue", ) def test_transaction_support(self): # Assert connections mocking is appropriately applied by preventing # any attempts at calling create_test_db on the global connection # objects. for connection in db.connections.all(): create_test_db = mock.patch.object( connection.creation, "create_test_db", side_effect=AssertionError( "Global connection object shouldn't be manipulated." ), ) create_test_db.start() self.addCleanup(create_test_db.stop) for option_key, option_value in ( ("NAME", ":memory:"), ("TEST", {"NAME": ":memory:"}), ): tested_connections = db.ConnectionHandler( { "default": { "ENGINE": "django.db.backends.sqlite3", option_key: option_value, }, "other": { "ENGINE": "django.db.backends.sqlite3", option_key: option_value, }, } ) with mock.patch("django.test.utils.connections", new=tested_connections): other = tested_connections["other"] DiscoverRunner(verbosity=0).setup_databases() msg = ( "DATABASES setting '%s' option set to sqlite3's ':memory:' value " "shouldn't interfere with transaction support detection." % option_key ) # Transaction support is properly initialized for the 'other' DB. self.assertTrue(other.features.supports_transactions, msg) # And all the DBs report that they support transactions. self.assertTrue(connections_support_transactions(), msg) class DummyBackendTest(unittest.TestCase): def test_setup_databases(self): """ setup_databases() doesn't fail with dummy database backend. """ tested_connections = db.ConnectionHandler({}) with mock.patch("django.test.utils.connections", new=tested_connections): runner_instance = DiscoverRunner(verbosity=0) old_config = runner_instance.setup_databases() runner_instance.teardown_databases(old_config) class AliasedDefaultTestSetupTest(unittest.TestCase): def test_setup_aliased_default_database(self): """ setup_databases() doesn't fail when 'default' is aliased """ tested_connections = db.ConnectionHandler( {"default": {"NAME": "dummy"}, "aliased": {"NAME": "dummy"}} ) with mock.patch("django.test.utils.connections", new=tested_connections): runner_instance = DiscoverRunner(verbosity=0) old_config = runner_instance.setup_databases() runner_instance.teardown_databases(old_config) class SetupDatabasesTests(SimpleTestCase): def setUp(self): self.runner_instance = DiscoverRunner(verbosity=0) def test_setup_aliased_databases(self): tested_connections = db.ConnectionHandler( { "default": { "ENGINE": "django.db.backends.dummy", "NAME": "dbname", }, "other": { "ENGINE": "django.db.backends.dummy", "NAME": "dbname", }, } ) with mock.patch( "django.db.backends.dummy.base.DatabaseWrapper.creation_class" ) as mocked_db_creation: with mock.patch("django.test.utils.connections", new=tested_connections): old_config = self.runner_instance.setup_databases() self.runner_instance.teardown_databases(old_config) mocked_db_creation.return_value.destroy_test_db.assert_called_once_with( "dbname", 0, False ) def test_setup_test_database_aliases(self): """ The default database must be the first because data migrations use the default alias by default. """ tested_connections = db.ConnectionHandler( { "other": { "ENGINE": "django.db.backends.dummy", "NAME": "dbname", }, "default": { "ENGINE": "django.db.backends.dummy", "NAME": "dbname", }, } ) with mock.patch("django.test.utils.connections", new=tested_connections): test_databases, _ = get_unique_databases_and_mirrors() self.assertEqual( test_databases, { ("", "", "django.db.backends.dummy", "test_dbname"): ( "dbname", ["default", "other"], ), }, ) def test_destroy_test_db_restores_db_name(self): tested_connections = db.ConnectionHandler( { "default": { "ENGINE": settings.DATABASES[db.DEFAULT_DB_ALIAS]["ENGINE"], "NAME": "xxx_test_database", }, } ) # Using the real current name as old_name to not mess with the test suite. old_name = settings.DATABASES[db.DEFAULT_DB_ALIAS]["NAME"] with mock.patch("django.db.connections", new=tested_connections): tested_connections["default"].creation.destroy_test_db( old_name, verbosity=0, keepdb=True ) self.assertEqual( tested_connections["default"].settings_dict["NAME"], old_name ) def test_serialization(self): tested_connections = db.ConnectionHandler( { "default": { "ENGINE": "django.db.backends.dummy", }, } ) with mock.patch( "django.db.backends.dummy.base.DatabaseWrapper.creation_class" ) as mocked_db_creation: with mock.patch("django.test.utils.connections", new=tested_connections): self.runner_instance.setup_databases() mocked_db_creation.return_value.create_test_db.assert_called_once_with( verbosity=0, autoclobber=False, serialize=True, keepdb=False ) def test_serialized_off(self): tested_connections = db.ConnectionHandler( { "default": { "ENGINE": "django.db.backends.dummy", "TEST": {"SERIALIZE": False}, }, } ) msg = ( "The SERIALIZE test database setting is deprecated as it can be " "inferred from the TestCase/TransactionTestCase.databases that " "enable the serialized_rollback feature." ) with mock.patch( "django.db.backends.dummy.base.DatabaseWrapper.creation_class" ) as mocked_db_creation: with mock.patch("django.test.utils.connections", new=tested_connections): with self.assertWarnsMessage(RemovedInDjango50Warning, msg): self.runner_instance.setup_databases() mocked_db_creation.return_value.create_test_db.assert_called_once_with( verbosity=0, autoclobber=False, serialize=False, keepdb=False ) @skipUnlessDBFeature("supports_sequence_reset") class AutoIncrementResetTest(TransactionTestCase): """ Creating the same models in different test methods receive the same PK values since the sequences are reset before each test method. """ available_apps = ["test_runner"] reset_sequences = True def _test(self): # Regular model p = Person.objects.create(first_name="Jack", last_name="Smith") self.assertEqual(p.pk, 1) # Auto-created many-to-many through model p.friends.add(Person.objects.create(first_name="Jacky", last_name="Smith")) self.assertEqual(p.friends.through.objects.first().pk, 1) # Many-to-many through model b = B.objects.create() t = Through.objects.create(person=p, b=b) self.assertEqual(t.pk, 1) def test_autoincrement_reset1(self): self._test() def test_autoincrement_reset2(self): self._test() class EmptyDefaultDatabaseTest(unittest.TestCase): def test_empty_default_database(self): """ An empty default database in settings does not raise an ImproperlyConfigured error when running a unit test that does not use a database. """ tested_connections = db.ConnectionHandler({"default": {}}) with mock.patch("django.db.connections", new=tested_connections): connection = tested_connections[db.utils.DEFAULT_DB_ALIAS] self.assertEqual( connection.settings_dict["ENGINE"], "django.db.backends.dummy" ) connections_support_transactions() class RunTestsExceptionHandlingTests(unittest.TestCase): def test_run_checks_raises(self): """ Teardown functions are run when run_checks() raises SystemCheckError. """ with mock.patch( "django.test.runner.DiscoverRunner.setup_test_environment" ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( "django.test.runner.DiscoverRunner.build_suite" ), mock.patch( "django.test.runner.DiscoverRunner.run_checks", side_effect=SystemCheckError ), mock.patch( "django.test.runner.DiscoverRunner.teardown_databases" ) as teardown_databases, mock.patch( "django.test.runner.DiscoverRunner.teardown_test_environment" ) as teardown_test_environment: runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(SystemCheckError): runner.run_tests( ["test_runner_apps.sample.tests_sample.TestDjangoTestCase"] ) self.assertTrue(teardown_databases.called) self.assertTrue(teardown_test_environment.called) def test_run_checks_raises_and_teardown_raises(self): """ SystemCheckError is surfaced when run_checks() raises SystemCheckError and teardown databases() raises ValueError. """ with mock.patch( "django.test.runner.DiscoverRunner.setup_test_environment" ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( "django.test.runner.DiscoverRunner.build_suite" ), mock.patch( "django.test.runner.DiscoverRunner.run_checks", side_effect=SystemCheckError ), mock.patch( "django.test.runner.DiscoverRunner.teardown_databases", side_effect=ValueError, ) as teardown_databases, mock.patch( "django.test.runner.DiscoverRunner.teardown_test_environment" ) as teardown_test_environment: runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(SystemCheckError): runner.run_tests( ["test_runner_apps.sample.tests_sample.TestDjangoTestCase"] ) self.assertTrue(teardown_databases.called) self.assertFalse(teardown_test_environment.called) def test_run_checks_passes_and_teardown_raises(self): """ Exceptions on teardown are surfaced if no exceptions happen during run_checks(). """ with mock.patch( "django.test.runner.DiscoverRunner.setup_test_environment" ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( "django.test.runner.DiscoverRunner.build_suite" ), mock.patch( "django.test.runner.DiscoverRunner.run_checks" ), mock.patch( "django.test.runner.DiscoverRunner.teardown_databases", side_effect=ValueError, ) as teardown_databases, mock.patch( "django.test.runner.DiscoverRunner.teardown_test_environment" ) as teardown_test_environment: runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(ValueError): # Suppress the output when running TestDjangoTestCase. with mock.patch("sys.stderr"): runner.run_tests( ["test_runner_apps.sample.tests_sample.TestDjangoTestCase"] ) self.assertTrue(teardown_databases.called) self.assertFalse(teardown_test_environment.called) # RemovedInDjango50Warning class NoOpTestRunner(DiscoverRunner): def setup_test_environment(self, **kwargs): return def setup_databases(self, **kwargs): return def run_checks(self, databases): return def teardown_databases(self, old_config, **kwargs): return def teardown_test_environment(self, **kwargs): return class DiscoverRunnerExtraTestsDeprecationTests(SimpleTestCase): msg = "The extra_tests argument is deprecated." def get_runner(self): return NoOpTestRunner(verbosity=0, interactive=False) def test_extra_tests_build_suite(self): runner = self.get_runner() with self.assertWarnsMessage(RemovedInDjango50Warning, self.msg): runner.build_suite(extra_tests=[]) def test_extra_tests_run_tests(self): runner = self.get_runner() with captured_stderr(): with self.assertWarnsMessage(RemovedInDjango50Warning, self.msg): runner.run_tests( test_labels=["test_runner_apps.sample.tests_sample.EmptyTestCase"], extra_tests=[], )
88330cce20dac1dc0f291a8e62162f5b73e00b54ab44b650af84868472f7235a
import json import unittest import xml.etree.ElementTree from django.db import NotSupportedError, connection, transaction from django.db.models import Count from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import Tag @skipUnlessDBFeature("supports_explaining_query_execution") class ExplainTests(TestCase): def test_basic(self): querysets = [ Tag.objects.filter(name="test"), Tag.objects.filter(name="test").select_related("parent"), Tag.objects.filter(name="test").prefetch_related("children"), Tag.objects.filter(name="test").annotate(Count("children")), Tag.objects.filter(name="test").values_list("name"), Tag.objects.order_by().union(Tag.objects.order_by().filter(name="test")), ] if connection.features.has_select_for_update: querysets.append(Tag.objects.select_for_update().filter(name="test")) supported_formats = connection.features.supported_explain_formats all_formats = ( (None,) + tuple(supported_formats) + tuple(f.lower() for f in supported_formats) ) for idx, queryset in enumerate(querysets): for format in all_formats: with self.subTest(format=format, queryset=idx): with self.assertNumQueries(1) as captured_queries: result = queryset.explain(format=format) self.assertTrue( captured_queries[0]["sql"].startswith( connection.ops.explain_prefix ) ) self.assertIsInstance(result, str) self.assertTrue(result) if not format: continue if format.lower() == "xml": try: xml.etree.ElementTree.fromstring(result) except xml.etree.ElementTree.ParseError as e: self.fail( f"QuerySet.explain() result is not valid XML: {e}" ) elif format.lower() == "json": try: json.loads(result) except json.JSONDecodeError as e: self.fail( f"QuerySet.explain() result is not valid JSON: {e}" ) def test_unknown_options(self): with self.assertRaisesMessage(ValueError, "Unknown options: TEST, TEST2"): Tag.objects.explain(**{"TEST": 1, "TEST2": 1}) def test_unknown_format(self): msg = "DOES NOT EXIST is not a recognized format." if connection.features.supported_explain_formats: msg += " Allowed formats: %s" % ", ".join( sorted(connection.features.supported_explain_formats) ) else: msg += f" {connection.display_name} does not support any formats." with self.assertRaisesMessage(ValueError, msg): Tag.objects.explain(format="does not exist") @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL specific") def test_postgres_options(self): qs = Tag.objects.filter(name="test") test_options = [ {"COSTS": False, "BUFFERS": True, "ANALYZE": True}, {"costs": False, "buffers": True, "analyze": True}, {"verbose": True, "timing": True, "analyze": True}, {"verbose": False, "timing": False, "analyze": True}, {"summary": True}, {"settings": True}, ] if connection.features.is_postgresql_13: test_options.append({"analyze": True, "wal": True}) for options in test_options: with self.subTest(**options), transaction.atomic(): with CaptureQueriesContext(connection) as captured_queries: qs.explain(format="text", **options) self.assertEqual(len(captured_queries), 1) for name, value in options.items(): option = "{} {}".format(name.upper(), "true" if value else "false") self.assertIn(option, captured_queries[0]["sql"]) def test_option_sql_injection(self): qs = Tag.objects.filter(name="test") options = {"SUMMARY true) SELECT 1; --": True} msg = "Invalid option name: 'SUMMARY true) SELECT 1; --'" with self.assertRaisesMessage(ValueError, msg): qs.explain(**options) def test_invalid_option_names(self): qs = Tag.objects.filter(name="test") tests = [ 'opt"ion', "o'ption", "op`tion", "opti on", "option--", "optio\tn", "o\nption", "option;", "你 好", # [] are used by MSSQL. "option[", "option]", ] for invalid_option in tests: with self.subTest(invalid_option): msg = f"Invalid option name: {invalid_option!r}" with self.assertRaisesMessage(ValueError, msg): qs.explain(**{invalid_option: True}) @unittest.skipUnless(connection.vendor == "mysql", "MySQL specific") def test_mysql_text_to_traditional(self): # Ensure these cached properties are initialized to prevent queries for # the MariaDB or MySQL version during the QuerySet evaluation. connection.features.supported_explain_formats with CaptureQueriesContext(connection) as captured_queries: Tag.objects.filter(name="test").explain(format="text") self.assertEqual(len(captured_queries), 1) self.assertIn("FORMAT=TRADITIONAL", captured_queries[0]["sql"]) @unittest.skipUnless( connection.vendor == "mysql", "MariaDB and MySQL >= 8.0.18 specific." ) def test_mysql_analyze(self): qs = Tag.objects.filter(name="test") with CaptureQueriesContext(connection) as captured_queries: qs.explain(analyze=True) self.assertEqual(len(captured_queries), 1) prefix = "ANALYZE " if connection.mysql_is_mariadb else "EXPLAIN ANALYZE " self.assertTrue(captured_queries[0]["sql"].startswith(prefix)) with CaptureQueriesContext(connection) as captured_queries: qs.explain(analyze=True, format="JSON") self.assertEqual(len(captured_queries), 1) if connection.mysql_is_mariadb: self.assertIn("FORMAT=JSON", captured_queries[0]["sql"]) else: self.assertNotIn("FORMAT=JSON", captured_queries[0]["sql"]) @skipIfDBFeature("supports_explaining_query_execution") class ExplainUnsupportedTests(TestCase): def test_message(self): msg = "This backend does not support explaining query execution." with self.assertRaisesMessage(NotSupportedError, msg): Tag.objects.filter(name="test").explain()
623e44a93c416574bf12192bcf19e492f43db64444983453b25b67d94564e6fd
import sys from django.template import Context, Engine, TemplateDoesNotExist, TemplateSyntaxError from django.template.base import UNKNOWN_SOURCE from django.test import SimpleTestCase, override_settings from django.urls import NoReverseMatch from django.utils import translation from django.utils.html import escape class TemplateTestMixin: def _engine(self, **kwargs): return Engine(debug=self.debug_engine, **kwargs) def test_string_origin(self): template = self._engine().from_string("string template") self.assertEqual(template.origin.name, UNKNOWN_SOURCE) self.assertIsNone(template.origin.loader_name) self.assertEqual(template.source, "string template") @override_settings(SETTINGS_MODULE=None) def test_url_reverse_no_settings_module(self): """ #9005 -- url tag shouldn't require settings.SETTINGS_MODULE to be set. """ t = self._engine().from_string("{% url will_not_match %}") c = Context() with self.assertRaises(NoReverseMatch): t.render(c) def test_url_reverse_view_name(self): """ #19827 -- url tag should keep original strack trace when reraising exception. """ t = self._engine().from_string("{% url will_not_match %}") c = Context() try: t.render(c) except NoReverseMatch: tb = sys.exc_info()[2] depth = 0 while tb.tb_next is not None: tb = tb.tb_next depth += 1 self.assertGreater( depth, 5, "The traceback context was lost when reraising the traceback." ) def test_no_wrapped_exception(self): """ # 16770 -- The template system doesn't wrap exceptions, but annotates them. """ engine = self._engine() c = Context({"coconuts": lambda: 42 / 0}) t = engine.from_string("{{ coconuts }}") with self.assertRaises(ZeroDivisionError) as e: t.render(c) if self.debug_engine: debug = e.exception.template_debug self.assertEqual(debug["start"], 0) self.assertEqual(debug["end"], 14) def test_invalid_block_suggestion(self): """ Error messages should include the unexpected block name and be in all English. """ engine = self._engine() msg = ( "Invalid block tag on line 1: 'endblock', expected 'elif', 'else' " "or 'endif'. Did you forget to register or load this tag?" ) with self.settings(USE_I18N=True), translation.override("de"): with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("{% if 1 %}lala{% endblock %}{% endif %}") def test_unknown_block_tag(self): engine = self._engine() msg = ( "Invalid block tag on line 1: 'foobar'. Did you forget to " "register or load this tag?" ) with self.assertRaisesMessage(TemplateSyntaxError, msg): engine.from_string("lala{% foobar %}") def test_compile_filter_expression_error(self): """ 19819 -- Make sure the correct token is highlighted for FilterExpression errors. """ engine = self._engine() msg = "Could not parse the remainder: '@bar' from 'foo@bar'" with self.assertRaisesMessage(TemplateSyntaxError, msg) as e: engine.from_string("{% if 1 %}{{ foo@bar }}{% endif %}") if self.debug_engine: debug = e.exception.template_debug self.assertEqual((debug["start"], debug["end"]), (10, 23)) self.assertEqual((debug["during"]), "{{ foo@bar }}") def test_compile_tag_error(self): """ Errors raised while compiling nodes should include the token information. """ engine = self._engine( libraries={"bad_tag": "template_tests.templatetags.bad_tag"}, ) with self.assertRaises(RuntimeError) as e: engine.from_string("{% load bad_tag %}{% badtag %}") if self.debug_engine: self.assertEqual(e.exception.template_debug["during"], "{% badtag %}") def test_compile_tag_error_27584(self): engine = self._engine( app_dirs=True, libraries={"tag_27584": "template_tests.templatetags.tag_27584"}, ) t = engine.get_template("27584_parent.html") with self.assertRaises(TemplateSyntaxError) as e: t.render(Context()) if self.debug_engine: self.assertEqual(e.exception.template_debug["during"], "{% badtag %}") def test_compile_tag_error_27956(self): """Errors in a child of {% extends %} are displayed correctly.""" engine = self._engine( app_dirs=True, libraries={"tag_27584": "template_tests.templatetags.tag_27584"}, ) t = engine.get_template("27956_child.html") with self.assertRaises(TemplateSyntaxError) as e: t.render(Context()) if self.debug_engine: self.assertEqual(e.exception.template_debug["during"], "{% badtag %}") def test_render_tag_error_in_extended_block(self): """Errors in extended block are displayed correctly.""" e = self._engine(app_dirs=True) template = e.get_template("test_extends_block_error.html") context = Context() with self.assertRaises(TemplateDoesNotExist) as cm: template.render(context) if self.debug_engine: self.assertEqual( cm.exception.template_debug["during"], escape('{% include "missing.html" %}'), ) def test_super_errors(self): """ #18169 -- NoReverseMatch should not be silence in block.super. """ engine = self._engine(app_dirs=True) t = engine.get_template("included_content.html") with self.assertRaises(NoReverseMatch): t.render(Context()) def test_extends_generic_template(self): """ #24338 -- Allow extending django.template.backends.django.Template objects. """ engine = self._engine() parent = engine.from_string("{% block content %}parent{% endblock %}") child = engine.from_string( "{% extends parent %}{% block content %}child{% endblock %}" ) self.assertEqual(child.render(Context({"parent": parent})), "child") def test_node_origin(self): """ #25848 -- Set origin on Node so debugging tools can determine which template the node came from even if extending or including templates. """ template = self._engine().from_string("content") for node in template.nodelist: self.assertEqual(node.origin, template.origin) def test_render_built_in_type_method(self): """ Templates should not crash when rendering methods for built-in types without required arguments. """ template = self._engine().from_string("{{ description.count }}") self.assertEqual(template.render(Context({"description": "test"})), "") class TemplateTests(TemplateTestMixin, SimpleTestCase): debug_engine = False class DebugTemplateTests(TemplateTestMixin, SimpleTestCase): debug_engine = True
2cddc22831b3d01d6b088cacc25674850a8bff7814cf5378175b9b70030b70fb
import os from functools import wraps from django.template.engine import Engine from django.test.utils import override_settings from django.utils.safestring import mark_safe ROOT = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_DIR = os.path.join(ROOT, "templates") def setup(templates, *args, test_once=False): """ Runs test method multiple times in the following order: debug cached string_if_invalid ----- ------ ----------------- False False False True False False INVALID False True INVALID True False True True Use test_once=True to test deprecation warnings since the message won't be displayed multiple times. """ for arg in args: templates.update(arg) # numerous tests make use of an inclusion tag # add this in here for simplicity templates["inclusion.html"] = "{{ result }}" loaders = [ ( "django.template.loaders.cached.Loader", [ ("django.template.loaders.locmem.Loader", templates), ], ), ] def decorator(func): # Make Engine.get_default() raise an exception to ensure that tests # are properly isolated from Django's global settings. @override_settings(TEMPLATES=None) @wraps(func) def inner(self): # Set up custom template tag libraries if specified libraries = getattr(self, "libraries", {}) self.engine = Engine( libraries=libraries, loaders=loaders, ) func(self) if test_once: return func(self) self.engine = Engine( libraries=libraries, loaders=loaders, string_if_invalid="INVALID", ) func(self) func(self) self.engine = Engine( debug=True, libraries=libraries, loaders=loaders, ) func(self) func(self) return inner return decorator # Helper objects class SomeException(Exception): silent_variable_failure = True class SomeOtherException(Exception): pass class ShouldNotExecuteException(Exception): pass class SomeClass: def __init__(self): self.otherclass = OtherClass() def method(self): return "SomeClass.method" def method2(self, o): return o def method3(self): raise SomeException def method4(self): raise SomeOtherException def method5(self): raise TypeError def __getitem__(self, key): if key == "silent_fail_key": raise SomeException elif key == "noisy_fail_key": raise SomeOtherException raise KeyError @property def silent_fail_attribute(self): raise SomeException @property def noisy_fail_attribute(self): raise SomeOtherException @property def attribute_error_attribute(self): raise AttributeError @property def type_error_attribute(self): raise TypeError class OtherClass: def method(self): return "OtherClass.method" class TestObj: def is_true(self): return True def is_false(self): return False def is_bad(self): raise ShouldNotExecuteException() class SilentGetItemClass: def __getitem__(self, key): raise SomeException class SilentAttrClass: def b(self): raise SomeException b = property(b) class UTF8Class: "Class whose __str__ returns non-ASCII data" def __str__(self): return "ŠĐĆŽćžšđ" # These two classes are used to test auto-escaping of string output. class UnsafeClass: def __str__(self): return "you & me" class SafeClass: def __str__(self): return mark_safe("you &gt; me")
b18ee2619713fffc3f714e762b4f0b28b12b33d31cef1da4bfd4c1f2a6cf32df
import datetime from copy import deepcopy from django.core.exceptions import FieldError, MultipleObjectsReturned from django.db import IntegrityError, models, transaction from django.test import TestCase from django.utils.translation import gettext_lazy from .models import ( Article, Category, Child, ChildNullableParent, ChildStringPrimaryKeyParent, City, Country, District, First, Parent, ParentStringPrimaryKey, Record, Relation, Reporter, School, Student, Third, ToFieldChild, ) class ManyToOneTests(TestCase): @classmethod def setUpTestData(cls): # Create a few Reporters. cls.r = Reporter(first_name="John", last_name="Smith", email="[email protected]") cls.r.save() cls.r2 = Reporter( first_name="Paul", last_name="Jones", email="[email protected]" ) cls.r2.save() # Create an Article. cls.a = Article( headline="This is a test", pub_date=datetime.date(2005, 7, 27), reporter=cls.r, ) cls.a.save() def test_get(self): # Article objects have access to their related Reporter objects. r = self.a.reporter self.assertEqual(r.id, self.r.id) self.assertEqual((r.first_name, self.r.last_name), ("John", "Smith")) def test_create(self): # You can also instantiate an Article by passing the Reporter's ID # instead of a Reporter object. a3 = Article( headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) a3.save() self.assertEqual(a3.reporter.id, self.r.id) # Similarly, the reporter ID can be a string. a4 = Article( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id), ) a4.save() self.assertEqual(repr(a4.reporter), "<Reporter: John Smith>") def test_add(self): # Create an Article via the Reporter object. new_article = self.r.article_set.create( headline="John's second story", pub_date=datetime.date(2005, 7, 29) ) self.assertEqual(repr(new_article), "<Article: John's second story>") self.assertEqual(new_article.reporter.id, self.r.id) # Create a new article, and add it to the article set. new_article2 = Article( headline="Paul's story", pub_date=datetime.date(2006, 1, 17) ) msg = ( "<Article: Paul's story> instance isn't saved. Use bulk=False or save the " "object first." ) with self.assertRaisesMessage(ValueError, msg): self.r.article_set.add(new_article2) self.r.article_set.add(new_article2, bulk=False) self.assertEqual(new_article2.reporter.id, self.r.id) self.assertSequenceEqual( self.r.article_set.all(), [new_article, new_article2, self.a], ) # Add the same article to a different article set - check that it moves. self.r2.article_set.add(new_article2) self.assertEqual(new_article2.reporter.id, self.r2.id) self.assertSequenceEqual(self.r2.article_set.all(), [new_article2]) # Adding an object of the wrong type raises TypeError. with transaction.atomic(): with self.assertRaisesMessage( TypeError, "'Article' instance expected, got <Reporter:" ): self.r.article_set.add(self.r2) self.assertSequenceEqual( self.r.article_set.all(), [new_article, self.a], ) def test_set(self): new_article = self.r.article_set.create( headline="John's second story", pub_date=datetime.date(2005, 7, 29) ) new_article2 = self.r2.article_set.create( headline="Paul's story", pub_date=datetime.date(2006, 1, 17) ) # Assign the article to the reporter. new_article2.reporter = self.r new_article2.save() self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>") self.assertEqual(new_article2.reporter.id, self.r.id) self.assertSequenceEqual( self.r.article_set.all(), [new_article, new_article2, self.a], ) self.assertSequenceEqual(self.r2.article_set.all(), []) # Set the article back again. self.r2.article_set.set([new_article, new_article2]) self.assertSequenceEqual(self.r.article_set.all(), [self.a]) self.assertSequenceEqual( self.r2.article_set.all(), [new_article, new_article2], ) # Funny case - because the ForeignKey cannot be null, # existing members of the set must remain. self.r.article_set.set([new_article]) self.assertSequenceEqual( self.r.article_set.all(), [new_article, self.a], ) self.assertSequenceEqual(self.r2.article_set.all(), [new_article2]) def test_reverse_assignment_deprecation(self): msg = ( "Direct assignment to the reverse side of a related set is " "prohibited. Use article_set.set() instead." ) with self.assertRaisesMessage(TypeError, msg): self.r2.article_set = [] def test_assign(self): new_article = self.r.article_set.create( headline="John's second story", pub_date=datetime.date(2005, 7, 29) ) new_article2 = self.r2.article_set.create( headline="Paul's story", pub_date=datetime.date(2006, 1, 17) ) # Assign the article to the reporter directly using the descriptor. new_article2.reporter = self.r new_article2.save() self.assertEqual(repr(new_article2.reporter), "<Reporter: John Smith>") self.assertEqual(new_article2.reporter.id, self.r.id) self.assertSequenceEqual( self.r.article_set.all(), [new_article, new_article2, self.a], ) self.assertSequenceEqual(self.r2.article_set.all(), []) # Set the article back again using set() method. self.r2.article_set.set([new_article, new_article2]) self.assertSequenceEqual(self.r.article_set.all(), [self.a]) self.assertSequenceEqual( self.r2.article_set.all(), [new_article, new_article2], ) # Because the ForeignKey cannot be null, existing members of the set # must remain. self.r.article_set.set([new_article]) self.assertSequenceEqual( self.r.article_set.all(), [new_article, self.a], ) self.assertSequenceEqual(self.r2.article_set.all(), [new_article2]) # Reporter cannot be null - there should not be a clear or remove method self.assertFalse(hasattr(self.r2.article_set, "remove")) self.assertFalse(hasattr(self.r2.article_set, "clear")) def test_assign_fk_id_value(self): parent = Parent.objects.create(name="jeff") child1 = Child.objects.create(name="frank", parent=parent) child2 = Child.objects.create(name="randy", parent=parent) parent.bestchild = child1 parent.save() parent.bestchild_id = child2.pk parent.save() self.assertEqual(parent.bestchild_id, child2.pk) self.assertFalse(Parent.bestchild.is_cached(parent)) self.assertEqual(parent.bestchild, child2) self.assertTrue(Parent.bestchild.is_cached(parent)) # Reassigning the same value doesn't clear cached instance. parent.bestchild_id = child2.pk self.assertTrue(Parent.bestchild.is_cached(parent)) def test_assign_fk_id_none(self): parent = Parent.objects.create(name="jeff") child = Child.objects.create(name="frank", parent=parent) parent.bestchild = child parent.save() parent.bestchild_id = None parent.save() self.assertIsNone(parent.bestchild_id) self.assertFalse(Parent.bestchild.is_cached(parent)) self.assertIsNone(parent.bestchild) self.assertTrue(Parent.bestchild.is_cached(parent)) def test_selects(self): new_article1 = self.r.article_set.create( headline="John's second story", pub_date=datetime.date(2005, 7, 29), ) new_article2 = self.r2.article_set.create( headline="Paul's story", pub_date=datetime.date(2006, 1, 17), ) # Reporter objects have access to their related Article objects. self.assertSequenceEqual( self.r.article_set.all(), [new_article1, self.a], ) self.assertSequenceEqual( self.r.article_set.filter(headline__startswith="This"), [self.a] ) self.assertEqual(self.r.article_set.count(), 2) self.assertEqual(self.r2.article_set.count(), 1) # Get articles by id self.assertSequenceEqual(Article.objects.filter(id__exact=self.a.id), [self.a]) self.assertSequenceEqual(Article.objects.filter(pk=self.a.id), [self.a]) # Query on an article property self.assertSequenceEqual( Article.objects.filter(headline__startswith="This"), [self.a] ) # The API automatically follows relationships as far as you need. # Use double underscores to separate relationships. # This works as many levels deep as you want. There's no limit. # Find all Articles for any Reporter whose first name is "John". self.assertSequenceEqual( Article.objects.filter(reporter__first_name__exact="John"), [new_article1, self.a], ) # Implied __exact also works self.assertSequenceEqual( Article.objects.filter(reporter__first_name="John"), [new_article1, self.a], ) # Query twice over the related field. self.assertSequenceEqual( Article.objects.filter( reporter__first_name__exact="John", reporter__last_name__exact="Smith" ), [new_article1, self.a], ) # The underlying query only makes one join when a related table is # referenced twice. queryset = Article.objects.filter( reporter__first_name__exact="John", reporter__last_name__exact="Smith" ) self.assertNumQueries(1, list, queryset) self.assertEqual( queryset.query.get_compiler(queryset.db).as_sql()[0].count("INNER JOIN"), 1 ) # The automatically joined table has a predictable name. self.assertSequenceEqual( Article.objects.filter(reporter__first_name__exact="John").extra( where=["many_to_one_reporter.last_name='Smith'"] ), [new_article1, self.a], ) # ... and should work fine with the string that comes out of # forms.Form.cleaned_data. self.assertQuerysetEqual( ( Article.objects.filter(reporter__first_name__exact="John").extra( where=["many_to_one_reporter.last_name='%s'" % "Smith"] ) ), [new_article1, self.a], ) # Find all Articles for a Reporter. # Use direct ID check, pk check, and object comparison self.assertSequenceEqual( Article.objects.filter(reporter__id__exact=self.r.id), [new_article1, self.a], ) self.assertSequenceEqual( Article.objects.filter(reporter__pk=self.r.id), [new_article1, self.a], ) self.assertSequenceEqual( Article.objects.filter(reporter=self.r.id), [new_article1, self.a], ) self.assertSequenceEqual( Article.objects.filter(reporter=self.r), [new_article1, self.a], ) self.assertSequenceEqual( Article.objects.filter(reporter__in=[self.r.id, self.r2.id]).distinct(), [new_article1, new_article2, self.a], ) self.assertSequenceEqual( Article.objects.filter(reporter__in=[self.r, self.r2]).distinct(), [new_article1, new_article2, self.a], ) # You can also use a queryset instead of a literal list of instances. # The queryset must be reduced to a list of values using values(), # then converted into a query self.assertSequenceEqual( Article.objects.filter( reporter__in=Reporter.objects.filter(first_name="John") .values("pk") .query ).distinct(), [new_article1, self.a], ) def test_reverse_selects(self): a3 = Article.objects.create( headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) Article.objects.create( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) john_smith = [self.r] # Reporters can be queried self.assertSequenceEqual( Reporter.objects.filter(id__exact=self.r.id), john_smith ) self.assertSequenceEqual(Reporter.objects.filter(pk=self.r.id), john_smith) self.assertSequenceEqual( Reporter.objects.filter(first_name__startswith="John"), john_smith ) # Reporters can query in opposite direction of ForeignKey definition self.assertSequenceEqual( Reporter.objects.filter(article__id__exact=self.a.id), john_smith ) self.assertSequenceEqual( Reporter.objects.filter(article__pk=self.a.id), john_smith ) self.assertSequenceEqual(Reporter.objects.filter(article=self.a.id), john_smith) self.assertSequenceEqual(Reporter.objects.filter(article=self.a), john_smith) self.assertSequenceEqual( Reporter.objects.filter(article__in=[self.a.id, a3.id]).distinct(), john_smith, ) self.assertSequenceEqual( Reporter.objects.filter(article__in=[self.a.id, a3]).distinct(), john_smith ) self.assertSequenceEqual( Reporter.objects.filter(article__in=[self.a, a3]).distinct(), john_smith ) self.assertCountEqual( Reporter.objects.filter(article__headline__startswith="T"), [self.r, self.r], ) self.assertSequenceEqual( Reporter.objects.filter(article__headline__startswith="T").distinct(), john_smith, ) # Counting in the opposite direction works in conjunction with distinct() self.assertEqual( Reporter.objects.filter(article__headline__startswith="T").count(), 2 ) self.assertEqual( Reporter.objects.filter(article__headline__startswith="T") .distinct() .count(), 1, ) # Queries can go round in circles. self.assertCountEqual( Reporter.objects.filter(article__reporter__first_name__startswith="John"), [self.r, self.r, self.r], ) self.assertSequenceEqual( Reporter.objects.filter( article__reporter__first_name__startswith="John" ).distinct(), john_smith, ) self.assertSequenceEqual( Reporter.objects.filter(article__reporter__exact=self.r).distinct(), john_smith, ) # Implied __exact also works. self.assertSequenceEqual( Reporter.objects.filter(article__reporter=self.r).distinct(), john_smith ) # It's possible to use values() calls across many-to-one relations. # (Note, too, that we clear the ordering here so as not to drag the # 'headline' field into the columns being used to determine uniqueness) d = {"reporter__first_name": "John", "reporter__last_name": "Smith"} qs = ( Article.objects.filter( reporter=self.r, ) .distinct() .order_by() .values("reporter__first_name", "reporter__last_name") ) self.assertEqual([d], list(qs)) def test_select_related(self): # Article.objects.select_related().dates() works properly when there # are multiple Articles with the same date but different foreign-key # objects (Reporters). r1 = Reporter.objects.create( first_name="Mike", last_name="Royko", email="[email protected]" ) r2 = Reporter.objects.create( first_name="John", last_name="Kass", email="[email protected]" ) Article.objects.create( headline="First", pub_date=datetime.date(1980, 4, 23), reporter=r1 ) Article.objects.create( headline="Second", pub_date=datetime.date(1980, 4, 23), reporter=r2 ) self.assertEqual( list(Article.objects.select_related().dates("pub_date", "day")), [datetime.date(1980, 4, 23), datetime.date(2005, 7, 27)], ) self.assertEqual( list(Article.objects.select_related().dates("pub_date", "month")), [datetime.date(1980, 4, 1), datetime.date(2005, 7, 1)], ) self.assertEqual( list(Article.objects.select_related().dates("pub_date", "year")), [datetime.date(1980, 1, 1), datetime.date(2005, 1, 1)], ) def test_delete(self): new_article1 = self.r.article_set.create( headline="John's second story", pub_date=datetime.date(2005, 7, 29), ) new_article2 = self.r2.article_set.create( headline="Paul's story", pub_date=datetime.date(2006, 1, 17), ) new_article3 = Article.objects.create( headline="Third article", pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id, ) new_article4 = Article.objects.create( headline="Fourth article", pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id), ) # If you delete a reporter, their articles will be deleted. self.assertSequenceEqual( Article.objects.all(), [new_article4, new_article1, new_article2, new_article3, self.a], ) self.assertSequenceEqual( Reporter.objects.order_by("first_name"), [self.r, self.r2], ) self.r2.delete() self.assertSequenceEqual( Article.objects.all(), [new_article4, new_article1, new_article3, self.a], ) self.assertSequenceEqual(Reporter.objects.order_by("first_name"), [self.r]) # You can delete using a JOIN in the query. Reporter.objects.filter(article__headline__startswith="This").delete() self.assertSequenceEqual(Reporter.objects.all(), []) self.assertSequenceEqual(Article.objects.all(), []) def test_explicit_fk(self): # Create a new Article with get_or_create using an explicit value # for a ForeignKey. a2, created = Article.objects.get_or_create( headline="John's second test", pub_date=datetime.date(2011, 5, 7), reporter_id=self.r.id, ) self.assertTrue(created) self.assertEqual(a2.reporter.id, self.r.id) # You can specify filters containing the explicit FK value. self.assertSequenceEqual( Article.objects.filter(reporter_id__exact=self.r.id), [a2, self.a], ) # Create an Article by Paul for the same date. a3 = Article.objects.create( headline="Paul's commentary", pub_date=datetime.date(2011, 5, 7), reporter_id=self.r2.id, ) self.assertEqual(a3.reporter.id, self.r2.id) # Get should respect explicit foreign keys as well. msg = "get() returned more than one Article -- it returned 2!" with self.assertRaisesMessage(MultipleObjectsReturned, msg): Article.objects.get(reporter_id=self.r.id) self.assertEqual( repr(a3), repr( Article.objects.get( reporter_id=self.r2.id, pub_date=datetime.date(2011, 5, 7) ) ), ) def test_deepcopy_and_circular_references(self): # Regression for #12876 -- Model methods that include queries that # recursive don't cause recursion depth problems under deepcopy. self.r.cached_query = Article.objects.filter(reporter=self.r) self.assertEqual(repr(deepcopy(self.r)), "<Reporter: John Smith>") def test_manager_class_caching(self): r1 = Reporter.objects.create(first_name="Mike") r2 = Reporter.objects.create(first_name="John") # Same twice self.assertIs(r1.article_set.__class__, r1.article_set.__class__) # Same as each other self.assertIs(r1.article_set.__class__, r2.article_set.__class__) def test_create_relation_with_gettext_lazy(self): reporter = Reporter.objects.create( first_name="John", last_name="Smith", email="[email protected]" ) lazy = gettext_lazy("test") reporter.article_set.create(headline=lazy, pub_date=datetime.date(2011, 6, 10)) notlazy = str(lazy) article = reporter.article_set.get() self.assertEqual(article.headline, notlazy) def test_values_list_exception(self): expected_message = ( "Cannot resolve keyword 'notafield' into field. Choices are: %s" ) reporter_fields = ", ".join(sorted(f.name for f in Reporter._meta.get_fields())) with self.assertRaisesMessage(FieldError, expected_message % reporter_fields): Article.objects.values_list("reporter__notafield") article_fields = ", ".join( ["EXTRA"] + sorted(f.name for f in Article._meta.get_fields()) ) with self.assertRaisesMessage(FieldError, expected_message % article_fields): Article.objects.extra(select={"EXTRA": "EXTRA_SELECT"}).values_list( "notafield" ) def test_fk_assignment_and_related_object_cache(self): # Tests of ForeignKey assignment and the related-object cache (see #6886). p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) # Look up the object again so that we get a "fresh" object. c = Child.objects.get(name="Child") p = c.parent # Accessing the related object again returns the exactly same object. self.assertIs(c.parent, p) # But if we kill the cache, we get a new object. del c._state.fields_cache["parent"] self.assertIsNot(c.parent, p) # Assigning a new object results in that object getting cached immediately. p2 = Parent.objects.create(name="Parent 2") c.parent = p2 self.assertIs(c.parent, p2) # Assigning None succeeds if field is null=True. p.bestchild = None self.assertIsNone(p.bestchild) # bestchild should still be None after saving. p.save() self.assertIsNone(p.bestchild) # bestchild should still be None after fetching the object again. p = Parent.objects.get(name="Parent") self.assertIsNone(p.bestchild) # Assigning None will not fail: Child.parent is null=False. setattr(c, "parent", None) # You also can't assign an object of the wrong type here msg = ( 'Cannot assign "<First: First object (1)>": "Child.parent" must ' 'be a "Parent" instance.' ) with self.assertRaisesMessage(ValueError, msg): setattr(c, "parent", First(id=1, second=1)) # You can assign None to Child.parent during object creation. Child(name="xyzzy", parent=None) # But when trying to save a Child with parent=None, the database will # raise IntegrityError. with self.assertRaises(IntegrityError), transaction.atomic(): Child.objects.create(name="xyzzy", parent=None) # Creation using keyword argument should cache the related object. p = Parent.objects.get(name="Parent") c = Child(parent=p) self.assertIs(c.parent, p) # Creation using keyword argument and unsaved related instance (#8070). p = Parent() msg = ( "save() prohibited to prevent data loss due to unsaved related object " "'parent'." ) with self.assertRaisesMessage(ValueError, msg): Child.objects.create(parent=p) with self.assertRaisesMessage(ValueError, msg): ToFieldChild.objects.create(parent=p) # Creation using attname keyword argument and an id will cause the # related object to be fetched. p = Parent.objects.get(name="Parent") c = Child(parent_id=p.id) self.assertIsNot(c.parent, p) self.assertEqual(c.parent, p) def test_save_parent_after_assign(self): category = Category(name="cats") record = Record(category=category) category.save() record.save() category.name = "dogs" with self.assertNumQueries(0): self.assertEqual(category.id, record.category_id) self.assertEqual(category.name, record.category.name) def test_save_nullable_fk_after_parent(self): parent = Parent() child = ChildNullableParent(parent=parent) parent.save() child.save() child.refresh_from_db() self.assertEqual(child.parent, parent) def test_save_nullable_fk_after_parent_with_to_field(self): parent = Parent(name="jeff") child = ToFieldChild(parent=parent) parent.save() child.save() child.refresh_from_db() self.assertEqual(child.parent, parent) self.assertEqual(child.parent_id, parent.name) def test_save_fk_after_parent_with_non_numeric_pk_set_on_child(self): parent = ParentStringPrimaryKey() child = ChildStringPrimaryKeyParent(parent=parent) child.parent.name = "jeff" parent.save() child.save() child.refresh_from_db() self.assertEqual(child.parent, parent) self.assertEqual(child.parent_id, parent.name) def test_fk_to_bigautofield(self): ch = City.objects.create(name="Chicago") District.objects.create(city=ch, name="Far South") District.objects.create(city=ch, name="North") ny = City.objects.create(name="New York", id=2**33) District.objects.create(city=ny, name="Brooklyn") District.objects.create(city=ny, name="Manhattan") def test_fk_to_smallautofield(self): us = Country.objects.create(name="United States") City.objects.create(country=us, name="Chicago") City.objects.create(country=us, name="New York") uk = Country.objects.create(name="United Kingdom", id=2**11) City.objects.create(country=uk, name="London") City.objects.create(country=uk, name="Edinburgh") def test_multiple_foreignkeys(self): # Test of multiple ForeignKeys to the same model (bug #7125). c1 = Category.objects.create(name="First") c2 = Category.objects.create(name="Second") c3 = Category.objects.create(name="Third") r1 = Record.objects.create(category=c1) r2 = Record.objects.create(category=c1) r3 = Record.objects.create(category=c2) r4 = Record.objects.create(category=c2) r5 = Record.objects.create(category=c3) Relation.objects.create(left=r1, right=r2) Relation.objects.create(left=r3, right=r4) rel = Relation.objects.create(left=r1, right=r3) Relation.objects.create(left=r5, right=r2) Relation.objects.create(left=r3, right=r2) q1 = Relation.objects.filter( left__category__name__in=["First"], right__category__name__in=["Second"] ) self.assertSequenceEqual(q1, [rel]) q2 = Category.objects.filter( record__left_set__right__category__name="Second" ).order_by("name") self.assertSequenceEqual(q2, [c1, c2]) p = Parent.objects.create(name="Parent") c = Child.objects.create(name="Child", parent=p) msg = 'Cannot assign "%r": "Child.parent" must be a "Parent" instance.' % c with self.assertRaisesMessage(ValueError, msg): Child.objects.create(name="Grandchild", parent=c) def test_fk_instantiation_outside_model(self): # Regression for #12190 -- Should be able to instantiate a FK outside # of a model, and interrogate its related field. cat = models.ForeignKey(Category, models.CASCADE) self.assertEqual("id", cat.remote_field.get_related_field().name) def test_relation_unsaved(self): Third.objects.create(name="Third 1") Third.objects.create(name="Third 2") th = Third(name="testing") # The object isn't saved and the relation cannot be used. msg = ( "'Third' instance needs to have a primary key value before this " "relationship can be used." ) with self.assertRaisesMessage(ValueError, msg): th.child_set.count() th.save() # Now the model is saved, so we will need to execute a query. with self.assertNumQueries(1): self.assertEqual(th.child_set.count(), 0) def test_related_object(self): public_school = School.objects.create(is_public=True) public_student = Student.objects.create(school=public_school) private_school = School.objects.create(is_public=False) private_student = Student.objects.create(school=private_school) # Only one school is available via all() due to the custom default manager. self.assertSequenceEqual(School.objects.all(), [public_school]) self.assertEqual(public_student.school, public_school) # Make sure the base manager is used so that a student can still access # its related school even if the default manager doesn't normally # allow it. self.assertEqual(private_student.school, private_school) School._meta.base_manager_name = "objects" School._meta._expire_cache() try: private_student = Student.objects.get(pk=private_student.pk) with self.assertRaises(School.DoesNotExist): private_student.school finally: School._meta.base_manager_name = None School._meta._expire_cache() def test_hasattr_related_object(self): # The exception raised on attribute access when a related object # doesn't exist should be an instance of a subclass of `AttributeError` # refs #21563 self.assertFalse(hasattr(Article(), "reporter")) def test_clear_after_prefetch(self): c = City.objects.create(name="Musical City") d = District.objects.create(name="Ladida", city=c) city = City.objects.prefetch_related("districts").get(id=c.id) self.assertSequenceEqual(city.districts.all(), [d]) city.districts.clear() self.assertSequenceEqual(city.districts.all(), []) def test_remove_after_prefetch(self): c = City.objects.create(name="Musical City") d = District.objects.create(name="Ladida", city=c) city = City.objects.prefetch_related("districts").get(id=c.id) self.assertSequenceEqual(city.districts.all(), [d]) city.districts.remove(d) self.assertSequenceEqual(city.districts.all(), []) def test_add_after_prefetch(self): c = City.objects.create(name="Musical City") District.objects.create(name="Ladida", city=c) d2 = District.objects.create(name="Ladidu") city = City.objects.prefetch_related("districts").get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.add(d2) self.assertEqual(city.districts.count(), 2) def test_set_after_prefetch(self): c = City.objects.create(name="Musical City") District.objects.create(name="Ladida", city=c) d2 = District.objects.create(name="Ladidu") city = City.objects.prefetch_related("districts").get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.set([d2]) self.assertSequenceEqual(city.districts.all(), [d2]) def test_add_then_remove_after_prefetch(self): c = City.objects.create(name="Musical City") District.objects.create(name="Ladida", city=c) d2 = District.objects.create(name="Ladidu") city = City.objects.prefetch_related("districts").get(id=c.id) self.assertEqual(city.districts.count(), 1) city.districts.add(d2) self.assertEqual(city.districts.count(), 2) city.districts.remove(d2) self.assertEqual(city.districts.count(), 1) def test_cached_relation_invalidated_on_save(self): """ Model.save() invalidates stale ForeignKey relations after a primary key assignment. """ self.assertEqual(self.a.reporter, self.r) # caches a.reporter self.a.reporter_id = self.r2.pk self.a.save() self.assertEqual(self.a.reporter, self.r2) def test_cached_foreign_key_with_to_field_not_cleared_by_save(self): parent = Parent.objects.create(name="a") child = ToFieldChild.objects.create(parent=parent) with self.assertNumQueries(0): self.assertIs(child.parent, parent) def test_reverse_foreign_key_instance_to_field_caching(self): parent = Parent.objects.create(name="a") ToFieldChild.objects.create(parent=parent) child = parent.to_field_children.get() with self.assertNumQueries(0): self.assertIs(child.parent, parent) def test_add_remove_set_by_pk_raises(self): usa = Country.objects.create(name="United States") chicago = City.objects.create(name="Chicago") msg = "'City' instance expected, got %s" % chicago.pk with self.assertRaisesMessage(TypeError, msg): usa.cities.add(chicago.pk) with self.assertRaisesMessage(TypeError, msg): usa.cities.remove(chicago.pk) with self.assertRaisesMessage(TypeError, msg): usa.cities.set([chicago.pk])
ce18aa8bc3250e1f17344a78f3f8eb15d81939f947208e6227b113cfa4a77147
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): @wraps(func) def wrapper(arg): return func("test:" + arg) return 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 wrapper(): return f() and self.myattr return update_wrapper(wrapper, 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")
de53a9be94d4b57f38e8a7e07cfe973c9c1551d1ff51be7d1d56b3a233fd5d05
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) def test_parse_header_with_double_quotes_and_semicolon(self): self.assertEqual( parse_header(b'form-data; name="files"; filename="fo\\"o;bar"'), ("form-data", {"name": b"files", "filename": b'fo"o;bar'}), )
5fe76ebdf5cb69cd0645ff2f77cf920528f5bf21b5521f69b5a7242130631657
import datetime import os from decimal import Decimal from unittest import mock, skipUnless from django import forms from django.core.exceptions import ( NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError, ) from django.core.files.uploadedfile import SimpleUploadedFile from django.db import connection, models from django.db.models.query import EmptyQuerySet from django.forms.models import ( ModelFormMetaclass, construct_instance, fields_for_model, model_to_dict, modelform_factory, ) from django.template import Context, Template from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature from django.test.utils import isolate_apps from .models import ( Article, ArticleStatus, Author, Author1, Award, BetterWriter, BigInt, Book, Category, Character, Colour, ColourfulItem, CustomErrorMessage, CustomFF, CustomFieldForExclusionModel, DateTimePost, DerivedBook, DerivedPost, Dice, Document, ExplicitPK, FilePathModel, FlexibleDatePost, Homepage, ImprovedArticle, ImprovedArticleWithParentLink, Inventory, NullableUniqueCharFieldModel, Number, Person, Photo, Post, Price, Product, Publication, PublicationDefaults, StrictAssignmentAll, StrictAssignmentFieldSpecific, Student, StumpJoke, TextFile, Triple, Writer, WriterProfile, test_images, ) if test_images: from .models import ImageFile, NoExtensionImageFile, OptionalImageFile class ImageFileForm(forms.ModelForm): class Meta: model = ImageFile fields = "__all__" class OptionalImageFileForm(forms.ModelForm): class Meta: model = OptionalImageFile fields = "__all__" class NoExtensionImageFileForm(forms.ModelForm): class Meta: model = NoExtensionImageFile fields = "__all__" class ProductForm(forms.ModelForm): class Meta: model = Product fields = "__all__" class PriceForm(forms.ModelForm): class Meta: model = Price fields = "__all__" class BookForm(forms.ModelForm): class Meta: model = Book fields = "__all__" class DerivedBookForm(forms.ModelForm): class Meta: model = DerivedBook fields = "__all__" class ExplicitPKForm(forms.ModelForm): class Meta: model = ExplicitPK fields = ( "key", "desc", ) class PostForm(forms.ModelForm): class Meta: model = Post fields = "__all__" class DerivedPostForm(forms.ModelForm): class Meta: model = DerivedPost fields = "__all__" class CustomWriterForm(forms.ModelForm): name = forms.CharField(required=False) class Meta: model = Writer fields = "__all__" class BaseCategoryForm(forms.ModelForm): class Meta: model = Category fields = "__all__" class ArticleForm(forms.ModelForm): class Meta: model = Article fields = "__all__" class RoykoForm(forms.ModelForm): class Meta: model = Writer fields = "__all__" class ArticleStatusForm(forms.ModelForm): class Meta: model = ArticleStatus fields = "__all__" class InventoryForm(forms.ModelForm): class Meta: model = Inventory fields = "__all__" class SelectInventoryForm(forms.Form): items = forms.ModelMultipleChoiceField( Inventory.objects.all(), to_field_name="barcode" ) class CustomFieldForExclusionForm(forms.ModelForm): class Meta: model = CustomFieldForExclusionModel fields = ["name", "markup"] class TextFileForm(forms.ModelForm): class Meta: model = TextFile fields = "__all__" class BigIntForm(forms.ModelForm): class Meta: model = BigInt fields = "__all__" class ModelFormWithMedia(forms.ModelForm): class Media: js = ("/some/form/javascript",) css = {"all": ("/some/form/css",)} class Meta: model = TextFile fields = "__all__" class CustomErrorMessageForm(forms.ModelForm): name1 = forms.CharField(error_messages={"invalid": "Form custom error message."}) class Meta: fields = "__all__" model = CustomErrorMessage class ModelFormBaseTest(TestCase): def test_base_form(self): self.assertEqual(list(BaseCategoryForm.base_fields), ["name", "slug", "url"]) def test_no_model_class(self): class NoModelModelForm(forms.ModelForm): pass with self.assertRaisesMessage( ValueError, "ModelForm has no model class specified." ): NoModelModelForm() def test_empty_fields_to_fields_for_model(self): """ An argument of fields=() to fields_for_model should return an empty dictionary """ field_dict = fields_for_model(Person, fields=()) self.assertEqual(len(field_dict), 0) def test_empty_fields_on_modelform(self): """ No fields on a ModelForm should actually result in no fields. """ class EmptyPersonForm(forms.ModelForm): class Meta: model = Person fields = () form = EmptyPersonForm() self.assertEqual(len(form.fields), 0) def test_empty_fields_to_construct_instance(self): """ No fields should be set on a model instance if construct_instance receives fields=(). """ form = modelform_factory(Person, fields="__all__")({"name": "John Doe"}) self.assertTrue(form.is_valid()) instance = construct_instance(form, Person(), fields=()) self.assertEqual(instance.name, "") def test_blank_with_null_foreign_key_field(self): """ #13776 -- ModelForm's with models having a FK set to null=False and required=False should be valid. """ class FormForTestingIsValid(forms.ModelForm): class Meta: model = Student fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["character"].required = False char = Character.objects.create( username="user", last_action=datetime.datetime.today() ) data = {"study": "Engineering"} data2 = {"study": "Engineering", "character": char.pk} # form is valid because required=False for field 'character' f1 = FormForTestingIsValid(data) self.assertTrue(f1.is_valid()) f2 = FormForTestingIsValid(data2) self.assertTrue(f2.is_valid()) obj = f2.save() self.assertEqual(obj.character, char) def test_blank_false_with_null_true_foreign_key_field(self): """ A ModelForm with a model having ForeignKey(blank=False, null=True) and the form field set to required=False should allow the field to be unset. """ class AwardForm(forms.ModelForm): class Meta: model = Award fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["character"].required = False character = Character.objects.create( username="user", last_action=datetime.datetime.today() ) award = Award.objects.create(name="Best sprinter", character=character) data = {"name": "Best tester", "character": ""} # remove character form = AwardForm(data=data, instance=award) self.assertTrue(form.is_valid()) award = form.save() self.assertIsNone(award.character) def test_blank_foreign_key_with_radio(self): class BookForm(forms.ModelForm): class Meta: model = Book fields = ["author"] widgets = {"author": forms.RadioSelect()} writer = Writer.objects.create(name="Joe Doe") form = BookForm() self.assertEqual( list(form.fields["author"].choices), [ ("", "---------"), (writer.pk, "Joe Doe"), ], ) def test_non_blank_foreign_key_with_radio(self): class AwardForm(forms.ModelForm): class Meta: model = Award fields = ["character"] widgets = {"character": forms.RadioSelect()} character = Character.objects.create( username="user", last_action=datetime.datetime.today(), ) form = AwardForm() self.assertEqual( list(form.fields["character"].choices), [(character.pk, "user")], ) def test_save_blank_false_with_required_false(self): """ A ModelForm with a model with a field set to blank=False and the form field set to required=False should allow the field to be unset. """ obj = Writer.objects.create(name="test") form = CustomWriterForm(data={"name": ""}, instance=obj) self.assertTrue(form.is_valid()) obj = form.save() self.assertEqual(obj.name, "") def test_save_blank_null_unique_charfield_saves_null(self): form_class = modelform_factory( model=NullableUniqueCharFieldModel, fields="__all__" ) empty_value = ( "" if connection.features.interprets_empty_strings_as_nulls else None ) data = { "codename": "", "email": "", "slug": "", "url": "", } form = form_class(data=data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.instance.codename, empty_value) self.assertEqual(form.instance.email, empty_value) self.assertEqual(form.instance.slug, empty_value) self.assertEqual(form.instance.url, empty_value) # Save a second form to verify there isn't a unique constraint violation. form = form_class(data=data) self.assertTrue(form.is_valid()) form.save() self.assertEqual(form.instance.codename, empty_value) self.assertEqual(form.instance.email, empty_value) self.assertEqual(form.instance.slug, empty_value) self.assertEqual(form.instance.url, empty_value) def test_missing_fields_attribute(self): message = ( "Creating a ModelForm without either the 'fields' attribute " "or the 'exclude' attribute is prohibited; form " "MissingFieldsForm needs updating." ) with self.assertRaisesMessage(ImproperlyConfigured, message): class MissingFieldsForm(forms.ModelForm): class Meta: model = Category def test_extra_fields(self): class ExtraFields(BaseCategoryForm): some_extra_field = forms.BooleanField() self.assertEqual( list(ExtraFields.base_fields), ["name", "slug", "url", "some_extra_field"] ) def test_extra_field_model_form(self): with self.assertRaisesMessage(FieldError, "no-field"): class ExtraPersonForm(forms.ModelForm): """ModelForm with an extra field""" age = forms.IntegerField() class Meta: model = Person fields = ("name", "no-field") def test_extra_declared_field_model_form(self): class ExtraPersonForm(forms.ModelForm): """ModelForm with an extra field""" age = forms.IntegerField() class Meta: model = Person fields = ("name", "age") def test_extra_field_modelform_factory(self): with self.assertRaisesMessage( FieldError, "Unknown field(s) (no-field) specified for Person" ): modelform_factory(Person, fields=["no-field", "name"]) def test_replace_field(self): class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = "__all__" self.assertIsInstance( ReplaceField.base_fields["url"], forms.fields.BooleanField ) def test_replace_field_variant_2(self): # Should have the same result as before, # but 'fields' attribute specified differently class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = ["url"] self.assertIsInstance( ReplaceField.base_fields["url"], forms.fields.BooleanField ) def test_replace_field_variant_3(self): # Should have the same result as before, # but 'fields' attribute specified differently class ReplaceField(forms.ModelForm): url = forms.BooleanField() class Meta: model = Category fields = [] # url will still appear, since it is explicit above self.assertIsInstance( ReplaceField.base_fields["url"], forms.fields.BooleanField ) def test_override_field(self): class WriterForm(forms.ModelForm): book = forms.CharField(required=False) class Meta: model = Writer fields = "__all__" wf = WriterForm({"name": "Richard Lockridge"}) self.assertTrue(wf.is_valid()) def test_limit_nonexistent_field(self): expected_msg = "Unknown field(s) (nonexistent) specified for Category" with self.assertRaisesMessage(FieldError, expected_msg): class InvalidCategoryForm(forms.ModelForm): class Meta: model = Category fields = ["nonexistent"] def test_limit_fields_with_string(self): msg = ( "CategoryForm.Meta.fields cannot be a string. Did you mean to type: " "('url',)?" ) with self.assertRaisesMessage(TypeError, msg): class CategoryForm(forms.ModelForm): class Meta: model = Category fields = "url" # note the missing comma def test_exclude_fields(self): class ExcludeFields(forms.ModelForm): class Meta: model = Category exclude = ["url"] self.assertEqual(list(ExcludeFields.base_fields), ["name", "slug"]) def test_exclude_nonexistent_field(self): class ExcludeFields(forms.ModelForm): class Meta: model = Category exclude = ["nonexistent"] self.assertEqual(list(ExcludeFields.base_fields), ["name", "slug", "url"]) def test_exclude_fields_with_string(self): msg = ( "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: " "('url',)?" ) with self.assertRaisesMessage(TypeError, msg): class CategoryForm(forms.ModelForm): class Meta: model = Category exclude = "url" # note the missing comma def test_exclude_and_validation(self): # This Price instance generated by this form is not valid because the quantity # field is required, but the form is valid because the field is excluded from # the form. This is for backwards compatibility. class PriceFormWithoutQuantity(forms.ModelForm): class Meta: model = Price exclude = ("quantity",) form = PriceFormWithoutQuantity({"price": "6.00"}) self.assertTrue(form.is_valid()) price = form.save(commit=False) msg = "{'quantity': ['This field cannot be null.']}" with self.assertRaisesMessage(ValidationError, msg): price.full_clean() # The form should not validate fields that it doesn't contain even if they are # specified using 'fields', not 'exclude'. class PriceFormWithoutQuantity(forms.ModelForm): class Meta: model = Price fields = ("price",) form = PriceFormWithoutQuantity({"price": "6.00"}) self.assertTrue(form.is_valid()) # The form should still have an instance of a model that is not complete and # not saved into a DB yet. self.assertEqual(form.instance.price, Decimal("6.00")) self.assertIsNone(form.instance.quantity) self.assertIsNone(form.instance.pk) def test_confused_form(self): class ConfusedForm(forms.ModelForm): """Using 'fields' *and* 'exclude'. Not sure why you'd want to do this, but uh, "be liberal in what you accept" and all. """ class Meta: model = Category fields = ["name", "url"] exclude = ["url"] self.assertEqual(list(ConfusedForm.base_fields), ["name"]) def test_mixmodel_form(self): class MixModelForm(BaseCategoryForm): """Don't allow more than one 'model' definition in the inheritance hierarchy. Technically, it would generate a valid form, but the fact that the resulting save method won't deal with multiple objects is likely to trip up people not familiar with the mechanics. """ class Meta: model = Article fields = "__all__" # MixModelForm is now an Article-related thing, because MixModelForm.Meta # overrides BaseCategoryForm.Meta. self.assertEqual( list(MixModelForm.base_fields), [ "headline", "slug", "pub_date", "writer", "article", "categories", "status", ], ) def test_article_form(self): self.assertEqual( list(ArticleForm.base_fields), [ "headline", "slug", "pub_date", "writer", "article", "categories", "status", ], ) def test_bad_form(self): # First class with a Meta class wins... class BadForm(ArticleForm, BaseCategoryForm): pass self.assertEqual( list(BadForm.base_fields), [ "headline", "slug", "pub_date", "writer", "article", "categories", "status", ], ) def test_invalid_meta_model(self): class InvalidModelForm(forms.ModelForm): class Meta: pass # no model # Can't create new form msg = "ModelForm has no model class specified." with self.assertRaisesMessage(ValueError, msg): InvalidModelForm() # Even if you provide a model instance with self.assertRaisesMessage(ValueError, msg): InvalidModelForm(instance=Category) def test_subcategory_form(self): class SubCategoryForm(BaseCategoryForm): """Subclassing without specifying a Meta on the class will use the parent's Meta (or the first parent in the MRO if there are multiple parent classes). """ pass self.assertEqual(list(SubCategoryForm.base_fields), ["name", "slug", "url"]) def test_subclassmeta_form(self): class SomeCategoryForm(forms.ModelForm): checkbox = forms.BooleanField() class Meta: model = Category fields = "__all__" class SubclassMeta(SomeCategoryForm): """We can also subclass the Meta inner class to change the fields list. """ class Meta(SomeCategoryForm.Meta): exclude = ["url"] self.assertHTMLEqual( str(SubclassMeta()), '<div><label for="id_name">Name:</label>' '<input type="text" name="name" maxlength="20" required id="id_name">' '</div><div><label for="id_slug">Slug:</label><input type="text" ' 'name="slug" maxlength="20" required id="id_slug"></div><div>' '<label for="id_checkbox">Checkbox:</label>' '<input type="checkbox" name="checkbox" required id="id_checkbox"></div>', ) def test_orderfields_form(self): class OrderFields(forms.ModelForm): class Meta: model = Category fields = ["url", "name"] self.assertEqual(list(OrderFields.base_fields), ["url", "name"]) self.assertHTMLEqual( str(OrderFields()), '<div><label for="id_url">The URL:</label>' '<input type="text" name="url" maxlength="40" required id="id_url">' '</div><div><label for="id_name">Name:</label><input type="text" ' 'name="name" maxlength="20" required id="id_name"></div>', ) def test_orderfields2_form(self): class OrderFields2(forms.ModelForm): class Meta: model = Category fields = ["slug", "url", "name"] exclude = ["url"] self.assertEqual(list(OrderFields2.base_fields), ["slug", "name"]) def test_default_populated_on_optional_field(self): class PubForm(forms.ModelForm): mode = forms.CharField(max_length=255, required=False) class Meta: model = PublicationDefaults fields = ("mode",) # Empty data uses the model field default. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, "di") self.assertEqual(m1._meta.get_field("mode").get_default(), "di") # Blank data doesn't use the model field default. mf2 = PubForm({"mode": ""}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.mode, "") def test_default_not_populated_on_non_empty_value_in_cleaned_data(self): class PubForm(forms.ModelForm): mode = forms.CharField(max_length=255, required=False) mocked_mode = None def clean(self): self.cleaned_data["mode"] = self.mocked_mode return self.cleaned_data class Meta: model = PublicationDefaults fields = ("mode",) pub_form = PubForm({}) pub_form.mocked_mode = "de" pub = pub_form.save(commit=False) self.assertEqual(pub.mode, "de") # Default should be populated on an empty value in cleaned_data. default_mode = "di" for empty_value in pub_form.fields["mode"].empty_values: with self.subTest(empty_value=empty_value): pub_form = PubForm({}) pub_form.mocked_mode = empty_value pub = pub_form.save(commit=False) self.assertEqual(pub.mode, default_mode) def test_default_not_populated_on_optional_checkbox_input(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ("active",) # Empty data doesn't use the model default because CheckboxInput # doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertIs(m1.active, False) self.assertIsInstance(mf1.fields["active"].widget, forms.CheckboxInput) self.assertIs(m1._meta.get_field("active").get_default(), True) def test_default_not_populated_on_checkboxselectmultiple(self): class PubForm(forms.ModelForm): mode = forms.CharField(required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = PublicationDefaults fields = ("mode",) # Empty data doesn't use the model default because an unchecked # CheckboxSelectMultiple doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, "") self.assertEqual(m1._meta.get_field("mode").get_default(), "di") def test_default_not_populated_on_selectmultiple(self): class PubForm(forms.ModelForm): mode = forms.CharField(required=False, widget=forms.SelectMultiple) class Meta: model = PublicationDefaults fields = ("mode",) # Empty data doesn't use the model default because an unselected # SelectMultiple doesn't have a value in HTML form submission. mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, "") self.assertEqual(m1._meta.get_field("mode").get_default(), "di") def test_prefixed_form_with_default_field(self): class PubForm(forms.ModelForm): prefix = "form-prefix" class Meta: model = PublicationDefaults fields = ("mode",) mode = "de" self.assertNotEqual( mode, PublicationDefaults._meta.get_field("mode").get_default() ) mf1 = PubForm({"form-prefix-mode": mode}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.mode, mode) def test_renderer_kwarg(self): custom = object() self.assertIs(ProductForm(renderer=custom).renderer, custom) def test_default_splitdatetime_field(self): class PubForm(forms.ModelForm): datetime_published = forms.SplitDateTimeField(required=False) class Meta: model = PublicationDefaults fields = ("datetime_published",) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.datetime_published, datetime.datetime(2000, 1, 1)) mf2 = PubForm( {"datetime_published_0": "2010-01-01", "datetime_published_1": "0:00:00"} ) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.datetime_published, datetime.datetime(2010, 1, 1)) def test_default_filefield(self): class PubForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ("file",) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.file.name, "default.txt") mf2 = PubForm({}, {"file": SimpleUploadedFile("name", b"foo")}) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.file.name, "name") def test_default_selectdatewidget(self): class PubForm(forms.ModelForm): date_published = forms.DateField( required=False, widget=forms.SelectDateWidget ) class Meta: model = PublicationDefaults fields = ("date_published",) mf1 = PubForm({}) self.assertEqual(mf1.errors, {}) m1 = mf1.save(commit=False) self.assertEqual(m1.date_published, datetime.date.today()) mf2 = PubForm( { "date_published_year": "2010", "date_published_month": "1", "date_published_day": "1", } ) self.assertEqual(mf2.errors, {}) m2 = mf2.save(commit=False) self.assertEqual(m2.date_published, datetime.date(2010, 1, 1)) class FieldOverridesByFormMetaForm(forms.ModelForm): class Meta: model = Category fields = ["name", "url", "slug"] widgets = { "name": forms.Textarea, "url": forms.TextInput(attrs={"class": "url"}), } labels = { "name": "Title", } help_texts = { "slug": "Watch out! Letters, numbers, underscores and hyphens only.", } error_messages = { "slug": { "invalid": ( "Didn't you read the help text? " "We said letters, numbers, underscores and hyphens only!" ) } } field_classes = { "url": forms.URLField, } class TestFieldOverridesByFormMeta(SimpleTestCase): def test_widget_overrides(self): form = FieldOverridesByFormMetaForm() self.assertHTMLEqual( str(form["name"]), '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20" ' "required></textarea>", ) self.assertHTMLEqual( str(form["url"]), '<input id="id_url" type="text" class="url" name="url" maxlength="40" ' "required>", ) self.assertHTMLEqual( str(form["slug"]), '<input id="id_slug" type="text" name="slug" maxlength="20" required>', ) def test_label_overrides(self): form = FieldOverridesByFormMetaForm() self.assertHTMLEqual( str(form["name"].label_tag()), '<label for="id_name">Title:</label>', ) self.assertHTMLEqual( str(form["url"].label_tag()), '<label for="id_url">The URL:</label>', ) self.assertHTMLEqual( str(form["slug"].label_tag()), '<label for="id_slug">Slug:</label>', ) self.assertHTMLEqual( form["name"].legend_tag(), '<legend for="id_name">Title:</legend>', ) self.assertHTMLEqual( form["url"].legend_tag(), '<legend for="id_url">The URL:</legend>', ) self.assertHTMLEqual( form["slug"].legend_tag(), '<legend for="id_slug">Slug:</legend>', ) def test_help_text_overrides(self): form = FieldOverridesByFormMetaForm() self.assertEqual( form["slug"].help_text, "Watch out! Letters, numbers, underscores and hyphens only.", ) def test_error_messages_overrides(self): form = FieldOverridesByFormMetaForm( data={ "name": "Category", "url": "http://www.example.com/category/", "slug": "!%#*@", } ) form.full_clean() error = [ "Didn't you read the help text? " "We said letters, numbers, underscores and hyphens only!", ] self.assertEqual(form.errors, {"slug": error}) def test_field_type_overrides(self): form = FieldOverridesByFormMetaForm() self.assertIs(Category._meta.get_field("url").__class__, models.CharField) self.assertIsInstance(form.fields["url"], forms.URLField) class IncompleteCategoryFormWithFields(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: fields = ("name", "slug") model = Category class IncompleteCategoryFormWithExclude(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should prevent the model field's validation from being called. """ url = forms.CharField(required=False) class Meta: exclude = ["url"] model = Category class ValidationTest(SimpleTestCase): def test_validates_with_replaced_field_not_specified(self): form = IncompleteCategoryFormWithFields( data={"name": "some name", "slug": "some-slug"} ) self.assertIs(form.is_valid(), True) def test_validates_with_replaced_field_excluded(self): form = IncompleteCategoryFormWithExclude( data={"name": "some name", "slug": "some-slug"} ) self.assertIs(form.is_valid(), True) def test_notrequired_overrides_notblank(self): form = CustomWriterForm({}) self.assertIs(form.is_valid(), True) class UniqueTest(TestCase): """ unique/unique_together validation. """ @classmethod def setUpTestData(cls): cls.writer = Writer.objects.create(name="Mike Royko") def test_simple_unique(self): form = ProductForm({"slug": "teddy-bear-blue"}) self.assertTrue(form.is_valid()) obj = form.save() form = ProductForm({"slug": "teddy-bear-blue"}) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["slug"], ["Product with this Slug already exists."] ) form = ProductForm({"slug": "teddy-bear-blue"}, instance=obj) self.assertTrue(form.is_valid()) def test_unique_together(self): """ModelForm test of unique_together constraint""" form = PriceForm({"price": "6.00", "quantity": "1"}) self.assertTrue(form.is_valid()) form.save() form = PriceForm({"price": "6.00", "quantity": "1"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["__all__"], ["Price with this Price and Quantity already exists."], ) def test_unique_together_exclusion(self): """ Forms don't validate unique_together constraints when only part of the constraint is included in the form's fields. This allows using form.save(commit=False) and then assigning the missing field(s) to the model instance. """ class BookForm(forms.ModelForm): class Meta: model = DerivedBook fields = ("isbn", "suffix1") # The unique_together is on suffix1/suffix2 but only suffix1 is part # of the form. The fields must have defaults, otherwise they'll be # skipped by other logic. self.assertEqual(DerivedBook._meta.unique_together, (("suffix1", "suffix2"),)) for name in ("suffix1", "suffix2"): with self.subTest(name=name): field = DerivedBook._meta.get_field(name) self.assertEqual(field.default, 0) # The form fails validation with "Derived book with this Suffix1 and # Suffix2 already exists." if the unique_together validation isn't # skipped. DerivedBook.objects.create(isbn="12345") form = BookForm({"isbn": "56789", "suffix1": "0"}) self.assertTrue(form.is_valid(), form.errors) def test_multiple_field_unique_together(self): """ When the same field is involved in multiple unique_together constraints, we need to make sure we don't remove the data for it before doing all the validation checking (not just failing after the first one). """ class TripleForm(forms.ModelForm): class Meta: model = Triple fields = "__all__" Triple.objects.create(left=1, middle=2, right=3) form = TripleForm({"left": "1", "middle": "2", "right": "3"}) self.assertFalse(form.is_valid()) form = TripleForm({"left": "1", "middle": "3", "right": "1"}) self.assertTrue(form.is_valid()) @skipUnlessDBFeature("supports_nullable_unique_constraints") def test_unique_null(self): title = "I May Be Wrong But I Doubt It" form = BookForm({"title": title, "author": self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = BookForm({"title": title, "author": self.writer.pk}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["__all__"], ["Book with this Title and Author already exists."] ) form = BookForm({"title": title}) self.assertTrue(form.is_valid()) form.save() form = BookForm({"title": title}) self.assertTrue(form.is_valid()) def test_inherited_unique(self): title = "Boss" Book.objects.create(title=title, author=self.writer, special_id=1) form = DerivedBookForm( { "title": "Other", "author": self.writer.pk, "special_id": "1", "isbn": "12345", } ) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["special_id"], ["Book with this Special id already exists."] ) def test_inherited_unique_together(self): title = "Boss" form = BookForm({"title": title, "author": self.writer.pk}) self.assertTrue(form.is_valid()) form.save() form = DerivedBookForm( {"title": title, "author": self.writer.pk, "isbn": "12345"} ) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["__all__"], ["Book with this Title and Author already exists."] ) def test_abstract_inherited_unique(self): title = "Boss" isbn = "12345" DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm( { "title": "Other", "author": self.writer.pk, "isbn": isbn, "suffix1": "1", "suffix2": "2", } ) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["isbn"], ["Derived book with this Isbn already exists."] ) def test_abstract_inherited_unique_together(self): title = "Boss" isbn = "12345" DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) form = DerivedBookForm( { "title": "Other", "author": self.writer.pk, "isbn": "9876", "suffix1": "0", "suffix2": "0", } ) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["__all__"], ["Derived book with this Suffix1 and Suffix2 already exists."], ) def test_explicitpk_unspecified(self): """Test for primary_key being in the form and failing validation.""" form = ExplicitPKForm({"key": "", "desc": ""}) self.assertFalse(form.is_valid()) def test_explicitpk_unique(self): """Ensure keys and blank character strings are tested for uniqueness.""" form = ExplicitPKForm({"key": "key1", "desc": ""}) self.assertTrue(form.is_valid()) form.save() form = ExplicitPKForm({"key": "key1", "desc": ""}) self.assertFalse(form.is_valid()) if connection.features.interprets_empty_strings_as_nulls: self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["key"], ["Explicit pk with this Key already exists."] ) else: self.assertEqual(len(form.errors), 3) self.assertEqual( form.errors["__all__"], ["Explicit pk with this Key and Desc already exists."], ) self.assertEqual( form.errors["desc"], ["Explicit pk with this Desc already exists."] ) self.assertEqual( form.errors["key"], ["Explicit pk with this Key already exists."] ) def test_unique_for_date(self): p = Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = PostForm({"title": "Django 1.0 is released", "posted": "2008-09-03"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["title"], ["Title must be unique for Posted date."] ) form = PostForm({"title": "Work on Django 1.1 begins", "posted": "2008-09-03"}) self.assertTrue(form.is_valid()) form = PostForm({"title": "Django 1.0 is released", "posted": "2008-09-04"}) self.assertTrue(form.is_valid()) form = PostForm({"slug": "Django 1.0", "posted": "2008-01-01"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors["slug"], ["Slug must be unique for Posted year."]) form = PostForm({"subtitle": "Finally", "posted": "2008-09-30"}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors["subtitle"], ["Subtitle must be unique for Posted month."] ) data = { "subtitle": "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", "posted": "2008-09-03", } form = PostForm(data, instance=p) self.assertTrue(form.is_valid()) form = PostForm({"title": "Django 1.0 is released"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors["posted"], ["This field is required."]) def test_unique_for_date_in_exclude(self): """ If the date for unique_for_* constraints is excluded from the ModelForm (in this case 'posted' has editable=False, then the constraint should be ignored. """ class DateTimePostForm(forms.ModelForm): class Meta: model = DateTimePost fields = "__all__" DateTimePost.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.datetime(2008, 9, 3, 10, 10, 1), ) # 'title' has unique_for_date='posted' form = DateTimePostForm( {"title": "Django 1.0 is released", "posted": "2008-09-03"} ) self.assertTrue(form.is_valid()) # 'slug' has unique_for_year='posted' form = DateTimePostForm({"slug": "Django 1.0", "posted": "2008-01-01"}) self.assertTrue(form.is_valid()) # 'subtitle' has unique_for_month='posted' form = DateTimePostForm({"subtitle": "Finally", "posted": "2008-09-30"}) self.assertTrue(form.is_valid()) def test_inherited_unique_for_date(self): p = Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = DerivedPostForm( {"title": "Django 1.0 is released", "posted": "2008-09-03"} ) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["title"], ["Title must be unique for Posted date."] ) form = DerivedPostForm( {"title": "Work on Django 1.1 begins", "posted": "2008-09-03"} ) self.assertTrue(form.is_valid()) form = DerivedPostForm( {"title": "Django 1.0 is released", "posted": "2008-09-04"} ) self.assertTrue(form.is_valid()) form = DerivedPostForm({"slug": "Django 1.0", "posted": "2008-01-01"}) self.assertFalse(form.is_valid()) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors["slug"], ["Slug must be unique for Posted year."]) form = DerivedPostForm({"subtitle": "Finally", "posted": "2008-09-30"}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors["subtitle"], ["Subtitle must be unique for Posted month."] ) data = { "subtitle": "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", "posted": "2008-09-03", } form = DerivedPostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_unique_for_date_with_nullable_date(self): class FlexDatePostForm(forms.ModelForm): class Meta: model = FlexibleDatePost fields = "__all__" p = FlexibleDatePost.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = FlexDatePostForm({"title": "Django 1.0 is released"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({"slug": "Django 1.0"}) self.assertTrue(form.is_valid()) form = FlexDatePostForm({"subtitle": "Finally"}) self.assertTrue(form.is_valid()) data = { "subtitle": "Finally", "title": "Django 1.0 is released", "slug": "Django 1.0", } form = FlexDatePostForm(data, instance=p) self.assertTrue(form.is_valid()) def test_override_unique_message(self): class CustomProductForm(ProductForm): class Meta(ProductForm.Meta): error_messages = { "slug": { "unique": "%(model_name)s's %(field_label)s not unique.", } } Product.objects.create(slug="teddy-bear-blue") form = CustomProductForm({"slug": "teddy-bear-blue"}) self.assertEqual(len(form.errors), 1) self.assertEqual(form.errors["slug"], ["Product's Slug not unique."]) def test_override_unique_together_message(self): class CustomPriceForm(PriceForm): class Meta(PriceForm.Meta): error_messages = { NON_FIELD_ERRORS: { "unique_together": ( "%(model_name)s's %(field_labels)s not unique." ), } } Price.objects.create(price=6.00, quantity=1) form = CustomPriceForm({"price": "6.00", "quantity": "1"}) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors[NON_FIELD_ERRORS], ["Price's Price and Quantity not unique."] ) def test_override_unique_for_date_message(self): class CustomPostForm(PostForm): class Meta(PostForm.Meta): error_messages = { "title": { "unique_for_date": ( "%(model_name)s's %(field_label)s not unique " "for %(date_field_label)s date." ), } } Post.objects.create( title="Django 1.0 is released", slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3), ) form = CustomPostForm( {"title": "Django 1.0 is released", "posted": "2008-09-03"} ) self.assertEqual(len(form.errors), 1) self.assertEqual( form.errors["title"], ["Post's Title not unique for Posted date."] ) class ModelFormBasicTests(TestCase): def create_basic_data(self): self.c1 = Category.objects.create( name="Entertainment", slug="entertainment", url="entertainment" ) self.c2 = Category.objects.create( name="It's a test", slug="its-test", url="test" ) self.c3 = Category.objects.create( name="Third test", slug="third-test", url="third" ) self.w_royko = Writer.objects.create(name="Mike Royko") self.w_woodward = Writer.objects.create(name="Bob Woodward") def test_base_form(self): self.assertEqual(Category.objects.count(), 0) f = BaseCategoryForm() self.assertHTMLEqual( str(f), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'maxlength="20" required id="id_name"></div><div><label for="id_slug">Slug:' '</label><input type="text" name="slug" maxlength="20" required ' 'id="id_slug"></div><div><label for="id_url">The URL:</label>' '<input type="text" name="url" maxlength="40" required id="id_url"></div>', ) self.assertHTMLEqual( str(f.as_ul()), """ <li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" required></li> <li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" required></li> <li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" required></li> """, ) self.assertHTMLEqual( str(f["name"]), """<input id="id_name" type="text" name="name" maxlength="20" required>""", ) def test_auto_id(self): f = BaseCategoryForm(auto_id=False) self.assertHTMLEqual( str(f.as_ul()), """<li>Name: <input type="text" name="name" maxlength="20" required></li> <li>Slug: <input type="text" name="slug" maxlength="20" required></li> <li>The URL: <input type="text" name="url" maxlength="40" required></li>""", ) def test_initial_values(self): self.create_basic_data() # Initial values can be provided for model forms f = ArticleForm( auto_id=False, initial={ "headline": "Your headline here", "categories": [str(self.c1.id), str(self.c2.id)], }, ) self.assertHTMLEqual( f.as_ul(), """ <li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" required> </li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s" selected>Entertainment</option> <option value="%s" selected>It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li> """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) # When the ModelForm is passed an instance, that instance's current values are # inserted as 'initial' data in each Field. f = RoykoForm(auto_id=False, instance=self.w_royko) self.assertHTMLEqual( str(f), '<div>Name:<div class="helptext">Use both first and last names.</div>' '<input type="text" name="name" value="Mike Royko" maxlength="50" ' "required></div>", ) art = Article.objects.create( headline="Test article", slug="test-article", pub_date=datetime.date(1988, 1, 4), writer=self.w_royko, article="Hello.", ) art_id_1 = art.id f = ArticleForm(auto_id=False, instance=art) self.assertHTMLEqual( f.as_ul(), """ <li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" required> </li> <li>Slug: <input type="text" name="slug" value="test-article" maxlength="50" required> </li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> <li>Writer: <select name="writer" required> <option value="">---------</option> <option value="%s">Bob Woodward</option> <option value="%s" selected>Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li> """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) f = ArticleForm( { "headline": "Test headline", "slug": "test-headline", "pub_date": "1984-02-06", "writer": str(self.w_royko.pk), "article": "Hello.", }, instance=art, ) self.assertEqual(f.errors, {}) self.assertTrue(f.is_valid()) test_art = f.save() self.assertEqual(test_art.id, art_id_1) test_art = Article.objects.get(id=art_id_1) self.assertEqual(test_art.headline, "Test headline") def test_m2m_initial_callable(self): """ A callable can be provided as the initial value for an m2m field. """ self.maxDiff = 1200 self.create_basic_data() # Set up a callable initial value def formfield_for_dbfield(db_field, **kwargs): if db_field.name == "categories": kwargs["initial"] = lambda: Category.objects.order_by("name")[:2] return db_field.formfield(**kwargs) # Create a ModelForm, instantiate it, and check that the output is as expected ModelForm = modelform_factory( Article, fields=["headline", "categories"], formfield_callback=formfield_for_dbfield, ) form = ModelForm() self.assertHTMLEqual( form.as_ul(), """<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="50" required></li> <li><label for="id_categories">Categories:</label> <select multiple name="categories" id="id_categories"> <option value="%d" selected>Entertainment</option> <option value="%d" selected>It&#x27;s a test</option> <option value="%d">Third test</option> </select></li>""" % (self.c1.pk, self.c2.pk, self.c3.pk), ) def test_basic_creation(self): self.assertEqual(Category.objects.count(), 0) f = BaseCategoryForm( { "name": "Entertainment", "slug": "entertainment", "url": "entertainment", } ) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["name"], "Entertainment") self.assertEqual(f.cleaned_data["slug"], "entertainment") self.assertEqual(f.cleaned_data["url"], "entertainment") c1 = f.save() # Testing whether the same object is returned from the # ORM... not the fastest way... self.assertEqual(Category.objects.count(), 1) self.assertEqual(c1, Category.objects.all()[0]) self.assertEqual(c1.name, "Entertainment") def test_save_commit_false(self): # If you call save() with commit=False, then it will return an object that # hasn't yet been saved to the database. In this case, it's up to you to call # save() on the resulting model instance. f = BaseCategoryForm( {"name": "Third test", "slug": "third-test", "url": "third"} ) self.assertTrue(f.is_valid()) c1 = f.save(commit=False) self.assertEqual(c1.name, "Third test") self.assertEqual(Category.objects.count(), 0) c1.save() self.assertEqual(Category.objects.count(), 1) def test_save_with_data_errors(self): # If you call save() with invalid data, you'll get a ValueError. f = BaseCategoryForm({"name": "", "slug": "not a slug!", "url": "foo"}) self.assertEqual(f.errors["name"], ["This field is required."]) self.assertEqual( f.errors["slug"], [ "Enter a valid “slug” consisting of letters, numbers, underscores or " "hyphens." ], ) self.assertEqual(f.cleaned_data, {"url": "foo"}) msg = "The Category could not be created because the data didn't validate." with self.assertRaisesMessage(ValueError, msg): f.save() f = BaseCategoryForm({"name": "", "slug": "", "url": "foo"}) with self.assertRaisesMessage(ValueError, msg): f.save() def test_multi_fields(self): self.create_basic_data() self.maxDiff = None # ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any # fields with the 'choices' attribute are represented by a ChoiceField. f = ArticleForm(auto_id=False) self.assertHTMLEqual( str(f), """ <div>Headline: <input type="text" name="headline" maxlength="50" required> </div> <div>Slug: <input type="text" name="slug" maxlength="50" required> </div> <div>Pub date: <input type="text" name="pub_date" required> </div> <div>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select> </div> <div>Article: <textarea name="article" cols="40" rows="10" required></textarea> </div> <div>Categories: <select name="categories" multiple> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select> </div> <div>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option><option value="2">Pending</option> <option value="3">Live</option> </select> </div> """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) # Add some categories and test the many-to-many form output. new_art = Article.objects.create( article="Hello.", headline="New headline", slug="new-headline", pub_date=datetime.date(1988, 1, 4), writer=self.w_royko, ) new_art.categories.add(Category.objects.get(name="Entertainment")) self.assertSequenceEqual(new_art.categories.all(), [self.c1]) f = ArticleForm(auto_id=False, instance=new_art) self.assertHTMLEqual( f.as_ul(), """ <li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required> </li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required> </li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> <li>Writer: <select name="writer" required> <option value="">---------</option> <option value="%s">Bob Woodward</option> <option value="%s" selected>Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required>Hello.</textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s" selected>Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li> """ % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) def test_subset_fields(self): # You can restrict a form to a subset of the complete list of fields # by providing a 'fields' argument. If you try to save a # model created with such a form, you need to ensure that the fields # that are _not_ on the form have default values, or are allowed to have # a value of None. If a field isn't specified on a form, the object created # from the form can't provide a value for that field! class PartialArticleForm(forms.ModelForm): class Meta: model = Article fields = ("headline", "pub_date") f = PartialArticleForm(auto_id=False) self.assertHTMLEqual( str(f), '<div>Headline:<input type="text" name="headline" maxlength="50" required>' '</div><div>Pub date:<input type="text" name="pub_date" required></div>', ) class PartialArticleFormWithSlug(forms.ModelForm): class Meta: model = Article fields = ("headline", "slug", "pub_date") w_royko = Writer.objects.create(name="Mike Royko") art = Article.objects.create( article="Hello.", headline="New headline", slug="new-headline", pub_date=datetime.date(1988, 1, 4), writer=w_royko, ) f = PartialArticleFormWithSlug( { "headline": "New headline", "slug": "new-headline", "pub_date": "1988-01-04", }, auto_id=False, instance=art, ) self.assertHTMLEqual( f.as_ul(), """ <li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" required> </li> <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" required> </li> <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" required></li> """, ) self.assertTrue(f.is_valid()) new_art = f.save() self.assertEqual(new_art.id, art.id) new_art = Article.objects.get(id=art.id) self.assertEqual(new_art.headline, "New headline") def test_m2m_editing(self): self.create_basic_data() form_data = { "headline": "New headline", "slug": "new-headline", "pub_date": "1988-01-04", "writer": str(self.w_royko.pk), "article": "Hello.", "categories": [str(self.c1.id), str(self.c2.id)], } # Create a new article, with categories, via the form. f = ArticleForm(form_data) new_art = f.save() new_art = Article.objects.get(id=new_art.id) art_id_1 = new_art.id self.assertSequenceEqual( new_art.categories.order_by("name"), [self.c1, self.c2] ) # Now, submit form data with no categories. This deletes the existing # categories. form_data["categories"] = [] f = ArticleForm(form_data, instance=new_art) new_art = f.save() self.assertEqual(new_art.id, art_id_1) new_art = Article.objects.get(id=art_id_1) self.assertSequenceEqual(new_art.categories.all(), []) # Create a new article, with no categories, via the form. f = ArticleForm(form_data) new_art = f.save() art_id_2 = new_art.id self.assertNotIn(art_id_2, (None, art_id_1)) new_art = Article.objects.get(id=art_id_2) self.assertSequenceEqual(new_art.categories.all(), []) # Create a new article, with categories, via the form, but use commit=False. # The m2m data won't be saved until save_m2m() is invoked on the form. form_data["categories"] = [str(self.c1.id), str(self.c2.id)] f = ArticleForm(form_data) new_art = f.save(commit=False) # Manually save the instance new_art.save() art_id_3 = new_art.id self.assertNotIn(art_id_3, (None, art_id_1, art_id_2)) # The instance doesn't have m2m data yet new_art = Article.objects.get(id=art_id_3) self.assertSequenceEqual(new_art.categories.all(), []) # Save the m2m data on the form f.save_m2m() self.assertSequenceEqual( new_art.categories.order_by("name"), [self.c1, self.c2] ) def test_custom_form_fields(self): # Here, we define a custom ModelForm. Because it happens to have the # same fields as the Category model, we can just call the form's save() # to apply its changes to an existing Category instance. class ShortCategory(forms.ModelForm): name = forms.CharField(max_length=5) slug = forms.CharField(max_length=5) url = forms.CharField(max_length=3) class Meta: model = Category fields = "__all__" cat = Category.objects.create(name="Third test") form = ShortCategory( {"name": "Third", "slug": "third", "url": "3rd"}, instance=cat ) self.assertEqual(form.save().name, "Third") self.assertEqual(Category.objects.get(id=cat.id).name, "Third") def test_runtime_choicefield_populated(self): self.maxDiff = None # Here, we demonstrate that choices for a ForeignKey ChoiceField are determined # at runtime, based on the data in the database when the form is displayed, not # the data in the database when the form is instantiated. self.create_basic_data() f = ArticleForm(auto_id=False) self.assertHTMLEqual( f.as_ul(), """<li>Headline: <input type="text" name="headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> </select> </li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>""" % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk), ) c4 = Category.objects.create(name="Fourth", url="4th") w_bernstein = Writer.objects.create(name="Carl Bernstein") self.assertHTMLEqual( f.as_ul(), """<li>Headline: <input type="text" name="headline" maxlength="50" required></li> <li>Slug: <input type="text" name="slug" maxlength="50" required></li> <li>Pub date: <input type="text" name="pub_date" required></li> <li>Writer: <select name="writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Carl Bernstein</option> <option value="%s">Mike Royko</option> </select></li> <li>Article: <textarea rows="10" cols="40" name="article" required></textarea></li> <li>Categories: <select multiple name="categories"> <option value="%s">Entertainment</option> <option value="%s">It&#x27;s a test</option> <option value="%s">Third test</option> <option value="%s">Fourth</option> </select></li> <li>Status: <select name="status"> <option value="" selected>---------</option> <option value="1">Draft</option> <option value="2">Pending</option> <option value="3">Live</option> </select></li>""" % ( self.w_woodward.pk, w_bernstein.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk, c4.pk, ), ) def test_recleaning_model_form_instance(self): """ Re-cleaning an instance that was added via a ModelForm shouldn't raise a pk uniqueness error. """ class AuthorForm(forms.ModelForm): class Meta: model = Author fields = "__all__" form = AuthorForm({"full_name": "Bob"}) self.assertTrue(form.is_valid()) obj = form.save() obj.name = "Alice" obj.full_clean() def test_validate_foreign_key_uses_default_manager(self): class MyForm(forms.ModelForm): class Meta: model = Article fields = "__all__" # Archived writers are filtered out by the default manager. w = Writer.objects.create(name="Randy", archived=True) data = { "headline": "My Article", "slug": "my-article", "pub_date": datetime.date.today(), "writer": w.pk, "article": "lorem ipsum", } form = MyForm(data) self.assertIs(form.is_valid(), False) self.assertEqual( form.errors, { "writer": [ "Select a valid choice. That choice is not one of the available " "choices." ] }, ) def test_validate_foreign_key_to_model_with_overridden_manager(self): class MyForm(forms.ModelForm): class Meta: model = Article fields = "__all__" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Allow archived authors. self.fields["writer"].queryset = Writer._base_manager.all() w = Writer.objects.create(name="Randy", archived=True) data = { "headline": "My Article", "slug": "my-article", "pub_date": datetime.date.today(), "writer": w.pk, "article": "lorem ipsum", } form = MyForm(data) self.assertIs(form.is_valid(), True) article = form.save() self.assertEqual(article.writer, w) class ModelMultipleChoiceFieldTests(TestCase): @classmethod def setUpTestData(cls): cls.c1 = Category.objects.create( name="Entertainment", slug="entertainment", url="entertainment" ) cls.c2 = Category.objects.create( name="It's a test", slug="its-test", url="test" ) cls.c3 = Category.objects.create(name="Third", slug="third-test", url="third") def test_model_multiple_choice_field(self): f = forms.ModelMultipleChoiceField(Category.objects.all()) self.assertCountEqual( list(f.choices), [ (self.c1.pk, "Entertainment"), (self.c2.pk, "It's a test"), (self.c3.pk, "Third"), ], ) with self.assertRaises(ValidationError): f.clean(None) with self.assertRaises(ValidationError): f.clean([]) self.assertCountEqual(f.clean([self.c1.id]), [self.c1]) self.assertCountEqual(f.clean([self.c2.id]), [self.c2]) self.assertCountEqual(f.clean([str(self.c1.id)]), [self.c1]) self.assertCountEqual( f.clean([str(self.c1.id), str(self.c2.id)]), [self.c1, self.c2], ) self.assertCountEqual( f.clean([self.c1.id, str(self.c2.id)]), [self.c1, self.c2], ) self.assertCountEqual( f.clean((self.c1.id, str(self.c2.id))), [self.c1, self.c2], ) with self.assertRaises(ValidationError): f.clean(["0"]) with self.assertRaises(ValidationError): f.clean("hello") with self.assertRaises(ValidationError): f.clean(["fail"]) # Invalid types that require TypeError to be caught (#22808). with self.assertRaises(ValidationError): f.clean([["fail"]]) with self.assertRaises(ValidationError): f.clean([{"foo": "bar"}]) # Add a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. # Note, we are using an id of 1006 here since tests that run before # this may create categories with primary keys up to 6. Use # a number that will not conflict. c6 = Category.objects.create(id=1006, name="Sixth", url="6th") self.assertCountEqual(f.clean([c6.id]), [c6]) # Delete a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. Category.objects.get(url="6th").delete() with self.assertRaises(ValidationError): f.clean([c6.id]) def test_model_multiple_choice_required_false(self): f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False) self.assertIsInstance(f.clean([]), EmptyQuerySet) self.assertIsInstance(f.clean(()), EmptyQuerySet) with self.assertRaises(ValidationError): f.clean(["0"]) with self.assertRaises(ValidationError): f.clean([str(self.c3.id), "0"]) with self.assertRaises(ValidationError): f.clean([str(self.c1.id), "0"]) # queryset can be changed after the field is created. f.queryset = Category.objects.exclude(name="Third") self.assertCountEqual( list(f.choices), [(self.c1.pk, "Entertainment"), (self.c2.pk, "It's a test")], ) self.assertSequenceEqual(f.clean([self.c2.id]), [self.c2]) with self.assertRaises(ValidationError): f.clean([self.c3.id]) with self.assertRaises(ValidationError): f.clean([str(self.c2.id), str(self.c3.id)]) f.queryset = Category.objects.all() f.label_from_instance = lambda obj: "multicategory " + str(obj) self.assertCountEqual( list(f.choices), [ (self.c1.pk, "multicategory Entertainment"), (self.c2.pk, "multicategory It's a test"), (self.c3.pk, "multicategory Third"), ], ) def test_model_multiple_choice_number_of_queries(self): """ ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156). """ persons = [Writer.objects.create(name="Person %s" % i) for i in range(30)] f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all()) self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]]) def test_model_multiple_choice_run_validators(self): """ ModelMultipleChoiceField run given validators (#14144). """ for i in range(30): Writer.objects.create(name="Person %s" % i) self._validator_run = False def my_validator(value): self._validator_run = True f = forms.ModelMultipleChoiceField( queryset=Writer.objects.all(), validators=[my_validator] ) f.clean([p.pk for p in Writer.objects.all()[8:9]]) self.assertTrue(self._validator_run) def test_model_multiple_choice_show_hidden_initial(self): """ Test support of show_hidden_initial by ModelMultipleChoiceField. """ class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField( show_hidden_initial=True, queryset=Writer.objects.all() ) person1 = Writer.objects.create(name="Person 1") person2 = Writer.objects.create(name="Person 2") form = WriterForm( initial={"persons": [person1, person2]}, data={ "initial-persons": [str(person1.pk), str(person2.pk)], "persons": [str(person1.pk), str(person2.pk)], }, ) self.assertTrue(form.is_valid()) self.assertFalse(form.has_changed()) form = WriterForm( initial={"persons": [person1, person2]}, data={ "initial-persons": [str(person1.pk), str(person2.pk)], "persons": [str(person2.pk)], }, ) self.assertTrue(form.is_valid()) self.assertTrue(form.has_changed()) def test_model_multiple_choice_field_22745(self): """ #22745 -- Make sure that ModelMultipleChoiceField with CheckboxSelectMultiple widget doesn't produce unnecessary db queries when accessing its BoundField's attrs. """ class ModelMultipleChoiceForm(forms.Form): categories = forms.ModelMultipleChoiceField( Category.objects.all(), widget=forms.CheckboxSelectMultiple ) form = ModelMultipleChoiceForm() field = form["categories"] # BoundField template = Template("{{ field.name }}{{ field }}{{ field.help_text }}") with self.assertNumQueries(1): template.render(Context({"field": field})) def test_show_hidden_initial_changed_queries_efficiently(self): class WriterForm(forms.Form): persons = forms.ModelMultipleChoiceField( show_hidden_initial=True, queryset=Writer.objects.all() ) writers = (Writer.objects.create(name=str(x)) for x in range(0, 50)) writer_pks = tuple(x.pk for x in writers) form = WriterForm(data={"initial-persons": writer_pks}) with self.assertNumQueries(1): self.assertTrue(form.has_changed()) def test_clean_does_deduplicate_values(self): class PersonForm(forms.Form): persons = forms.ModelMultipleChoiceField(queryset=Person.objects.all()) person1 = Person.objects.create(name="Person 1") form = PersonForm(data={}) queryset = form.fields["persons"].clean([str(person1.pk)] * 50) sql, params = queryset.query.sql_with_params() self.assertEqual(len(params), 1) def test_to_field_name_with_initial_data(self): class ArticleCategoriesForm(forms.ModelForm): categories = forms.ModelMultipleChoiceField( Category.objects.all(), to_field_name="slug" ) class Meta: model = Article fields = ["categories"] article = Article.objects.create( headline="Test article", slug="test-article", pub_date=datetime.date(1988, 1, 4), writer=Writer.objects.create(name="Test writer"), article="Hello.", ) article.categories.add(self.c2, self.c3) form = ArticleCategoriesForm(instance=article) self.assertCountEqual(form["categories"].value(), [self.c2.slug, self.c3.slug]) class ModelOneToOneFieldTests(TestCase): def test_modelform_onetoonefield(self): class ImprovedArticleForm(forms.ModelForm): class Meta: model = ImprovedArticle fields = "__all__" class ImprovedArticleWithParentLinkForm(forms.ModelForm): class Meta: model = ImprovedArticleWithParentLink fields = "__all__" self.assertEqual(list(ImprovedArticleForm.base_fields), ["article"]) self.assertEqual(list(ImprovedArticleWithParentLinkForm.base_fields), []) def test_modelform_subclassed_model(self): class BetterWriterForm(forms.ModelForm): class Meta: # BetterWriter model is a subclass of Writer with an additional # `score` field. model = BetterWriter fields = "__all__" bw = BetterWriter.objects.create(name="Joe Better", score=10) self.assertEqual( sorted(model_to_dict(bw)), ["id", "name", "score", "writer_ptr"] ) self.assertEqual(sorted(model_to_dict(bw, fields=[])), []) self.assertEqual( sorted(model_to_dict(bw, fields=["id", "name"])), ["id", "name"] ) self.assertEqual( sorted(model_to_dict(bw, exclude=[])), ["id", "name", "score", "writer_ptr"] ) self.assertEqual( sorted(model_to_dict(bw, exclude=["id", "name"])), ["score", "writer_ptr"] ) form = BetterWriterForm({"name": "Some Name", "score": 12}) self.assertTrue(form.is_valid()) bw2 = form.save() self.assertEqual(bw2.score, 12) def test_onetoonefield(self): class WriterProfileForm(forms.ModelForm): class Meta: # WriterProfile has a OneToOneField to Writer model = WriterProfile fields = "__all__" self.w_royko = Writer.objects.create(name="Mike Royko") self.w_woodward = Writer.objects.create(name="Bob Woodward") form = WriterProfileForm() self.assertHTMLEqual( form.as_p(), """ <p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required> <option value="" selected>---------</option> <option value="%s">Bob Woodward</option> <option value="%s">Mike Royko</option> </select></p> <p><label for="id_age">Age:</label> <input type="number" name="age" id="id_age" min="0" required></p> """ % ( self.w_woodward.pk, self.w_royko.pk, ), ) data = { "writer": str(self.w_woodward.pk), "age": "65", } form = WriterProfileForm(data) instance = form.save() self.assertEqual(str(instance), "Bob Woodward is 65") form = WriterProfileForm(instance=instance) self.assertHTMLEqual( form.as_p(), """ <p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer" required> <option value="">---------</option> <option value="%s" selected>Bob Woodward</option> <option value="%s">Mike Royko</option> </select></p> <p><label for="id_age">Age:</label> <input type="number" name="age" value="65" id="id_age" min="0" required> </p>""" % ( self.w_woodward.pk, self.w_royko.pk, ), ) def test_assignment_of_none(self): class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ["publication", "full_name"] publication = Publication.objects.create( title="Pravda", date_published=datetime.date(1991, 8, 22) ) author = Author.objects.create(publication=publication, full_name="John Doe") form = AuthorForm({"publication": "", "full_name": "John Doe"}, instance=author) self.assertTrue(form.is_valid()) self.assertIsNone(form.cleaned_data["publication"]) author = form.save() # author object returned from form still retains original publication object # that's why we need to retrieve it from database again new_author = Author.objects.get(pk=author.pk) self.assertIsNone(new_author.publication) def test_assignment_of_none_null_false(self): class AuthorForm(forms.ModelForm): class Meta: model = Author1 fields = ["publication", "full_name"] publication = Publication.objects.create( title="Pravda", date_published=datetime.date(1991, 8, 22) ) author = Author1.objects.create(publication=publication, full_name="John Doe") form = AuthorForm({"publication": "", "full_name": "John Doe"}, instance=author) self.assertFalse(form.is_valid()) class FileAndImageFieldTests(TestCase): def test_clean_false(self): """ If the ``clean`` method on a non-required FileField receives False as the data (meaning clear the field value), it returns False, regardless of the value of ``initial``. """ f = forms.FileField(required=False) self.assertIs(f.clean(False), False) self.assertIs(f.clean(False, "initial"), False) def test_clean_false_required(self): """ If the ``clean`` method on a required FileField receives False as the data, it has the same effect as None: initial is returned if non-empty, otherwise the validation catches the lack of a required value. """ f = forms.FileField(required=True) self.assertEqual(f.clean(False, "initial"), "initial") with self.assertRaises(ValidationError): f.clean(False) def test_full_clear(self): """ Integration happy-path test that a model FileField can actually be set and cleared via a ModelForm. """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = "__all__" form = DocumentForm() self.assertIn('name="myfile"', str(form)) self.assertNotIn("myfile-clear", str(form)) form = DocumentForm( files={"myfile": SimpleUploadedFile("something.txt", b"content")} ) self.assertTrue(form.is_valid()) doc = form.save(commit=False) self.assertEqual(doc.myfile.name, "something.txt") form = DocumentForm(instance=doc) self.assertIn("myfile-clear", str(form)) form = DocumentForm(instance=doc, data={"myfile-clear": "true"}) doc = form.save(commit=False) self.assertFalse(doc.myfile) def test_clear_and_file_contradiction(self): """ If the user submits a new file upload AND checks the clear checkbox, they get a validation error, and the bound redisplay of the form still includes the current file and the clear checkbox. """ class DocumentForm(forms.ModelForm): class Meta: model = Document fields = "__all__" form = DocumentForm( files={"myfile": SimpleUploadedFile("something.txt", b"content")} ) self.assertTrue(form.is_valid()) doc = form.save(commit=False) form = DocumentForm( instance=doc, files={"myfile": SimpleUploadedFile("something.txt", b"content")}, data={"myfile-clear": "true"}, ) self.assertTrue(not form.is_valid()) self.assertEqual( form.errors["myfile"], ["Please either submit a file or check the clear checkbox, not both."], ) rendered = str(form) self.assertIn("something.txt", rendered) self.assertIn("myfile-clear", rendered) def test_render_empty_file_field(self): class DocumentForm(forms.ModelForm): class Meta: model = Document fields = "__all__" doc = Document.objects.create() form = DocumentForm(instance=doc) self.assertHTMLEqual( str(form["myfile"]), '<input id="id_myfile" name="myfile" type="file">' ) def test_file_field_data(self): # Test conditions when files is either not given or empty. f = TextFileForm(data={"description": "Assistance"}) self.assertFalse(f.is_valid()) f = TextFileForm(data={"description": "Assistance"}, files={}) self.assertFalse(f.is_valid()) # Upload a file and ensure it all works as expected. f = TextFileForm( data={"description": "Assistance"}, files={"file": SimpleUploadedFile("test1.txt", b"hello world")}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data["file"]), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.file.name, "tests/test1.txt") instance.file.delete() # If the previous file has been deleted, the file name can be reused f = TextFileForm( data={"description": "Assistance"}, files={"file": SimpleUploadedFile("test1.txt", b"hello world")}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data["file"]), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.file.name, "tests/test1.txt") # Check if the max_length attribute has been inherited from the model. f = TextFileForm( data={"description": "Assistance"}, files={"file": SimpleUploadedFile("test-maxlength.txt", b"hello world")}, ) self.assertFalse(f.is_valid()) # Edit an instance that already has the file defined in the model. This will not # save the file again, but leave it exactly as it is. f = TextFileForm({"description": "Assistance"}, instance=instance) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["file"].name, "tests/test1.txt") instance = f.save() self.assertEqual(instance.file.name, "tests/test1.txt") # Delete the current file since this is not done by Django. instance.file.delete() # Override the file by uploading a new one. f = TextFileForm( data={"description": "Assistance"}, files={"file": SimpleUploadedFile("test2.txt", b"hello world")}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, "tests/test2.txt") # Delete the current file since this is not done by Django. instance.file.delete() instance.delete() def test_filefield_required_false(self): # Test the non-required FileField f = TextFileForm(data={"description": "Assistance"}) f.fields["file"].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, "") f = TextFileForm( data={"description": "Assistance"}, files={"file": SimpleUploadedFile("test3.txt", b"hello world")}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.file.name, "tests/test3.txt") # Instance can be edited w/out re-uploading the file and existing file # should be preserved. f = TextFileForm({"description": "New Description"}, instance=instance) f.fields["file"].required = False self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, "New Description") self.assertEqual(instance.file.name, "tests/test3.txt") # Delete the current file since this is not done by Django. instance.file.delete() instance.delete() def test_custom_file_field_save(self): """ Regression for #11149: save_form_data should be called only once """ class CFFForm(forms.ModelForm): class Meta: model = CustomFF fields = "__all__" # It's enough that the form saves without error -- the custom save routine will # generate an AssertionError if it is called more than once during save. form = CFFForm(data={"f": None}) form.save() def test_file_field_multiple_save(self): """ Simulate a file upload and check how many times Model.save() gets called. Test for bug #639. """ class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = "__all__" # Grab an image for testing. filename = os.path.join(os.path.dirname(__file__), "test.png") with open(filename, "rb") as fp: img = fp.read() # Fake a POST QueryDict and FILES MultiValueDict. data = {"title": "Testing"} files = {"image": SimpleUploadedFile("test.png", img, "image/png")} form = PhotoForm(data=data, files=files) p = form.save() try: # Check the savecount stored on the object (see the model). self.assertEqual(p._savecount, 1) finally: # Delete the "uploaded" file to avoid clogging /tmp. p = Photo.objects.get() p.image.delete(save=False) def test_file_path_field_blank(self): """FilePathField(blank=True) includes the empty option.""" class FPForm(forms.ModelForm): class Meta: model = FilePathModel fields = "__all__" form = FPForm() self.assertEqual( [name for _, name in form["path"].field.choices], ["---------", "models.py"] ) @skipUnless(test_images, "Pillow not installed") def test_image_field(self): # ImageField and FileField are nearly identical, but they differ slightly when # it comes to validation. This specifically tests that #6302 is fixed for # both file fields and image fields. with open(os.path.join(os.path.dirname(__file__), "test.png"), "rb") as fp: image_data = fp.read() with open(os.path.join(os.path.dirname(__file__), "test2.png"), "rb") as fp: image_data2 = fp.read() f = ImageFileForm( data={"description": "An image"}, files={"image": SimpleUploadedFile("test.png", image_data)}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data["image"]), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.image.name, "tests/test.png") self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) f = ImageFileForm( data={"description": "An image"}, files={"image": SimpleUploadedFile("test.png", image_data)}, ) self.assertTrue(f.is_valid()) self.assertEqual(type(f.cleaned_data["image"]), SimpleUploadedFile) instance = f.save() self.assertEqual(instance.image.name, "tests/test.png") self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Edit an instance that already has the (required) image defined in the # model. This will not save the image again, but leave it exactly as it # is. f = ImageFileForm(data={"description": "Look, it changed"}, instance=instance) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["image"].name, "tests/test.png") instance = f.save() self.assertEqual(instance.image.name, "tests/test.png") self.assertEqual(instance.height, 16) self.assertEqual(instance.width, 16) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) # Override the file by uploading a new one. f = ImageFileForm( data={"description": "Changed it"}, files={"image": SimpleUploadedFile("test2.png", image_data2)}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "tests/test2.png") self.assertEqual(instance.height, 32) self.assertEqual(instance.width, 48) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) instance.delete() f = ImageFileForm( data={"description": "Changed it"}, files={"image": SimpleUploadedFile("test2.png", image_data2)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "tests/test2.png") self.assertEqual(instance.height, 32) self.assertEqual(instance.width, 48) # Delete the current file since this is not done by Django, but don't save # because the dimension fields are not null=True. instance.image.delete(save=False) instance.delete() # Test the non-required ImageField # Note: In Oracle, we expect a null ImageField to return '' instead of # None. if connection.features.interprets_empty_strings_as_nulls: expected_null_imagefield_repr = "" else: expected_null_imagefield_repr = None f = OptionalImageFileForm(data={"description": "Test"}) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, expected_null_imagefield_repr) self.assertIsNone(instance.width) self.assertIsNone(instance.height) f = OptionalImageFileForm( data={"description": "And a final one"}, files={"image": SimpleUploadedFile("test3.png", image_data)}, instance=instance, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "tests/test3.png") self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Editing the instance without re-uploading the image should not affect # the image or its width/height properties. f = OptionalImageFileForm({"description": "New Description"}, instance=instance) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.description, "New Description") self.assertEqual(instance.image.name, "tests/test3.png") self.assertEqual(instance.width, 16) self.assertEqual(instance.height, 16) # Delete the current file since this is not done by Django. instance.image.delete() instance.delete() f = OptionalImageFileForm( data={"description": "And a final one"}, files={"image": SimpleUploadedFile("test4.png", image_data2)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "tests/test4.png") self.assertEqual(instance.width, 48) self.assertEqual(instance.height, 32) instance.delete() # Callable upload_to behavior that's dependent on the value of another # field in the model. f = ImageFileForm( data={"description": "And a final one", "path": "foo"}, files={"image": SimpleUploadedFile("test4.png", image_data)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "foo/test4.png") instance.delete() # Editing an instance that has an image without an extension shouldn't # fail validation. First create: f = NoExtensionImageFileForm( data={"description": "An image"}, files={"image": SimpleUploadedFile("test.png", image_data)}, ) self.assertTrue(f.is_valid()) instance = f.save() self.assertEqual(instance.image.name, "tests/no_extension") # Then edit: f = NoExtensionImageFileForm( data={"description": "Edited image"}, instance=instance ) self.assertTrue(f.is_valid()) class ModelOtherFieldTests(SimpleTestCase): def test_big_integer_field(self): bif = BigIntForm({"biggie": "-9223372036854775808"}) self.assertTrue(bif.is_valid()) bif = BigIntForm({"biggie": "-9223372036854775809"}) self.assertFalse(bif.is_valid()) self.assertEqual( bif.errors, { "biggie": [ "Ensure this value is greater than or equal to " "-9223372036854775808." ] }, ) bif = BigIntForm({"biggie": "9223372036854775807"}) self.assertTrue(bif.is_valid()) bif = BigIntForm({"biggie": "9223372036854775808"}) self.assertFalse(bif.is_valid()) self.assertEqual( bif.errors, { "biggie": [ "Ensure this value is less than or equal to 9223372036854775807." ] }, ) def test_url_on_modelform(self): "Check basic URL field validation on model forms" class HomepageForm(forms.ModelForm): class Meta: model = Homepage fields = "__all__" self.assertFalse(HomepageForm({"url": "foo"}).is_valid()) self.assertFalse(HomepageForm({"url": "http://"}).is_valid()) self.assertFalse(HomepageForm({"url": "http://example"}).is_valid()) self.assertFalse(HomepageForm({"url": "http://example."}).is_valid()) self.assertFalse(HomepageForm({"url": "http://com."}).is_valid()) self.assertTrue(HomepageForm({"url": "http://localhost"}).is_valid()) self.assertTrue(HomepageForm({"url": "http://example.com"}).is_valid()) self.assertTrue(HomepageForm({"url": "http://www.example.com"}).is_valid()) self.assertTrue(HomepageForm({"url": "http://www.example.com:8000"}).is_valid()) self.assertTrue(HomepageForm({"url": "http://www.example.com/test"}).is_valid()) self.assertTrue( HomepageForm({"url": "http://www.example.com:8000/test"}).is_valid() ) self.assertTrue(HomepageForm({"url": "http://example.com/foo/bar"}).is_valid()) def test_modelform_non_editable_field(self): """ When explicitly including a non-editable field in a ModelForm, the error message should be explicit. """ # 'created', non-editable, is excluded by default self.assertNotIn("created", ArticleForm().fields) msg = ( "'created' cannot be specified for Article model form as it is a " "non-editable field" ) with self.assertRaisesMessage(FieldError, msg): class InvalidArticleForm(forms.ModelForm): class Meta: model = Article fields = ("headline", "created") def test_http_prefixing(self): """ If the http:// prefix is omitted on form input, the field adds it again. """ class HomepageForm(forms.ModelForm): class Meta: model = Homepage fields = "__all__" form = HomepageForm({"url": "example.com"}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data["url"], "http://example.com") form = HomepageForm({"url": "example.com/test"}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data["url"], "http://example.com/test") class OtherModelFormTests(TestCase): def test_media_on_modelform(self): # Similar to a regular Form class you can define custom media to be used on # the ModelForm. f = ModelFormWithMedia() self.assertHTMLEqual( str(f.media), '<link href="/some/form/css" media="all" rel="stylesheet">' '<script src="/some/form/javascript"></script>', ) def test_choices_type(self): # Choices on CharField and IntegerField f = ArticleForm() with self.assertRaises(ValidationError): f.fields["status"].clean("42") f = ArticleStatusForm() with self.assertRaises(ValidationError): f.fields["status"].clean("z") def test_prefetch_related_queryset(self): """ ModelChoiceField should respect a prefetch_related() on its queryset. """ blue = Colour.objects.create(name="blue") red = Colour.objects.create(name="red") multicolor_item = ColourfulItem.objects.create() multicolor_item.colours.add(blue, red) red_item = ColourfulItem.objects.create() red_item.colours.add(red) class ColorModelChoiceField(forms.ModelChoiceField): def label_from_instance(self, obj): return ", ".join(c.name for c in obj.colours.all()) field = ColorModelChoiceField(ColourfulItem.objects.prefetch_related("colours")) with self.assertNumQueries(3): # would be 4 if prefetch is ignored self.assertEqual( tuple(field.choices), ( ("", "---------"), (multicolor_item.pk, "blue, red"), (red_item.pk, "red"), ), ) def test_foreignkeys_which_use_to_field(self): apple = Inventory.objects.create(barcode=86, name="Apple") pear = Inventory.objects.create(barcode=22, name="Pear") core = Inventory.objects.create(barcode=87, name="Core", parent=apple) field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name="barcode") self.assertEqual( tuple(field.choices), (("", "---------"), (86, "Apple"), (87, "Core"), (22, "Pear")), ) form = InventoryForm(instance=core) self.assertHTMLEqual( str(form["parent"]), """<select name="parent" id="id_parent"> <option value="">---------</option> <option value="86" selected>Apple</option> <option value="87">Core</option> <option value="22">Pear</option> </select>""", ) data = model_to_dict(core) data["parent"] = "22" form = InventoryForm(data=data, instance=core) core = form.save() self.assertEqual(core.parent.name, "Pear") class CategoryForm(forms.ModelForm): description = forms.CharField() class Meta: model = Category fields = ["description", "url"] self.assertEqual(list(CategoryForm.base_fields), ["description", "url"]) self.assertHTMLEqual( str(CategoryForm()), '<div><label for="id_description">Description:</label><input type="text" ' 'name="description" required id="id_description"></div><div>' '<label for="id_url">The URL:</label><input type="text" name="url" ' 'maxlength="40" required id="id_url"></div>', ) # to_field_name should also work on ModelMultipleChoiceField ################## field = forms.ModelMultipleChoiceField( Inventory.objects.all(), to_field_name="barcode" ) self.assertEqual( tuple(field.choices), ((86, "Apple"), (87, "Core"), (22, "Pear")) ) self.assertSequenceEqual(field.clean([86]), [apple]) form = SelectInventoryForm({"items": [87, 22]}) self.assertTrue(form.is_valid()) self.assertEqual(len(form.cleaned_data), 1) self.assertSequenceEqual(form.cleaned_data["items"], [core, pear]) def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self): self.assertEqual(list(CustomFieldForExclusionForm.base_fields), ["name"]) self.assertHTMLEqual( str(CustomFieldForExclusionForm()), '<div><label for="id_name">Name:</label><input type="text" ' 'name="name" maxlength="10" required id="id_name"></div>', ) def test_iterable_model_m2m(self): class ColourfulItemForm(forms.ModelForm): class Meta: model = ColourfulItem fields = "__all__" colour = Colour.objects.create(name="Blue") form = ColourfulItemForm() self.maxDiff = 1024 self.assertHTMLEqual( form.as_p(), """ <p> <label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="50" required></p> <p><label for="id_colours">Colours:</label> <select multiple name="colours" id="id_colours" required> <option value="%(blue_pk)s">Blue</option> </select></p> """ % {"blue_pk": colour.pk}, ) def test_callable_field_default(self): class PublicationDefaultsForm(forms.ModelForm): class Meta: model = PublicationDefaults fields = ("title", "date_published", "mode", "category") self.maxDiff = 2000 form = PublicationDefaultsForm() today_str = str(datetime.date.today()) self.assertHTMLEqual( form.as_p(), """ <p><label for="id_title">Title:</label> <input id="id_title" maxlength="30" name="title" type="text" required> </p> <p><label for="id_date_published">Date published:</label> <input id="id_date_published" name="date_published" type="text" value="{0}" required> <input id="initial-id_date_published" name="initial-date_published" type="hidden" value="{0}"> </p> <p><label for="id_mode">Mode:</label> <select id="id_mode" name="mode"> <option value="di" selected>direct</option> <option value="de">delayed</option></select> <input id="initial-id_mode" name="initial-mode" type="hidden" value="di"> </p> <p> <label for="id_category">Category:</label> <select id="id_category" name="category"> <option value="1">Games</option> <option value="2">Comics</option> <option value="3" selected>Novel</option></select> <input id="initial-id_category" name="initial-category" type="hidden" value="3"> """.format( today_str ), ) empty_data = { "title": "", "date_published": today_str, "initial-date_published": today_str, "mode": "di", "initial-mode": "di", "category": "3", "initial-category": "3", } bound_form = PublicationDefaultsForm(empty_data) self.assertFalse(bound_form.has_changed()) class ModelFormCustomErrorTests(SimpleTestCase): def test_custom_error_messages(self): data = {"name1": "@#$!!**@#$", "name2": "@#$!!**@#$"} errors = CustomErrorMessageForm(data).errors self.assertHTMLEqual( str(errors["name1"]), '<ul class="errorlist"><li>Form custom error message.</li></ul>', ) self.assertHTMLEqual( str(errors["name2"]), '<ul class="errorlist"><li>Model custom error message.</li></ul>', ) def test_model_clean_error_messages(self): data = {"name1": "FORBIDDEN_VALUE", "name2": "ABC"} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertHTMLEqual( str(form.errors["name1"]), '<ul class="errorlist"><li>Model.clean() error messages.</li></ul>', ) data = {"name1": "FORBIDDEN_VALUE2", "name2": "ABC"} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertHTMLEqual( str(form.errors["name1"]), '<ul class="errorlist">' "<li>Model.clean() error messages (simpler syntax).</li></ul>", ) data = {"name1": "GLOBAL_ERROR", "name2": "ABC"} form = CustomErrorMessageForm(data) self.assertFalse(form.is_valid()) self.assertEqual(form.errors["__all__"], ["Global error message."]) class CustomCleanTests(TestCase): def test_override_clean(self): """ Regression for #12596: Calling super from ModelForm.clean() should be optional. """ class TripleFormWithCleanOverride(forms.ModelForm): class Meta: model = Triple fields = "__all__" def clean(self): if not self.cleaned_data["left"] == self.cleaned_data["right"]: raise ValidationError("Left and right should be equal") return self.cleaned_data form = TripleFormWithCleanOverride({"left": 1, "middle": 2, "right": 1}) self.assertTrue(form.is_valid()) # form.instance.left will be None if the instance was not constructed # by form.full_clean(). self.assertEqual(form.instance.left, 1) def test_model_form_clean_applies_to_model(self): """ Regression test for #12960. Make sure the cleaned_data returned from ModelForm.clean() is applied to the model instance. """ class CategoryForm(forms.ModelForm): class Meta: model = Category fields = "__all__" def clean(self): self.cleaned_data["name"] = self.cleaned_data["name"].upper() return self.cleaned_data data = {"name": "Test", "slug": "test", "url": "/test"} form = CategoryForm(data) category = form.save() self.assertEqual(category.name, "TEST") class ModelFormInheritanceTests(SimpleTestCase): def test_form_subclass_inheritance(self): class Form(forms.Form): age = forms.IntegerField() class ModelForm(forms.ModelForm, Form): class Meta: model = Writer fields = "__all__" self.assertEqual(list(ModelForm().fields), ["name", "age"]) def test_field_removal(self): class ModelForm(forms.ModelForm): class Meta: model = Writer fields = "__all__" class Mixin: age = None class Form(forms.Form): age = forms.IntegerField() class Form2(forms.Form): foo = forms.IntegerField() self.assertEqual(list(ModelForm().fields), ["name"]) self.assertEqual(list(type("NewForm", (Mixin, Form), {})().fields), []) self.assertEqual( list(type("NewForm", (Form2, Mixin, Form), {})().fields), ["foo"] ) self.assertEqual( list(type("NewForm", (Mixin, ModelForm, Form), {})().fields), ["name"] ) self.assertEqual( list(type("NewForm", (ModelForm, Mixin, Form), {})().fields), ["name"] ) self.assertEqual( list(type("NewForm", (ModelForm, Form, Mixin), {})().fields), ["name", "age"], ) self.assertEqual( list(type("NewForm", (ModelForm, Form), {"age": None})().fields), ["name"] ) def test_field_removal_name_clashes(self): """ Form fields can be removed in subclasses by setting them to None (#22510). """ class MyForm(forms.ModelForm): media = forms.CharField() class Meta: model = Writer fields = "__all__" class SubForm(MyForm): media = None self.assertIn("media", MyForm().fields) self.assertNotIn("media", SubForm().fields) self.assertTrue(hasattr(MyForm, "media")) self.assertTrue(hasattr(SubForm, "media")) class StumpJokeForm(forms.ModelForm): class Meta: model = StumpJoke fields = "__all__" class CustomFieldWithQuerysetButNoLimitChoicesTo(forms.Field): queryset = 42 class StumpJokeWithCustomFieldForm(forms.ModelForm): custom = CustomFieldWithQuerysetButNoLimitChoicesTo() class Meta: model = StumpJoke fields = () class LimitChoicesToTests(TestCase): """ Tests the functionality of ``limit_choices_to``. """ @classmethod def setUpTestData(cls): cls.threepwood = Character.objects.create( username="threepwood", last_action=datetime.datetime.today() + datetime.timedelta(days=1), ) cls.marley = Character.objects.create( username="marley", last_action=datetime.datetime.today() - datetime.timedelta(days=1), ) def test_limit_choices_to_callable_for_fk_rel(self): """ A ForeignKey can use limit_choices_to as a callable (#2554). """ stumpjokeform = StumpJokeForm() self.assertSequenceEqual( stumpjokeform.fields["most_recently_fooled"].queryset, [self.threepwood] ) def test_limit_choices_to_callable_for_m2m_rel(self): """ A ManyToManyField can use limit_choices_to as a callable (#2554). """ stumpjokeform = StumpJokeForm() self.assertSequenceEqual( stumpjokeform.fields["most_recently_fooled"].queryset, [self.threepwood] ) def test_custom_field_with_queryset_but_no_limit_choices_to(self): """ A custom field with a `queryset` attribute but no `limit_choices_to` works (#23795). """ f = StumpJokeWithCustomFieldForm() self.assertEqual(f.fields["custom"].queryset, 42) def test_fields_for_model_applies_limit_choices_to(self): fields = fields_for_model(StumpJoke, ["has_fooled_today"]) self.assertSequenceEqual(fields["has_fooled_today"].queryset, [self.threepwood]) def test_callable_called_each_time_form_is_instantiated(self): field = StumpJokeForm.base_fields["most_recently_fooled"] with mock.patch.object(field, "limit_choices_to") as today_callable_dict: StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 1) StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 2) StumpJokeForm() self.assertEqual(today_callable_dict.call_count, 3) @isolate_apps("model_forms") def test_limit_choices_to_no_duplicates(self): joke1 = StumpJoke.objects.create( funny=True, most_recently_fooled=self.threepwood, ) joke2 = StumpJoke.objects.create( funny=True, most_recently_fooled=self.threepwood, ) joke3 = StumpJoke.objects.create( funny=True, most_recently_fooled=self.marley, ) StumpJoke.objects.create(funny=False, most_recently_fooled=self.marley) joke1.has_fooled_today.add(self.marley, self.threepwood) joke2.has_fooled_today.add(self.marley) joke3.has_fooled_today.add(self.marley, self.threepwood) class CharacterDetails(models.Model): character1 = models.ForeignKey( Character, models.CASCADE, limit_choices_to=models.Q( jokes__funny=True, jokes_today__funny=True, ), related_name="details_fk_1", ) character2 = models.ForeignKey( Character, models.CASCADE, limit_choices_to={ "jokes__funny": True, "jokes_today__funny": True, }, related_name="details_fk_2", ) character3 = models.ManyToManyField( Character, limit_choices_to=models.Q( jokes__funny=True, jokes_today__funny=True, ), related_name="details_m2m_1", ) class CharacterDetailsForm(forms.ModelForm): class Meta: model = CharacterDetails fields = "__all__" form = CharacterDetailsForm() self.assertCountEqual( form.fields["character1"].queryset, [self.marley, self.threepwood], ) self.assertCountEqual( form.fields["character2"].queryset, [self.marley, self.threepwood], ) self.assertCountEqual( form.fields["character3"].queryset, [self.marley, self.threepwood], ) def test_limit_choices_to_m2m_through(self): class DiceForm(forms.ModelForm): class Meta: model = Dice fields = ["numbers"] Number.objects.create(value=0) n1 = Number.objects.create(value=1) n2 = Number.objects.create(value=2) form = DiceForm() self.assertCountEqual(form.fields["numbers"].queryset, [n1, n2]) class FormFieldCallbackTests(SimpleTestCase): def test_baseform_with_widgets_in_meta(self): """ Using base forms with widgets defined in Meta should not raise errors. """ widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {"name": widget} fields = "__all__" Form = modelform_factory(Person, form=BaseForm) self.assertIsInstance(Form.base_fields["name"].widget, forms.Textarea) def test_factory_with_widget_argument(self): """Regression for #15315: modelform_factory should accept widgets argument """ widget = forms.Textarea() # Without a widget should not set the widget to textarea Form = modelform_factory(Person, fields="__all__") self.assertNotEqual(Form.base_fields["name"].widget.__class__, forms.Textarea) # With a widget should not set the widget to textarea Form = modelform_factory(Person, fields="__all__", widgets={"name": widget}) self.assertEqual(Form.base_fields["name"].widget.__class__, forms.Textarea) def test_modelform_factory_without_fields(self): """Regression for #19733""" message = ( "Calling modelform_factory without defining 'fields' or 'exclude' " "explicitly is prohibited." ) with self.assertRaisesMessage(ImproperlyConfigured, message): modelform_factory(Person) def test_modelform_factory_with_all_fields(self): """Regression for #19733""" form = modelform_factory(Person, fields="__all__") self.assertEqual(list(form.base_fields), ["name"]) def test_custom_callback(self): """A custom formfield_callback is used if provided""" callback_args = [] def callback(db_field, **kwargs): callback_args.append((db_field, kwargs)) return db_field.formfield(**kwargs) widget = forms.Textarea() class BaseForm(forms.ModelForm): class Meta: model = Person widgets = {"name": widget} fields = "__all__" modelform_factory(Person, form=BaseForm, formfield_callback=callback) id_field, name_field = Person._meta.fields self.assertEqual( callback_args, [(id_field, {}), (name_field, {"widget": widget})] ) def test_bad_callback(self): # A bad callback provided by user still gives an error with self.assertRaises(TypeError): modelform_factory( Person, fields="__all__", formfield_callback="not a function or callable", ) def test_inherit_after_custom_callback(self): def callback(db_field, **kwargs): if isinstance(db_field, models.CharField): return forms.CharField(widget=forms.Textarea) return db_field.formfield(**kwargs) class BaseForm(forms.ModelForm): class Meta: model = Person fields = "__all__" NewForm = modelform_factory(Person, form=BaseForm, formfield_callback=callback) class InheritedForm(NewForm): pass for name in NewForm.base_fields: self.assertEqual( type(InheritedForm.base_fields[name].widget), type(NewForm.base_fields[name].widget), ) class LocalizedModelFormTest(TestCase): def test_model_form_applies_localize_to_some_fields(self): class PartiallyLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = ( "left", "right", ) fields = "__all__" f = PartiallyLocalizedTripleForm({"left": 10, "middle": 10, "right": 10}) self.assertTrue(f.is_valid()) self.assertTrue(f.fields["left"].localize) self.assertFalse(f.fields["middle"].localize) self.assertTrue(f.fields["right"].localize) def test_model_form_applies_localize_to_all_fields(self): class FullyLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = "__all__" fields = "__all__" f = FullyLocalizedTripleForm({"left": 10, "middle": 10, "right": 10}) self.assertTrue(f.is_valid()) self.assertTrue(f.fields["left"].localize) self.assertTrue(f.fields["middle"].localize) self.assertTrue(f.fields["right"].localize) def test_model_form_refuses_arbitrary_string(self): msg = ( "BrokenLocalizedTripleForm.Meta.localized_fields " "cannot be a string. Did you mean to type: ('foo',)?" ) with self.assertRaisesMessage(TypeError, msg): class BrokenLocalizedTripleForm(forms.ModelForm): class Meta: model = Triple localized_fields = "foo" class CustomMetaclass(ModelFormMetaclass): def __new__(cls, name, bases, attrs): new = super().__new__(cls, name, bases, attrs) new.base_fields = {} return new class CustomMetaclassForm(forms.ModelForm, metaclass=CustomMetaclass): pass class CustomMetaclassTestCase(SimpleTestCase): def test_modelform_factory_metaclass(self): new_cls = modelform_factory(Person, fields="__all__", form=CustomMetaclassForm) self.assertEqual(new_cls.base_fields, {}) class StrictAssignmentTests(SimpleTestCase): """ Should a model do anything special with __setattr__() or descriptors which raise a ValidationError, a model form should catch the error (#24706). """ def test_setattr_raises_validation_error_field_specific(self): """ A model ValidationError using the dict form should put the error message into the correct key of form.errors. """ form_class = modelform_factory( model=StrictAssignmentFieldSpecific, fields=["title"] ) form = form_class(data={"title": "testing setattr"}, files=None) # This line turns on the ValidationError; it avoids the model erroring # when its own __init__() is called when creating form.instance. form.instance._should_error = True self.assertFalse(form.is_valid()) self.assertEqual( form.errors, {"title": ["Cannot set attribute", "This field cannot be blank."]}, ) def test_setattr_raises_validation_error_non_field(self): """ A model ValidationError not using the dict form should put the error message into __all__ (i.e. non-field errors) on the form. """ form_class = modelform_factory(model=StrictAssignmentAll, fields=["title"]) form = form_class(data={"title": "testing setattr"}, files=None) # This line turns on the ValidationError; it avoids the model erroring # when its own __init__() is called when creating form.instance. form.instance._should_error = True self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "__all__": ["Cannot set attribute"], "title": ["This field cannot be blank."], }, ) class ModelToDictTests(TestCase): def test_many_to_many(self): """Data for a ManyToManyField is a list rather than a lazy QuerySet.""" blue = Colour.objects.create(name="blue") red = Colour.objects.create(name="red") item = ColourfulItem.objects.create() item.colours.set([blue]) data = model_to_dict(item)["colours"] self.assertEqual(data, [blue]) item.colours.set([red]) # If data were a QuerySet, it would be reevaluated here and give "red" # instead of the original value. self.assertEqual(data, [blue])
07833dcaeb67621e2e11e5cf21be710f59127b6f483ebee07aea9a95c785efac
import datetime import decimal import gettext as gettext_module import os import pickle import re import tempfile from contextlib import contextmanager from importlib import import_module from pathlib import Path from unittest import mock from asgiref.local import Local from django import forms from django.apps import AppConfig from django.conf import settings from django.conf.locale import LANG_INFO from django.conf.urls.i18n import i18n_patterns from django.template import Context, Template from django.test import ( RequestFactory, SimpleTestCase, TestCase, ignore_warnings, override_settings, ) from django.utils import translation from django.utils.deprecation import RemovedInDjango50Warning from django.utils.formats import ( date_format, get_format, iter_format_modules, localize, localize_input, reset_format_cache, sanitize_separators, sanitize_strftime_format, time_format, ) from django.utils.numberformat import format as nformat from django.utils.safestring import SafeString, mark_safe from django.utils.translation import ( activate, check_for_language, deactivate, get_language, get_language_bidi, get_language_from_request, get_language_info, gettext, gettext_lazy, ngettext, ngettext_lazy, npgettext, npgettext_lazy, pgettext, round_away_from_one, to_language, to_locale, trans_null, trans_real, ) from django.utils.translation.reloader import ( translation_file_changed, watch_for_translation_changes, ) from .forms import CompanyForm, I18nForm, SelectDateForm from .models import Company, TestModel here = os.path.dirname(os.path.abspath(__file__)) extended_locale_paths = settings.LOCALE_PATHS + [ os.path.join(here, "other", "locale"), ] class AppModuleStub: def __init__(self, **kwargs): self.__dict__.update(kwargs) @contextmanager def patch_formats(lang, **settings): from django.utils.formats import _format_cache # Populate _format_cache with temporary values for key, value in settings.items(): _format_cache[(key, lang)] = value try: yield finally: reset_format_cache() class TranslationTests(SimpleTestCase): @translation.override("fr") def test_plural(self): """ Test plurals with ngettext. French differs from English in that 0 is singular. """ self.assertEqual( ngettext("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 année", ) self.assertEqual( ngettext("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 années", ) self.assertEqual( ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0}, "0 octet" ) self.assertEqual( ngettext("%(size)d byte", "%(size)d bytes", 2) % {"size": 2}, "2 octets" ) def test_plural_null(self): g = trans_null.ngettext self.assertEqual(g("%(num)d year", "%(num)d years", 0) % {"num": 0}, "0 years") self.assertEqual(g("%(num)d year", "%(num)d years", 1) % {"num": 1}, "1 year") self.assertEqual(g("%(num)d year", "%(num)d years", 2) % {"num": 2}, "2 years") @override_settings(LOCALE_PATHS=extended_locale_paths) @translation.override("fr") def test_multiple_plurals_per_language(self): """ Normally, French has 2 plurals. As other/locale/fr/LC_MESSAGES/django.po has a different plural equation with 3 plurals, this tests if those plural are honored. """ self.assertEqual(ngettext("%d singular", "%d plural", 0) % 0, "0 pluriel1") self.assertEqual(ngettext("%d singular", "%d plural", 1) % 1, "1 singulier") self.assertEqual(ngettext("%d singular", "%d plural", 2) % 2, "2 pluriel2") french = trans_real.catalog() # Internal _catalog can query subcatalogs (from different po files). self.assertEqual(french._catalog[("%d singular", 0)], "%d singulier") self.assertEqual(french._catalog[("%(num)d hour", 0)], "%(num)d heure") def test_override(self): activate("de") try: with translation.override("pl"): self.assertEqual(get_language(), "pl") self.assertEqual(get_language(), "de") with translation.override(None): self.assertIsNone(get_language()) with translation.override("pl"): pass self.assertIsNone(get_language()) self.assertEqual(get_language(), "de") finally: deactivate() def test_override_decorator(self): @translation.override("pl") def func_pl(): self.assertEqual(get_language(), "pl") @translation.override(None) def func_none(): self.assertIsNone(get_language()) try: activate("de") func_pl() self.assertEqual(get_language(), "de") func_none() self.assertEqual(get_language(), "de") finally: deactivate() def test_override_exit(self): """ The language restored is the one used when the function was called, not the one used when the decorator was initialized (#23381). """ activate("fr") @translation.override("pl") def func_pl(): pass deactivate() try: activate("en") func_pl() self.assertEqual(get_language(), "en") finally: deactivate() def test_lazy_objects(self): """ Format string interpolation should work with *_lazy objects. """ s = gettext_lazy("Add %(name)s") d = {"name": "Ringo"} self.assertEqual("Add Ringo", s % d) with translation.override("de", deactivate=True): self.assertEqual("Ringo hinzuf\xfcgen", s % d) with translation.override("pl"): self.assertEqual("Dodaj Ringo", s % d) # It should be possible to compare *_lazy objects. s1 = gettext_lazy("Add %(name)s") self.assertEqual(s, s1) s2 = gettext_lazy("Add %(name)s") s3 = gettext_lazy("Add %(name)s") self.assertEqual(s2, s3) self.assertEqual(s, s2) s4 = gettext_lazy("Some other string") self.assertNotEqual(s, s4) def test_lazy_pickle(self): s1 = gettext_lazy("test") self.assertEqual(str(s1), "test") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(str(s2), "test") @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy(self): simple_with_format = ngettext_lazy("%d good result", "%d good results") simple_context_with_format = npgettext_lazy( "Exclamation", "%d good result", "%d good results" ) simple_without_format = ngettext_lazy("good result", "good results") with translation.override("de"): self.assertEqual(simple_with_format % 1, "1 gutes Resultat") self.assertEqual(simple_with_format % 4, "4 guten Resultate") self.assertEqual(simple_context_with_format % 1, "1 gutes Resultat!") self.assertEqual(simple_context_with_format % 4, "4 guten Resultate!") self.assertEqual(simple_without_format % 1, "gutes Resultat") self.assertEqual(simple_without_format % 4, "guten Resultate") complex_nonlazy = ngettext_lazy( "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4 ) complex_deferred = ngettext_lazy( "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", "num", ) complex_context_nonlazy = npgettext_lazy( "Greeting", "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", 4, ) complex_context_deferred = npgettext_lazy( "Greeting", "Hi %(name)s, %(num)d good result", "Hi %(name)s, %(num)d good results", "num", ) with translation.override("de"): self.assertEqual( complex_nonlazy % {"num": 4, "name": "Jim"}, "Hallo Jim, 4 guten Resultate", ) self.assertEqual( complex_deferred % {"name": "Jim", "num": 1}, "Hallo Jim, 1 gutes Resultat", ) self.assertEqual( complex_deferred % {"name": "Jim", "num": 5}, "Hallo Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_deferred % {"name": "Jim"} self.assertEqual( complex_context_nonlazy % {"num": 4, "name": "Jim"}, "Willkommen Jim, 4 guten Resultate", ) self.assertEqual( complex_context_deferred % {"name": "Jim", "num": 1}, "Willkommen Jim, 1 gutes Resultat", ) self.assertEqual( complex_context_deferred % {"name": "Jim", "num": 5}, "Willkommen Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_context_deferred % {"name": "Jim"} @override_settings(LOCALE_PATHS=extended_locale_paths) def test_ngettext_lazy_format_style(self): simple_with_format = ngettext_lazy("{} good result", "{} good results") simple_context_with_format = npgettext_lazy( "Exclamation", "{} good result", "{} good results" ) with translation.override("de"): self.assertEqual(simple_with_format.format(1), "1 gutes Resultat") self.assertEqual(simple_with_format.format(4), "4 guten Resultate") self.assertEqual(simple_context_with_format.format(1), "1 gutes Resultat!") self.assertEqual(simple_context_with_format.format(4), "4 guten Resultate!") complex_nonlazy = ngettext_lazy( "Hi {name}, {num} good result", "Hi {name}, {num} good results", 4 ) complex_deferred = ngettext_lazy( "Hi {name}, {num} good result", "Hi {name}, {num} good results", "num" ) complex_context_nonlazy = npgettext_lazy( "Greeting", "Hi {name}, {num} good result", "Hi {name}, {num} good results", 4, ) complex_context_deferred = npgettext_lazy( "Greeting", "Hi {name}, {num} good result", "Hi {name}, {num} good results", "num", ) with translation.override("de"): self.assertEqual( complex_nonlazy.format(num=4, name="Jim"), "Hallo Jim, 4 guten Resultate", ) self.assertEqual( complex_deferred.format(name="Jim", num=1), "Hallo Jim, 1 gutes Resultat", ) self.assertEqual( complex_deferred.format(name="Jim", num=5), "Hallo Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_deferred.format(name="Jim") self.assertEqual( complex_context_nonlazy.format(num=4, name="Jim"), "Willkommen Jim, 4 guten Resultate", ) self.assertEqual( complex_context_deferred.format(name="Jim", num=1), "Willkommen Jim, 1 gutes Resultat", ) self.assertEqual( complex_context_deferred.format(name="Jim", num=5), "Willkommen Jim, 5 guten Resultate", ) with self.assertRaisesMessage(KeyError, "Your dictionary lacks key"): complex_context_deferred.format(name="Jim") def test_ngettext_lazy_bool(self): self.assertTrue(ngettext_lazy("%d good result", "%d good results")) self.assertFalse(ngettext_lazy("", "")) def test_ngettext_lazy_pickle(self): s1 = ngettext_lazy("%d good result", "%d good results") self.assertEqual(s1 % 1, "1 good result") self.assertEqual(s1 % 8, "8 good results") s2 = pickle.loads(pickle.dumps(s1)) self.assertEqual(s2 % 1, "1 good result") self.assertEqual(s2 % 8, "8 good results") @override_settings(LOCALE_PATHS=extended_locale_paths) def test_pgettext(self): trans_real._active = Local() trans_real._translations = {} with translation.override("de"): self.assertEqual(pgettext("unexisting", "May"), "May") self.assertEqual(pgettext("month name", "May"), "Mai") self.assertEqual(pgettext("verb", "May"), "Kann") self.assertEqual( npgettext("search", "%d result", "%d results", 4) % 4, "4 Resultate" ) def test_empty_value(self): """Empty value must stay empty after being translated (#23196).""" with translation.override("de"): self.assertEqual("", gettext("")) s = mark_safe("") self.assertEqual(s, gettext(s)) @override_settings(LOCALE_PATHS=extended_locale_paths) def test_safe_status(self): """ Translating a string requiring no auto-escaping with gettext or pgettext shouldn't change the "safe" status. """ trans_real._active = Local() trans_real._translations = {} s1 = mark_safe("Password") s2 = mark_safe("May") with translation.override("de", deactivate=True): self.assertIs(type(gettext(s1)), SafeString) self.assertIs(type(pgettext("month name", s2)), SafeString) self.assertEqual("aPassword", SafeString("a") + s1) self.assertEqual("Passworda", s1 + SafeString("a")) self.assertEqual("Passworda", s1 + mark_safe("a")) self.assertEqual("aPassword", mark_safe("a") + s1) self.assertEqual("as", mark_safe("a") + mark_safe("s")) def test_maclines(self): """ Translations on files with Mac or DOS end of lines will be converted to unix EOF in .po catalogs. """ ca_translation = trans_real.translation("ca") ca_translation._catalog["Mac\nEOF\n"] = "Catalan Mac\nEOF\n" ca_translation._catalog["Win\nEOF\n"] = "Catalan Win\nEOF\n" with translation.override("ca", deactivate=True): self.assertEqual("Catalan Mac\nEOF\n", gettext("Mac\rEOF\r")) self.assertEqual("Catalan Win\nEOF\n", gettext("Win\r\nEOF\r\n")) def test_to_locale(self): tests = ( ("en", "en"), ("EN", "en"), ("en-us", "en_US"), ("EN-US", "en_US"), ("en_US", "en_US"), # With > 2 characters after the dash. ("sr-latn", "sr_Latn"), ("sr-LATN", "sr_Latn"), ("sr_Latn", "sr_Latn"), # 3-char language codes. ("ber-MA", "ber_MA"), ("BER-MA", "ber_MA"), ("BER_MA", "ber_MA"), ("ber_MA", "ber_MA"), # With private use subtag (x-informal). ("nl-nl-x-informal", "nl_NL-x-informal"), ("NL-NL-X-INFORMAL", "nl_NL-x-informal"), ("sr-latn-x-informal", "sr_Latn-x-informal"), ("SR-LATN-X-INFORMAL", "sr_Latn-x-informal"), ) for lang, locale in tests: with self.subTest(lang=lang): self.assertEqual(to_locale(lang), locale) def test_to_language(self): self.assertEqual(to_language("en_US"), "en-us") self.assertEqual(to_language("sr_Lat"), "sr-lat") def test_language_bidi(self): self.assertIs(get_language_bidi(), False) with translation.override(None): self.assertIs(get_language_bidi(), False) def test_language_bidi_null(self): self.assertIs(trans_null.get_language_bidi(), False) with override_settings(LANGUAGE_CODE="he"): self.assertIs(get_language_bidi(), True) class TranslationLoadingTests(SimpleTestCase): def setUp(self): """Clear translation state.""" self._old_language = get_language() self._old_translations = trans_real._translations deactivate() trans_real._translations = {} def tearDown(self): trans_real._translations = self._old_translations activate(self._old_language) @override_settings( USE_I18N=True, LANGUAGE_CODE="en", LANGUAGES=[ ("en", "English"), ("en-ca", "English (Canada)"), ("en-nz", "English (New Zealand)"), ("en-au", "English (Australia)"), ], LOCALE_PATHS=[os.path.join(here, "loading")], INSTALLED_APPS=["i18n.loading_app"], ) def test_translation_loading(self): """ "loading_app" does not have translations for all languages provided by "loading". Catalogs are merged correctly. """ tests = [ ("en", "local country person"), ("en_AU", "aussie"), ("en_NZ", "kiwi"), ("en_CA", "canuck"), ] # Load all relevant translations. for language, _ in tests: activate(language) # Catalogs are merged correctly. for language, nickname in tests: with self.subTest(language=language): activate(language) self.assertEqual(gettext("local country person"), nickname) class TranslationThreadSafetyTests(SimpleTestCase): def setUp(self): self._old_language = get_language() self._translations = trans_real._translations # here we rely on .split() being called inside the _fetch() # in trans_real.translation() class sideeffect_str(str): def split(self, *args, **kwargs): res = str.split(self, *args, **kwargs) trans_real._translations["en-YY"] = None return res trans_real._translations = {sideeffect_str("en-XX"): None} def tearDown(self): trans_real._translations = self._translations activate(self._old_language) def test_bug14894_translation_activate_thread_safety(self): translation_count = len(trans_real._translations) # May raise RuntimeError if translation.activate() isn't thread-safe. translation.activate("pl") # make sure sideeffect_str actually added a new translation self.assertLess(translation_count, len(trans_real._translations)) class FormattingTests(SimpleTestCase): def setUp(self): super().setUp() self.n = decimal.Decimal("66666.666") self.f = 99999.999 self.d = datetime.date(2009, 12, 31) self.dt = datetime.datetime(2009, 12, 31, 20, 50) self.t = datetime.time(10, 15, 48) self.long = 10000 self.ctxt = Context( { "n": self.n, "t": self.t, "d": self.d, "dt": self.dt, "f": self.f, "l": self.long, } ) def test_all_format_strings(self): all_locales = LANG_INFO.keys() some_date = datetime.date(2017, 10, 14) some_datetime = datetime.datetime(2017, 10, 14, 10, 23) for locale in all_locales: with self.subTest(locale=locale), translation.override(locale): self.assertIn( "2017", date_format(some_date) ) # Uses DATE_FORMAT by default self.assertIn( "23", time_format(some_datetime) ) # Uses TIME_FORMAT by default self.assertIn( "2017", date_format(some_datetime, format=get_format("DATETIME_FORMAT")), ) self.assertIn( "2017", date_format(some_date, format=get_format("YEAR_MONTH_FORMAT")), ) self.assertIn( "14", date_format(some_date, format=get_format("MONTH_DAY_FORMAT")) ) self.assertIn( "2017", date_format(some_date, format=get_format("SHORT_DATE_FORMAT")), ) self.assertIn( "2017", date_format( some_datetime, format=get_format("SHORT_DATETIME_FORMAT") ), ) def test_locale_independent(self): """ Localization of numbers """ with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual( "66666.66", nformat( self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," ), ) self.assertEqual( "66666A6", nformat( self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" ), ) self.assertEqual( "66666", nformat( self.n, decimal_sep="X", decimal_pos=0, grouping=1, thousand_sep="Y" ), ) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual( "66,666.66", nformat( self.n, decimal_sep=".", decimal_pos=2, grouping=3, thousand_sep="," ), ) self.assertEqual( "6B6B6B6B6A6", nformat( self.n, decimal_sep="A", decimal_pos=1, grouping=1, thousand_sep="B" ), ) self.assertEqual( "-66666.6", nformat(-66666.666, decimal_sep=".", decimal_pos=1) ) self.assertEqual( "-66666.0", nformat(int("-66666"), decimal_sep=".", decimal_pos=1) ) self.assertEqual( "10000.0", nformat(self.long, decimal_sep=".", decimal_pos=1) ) self.assertEqual( "10,00,00,000.00", nformat( 100000000.00, decimal_sep=".", decimal_pos=2, grouping=(3, 2, 0), thousand_sep=",", ), ) self.assertEqual( "1,0,00,000,0000.00", nformat( 10000000000.00, decimal_sep=".", decimal_pos=2, grouping=(4, 3, 2, 1, 0), thousand_sep=",", ), ) self.assertEqual( "10000,00,000.00", nformat( 1000000000.00, decimal_sep=".", decimal_pos=2, grouping=(3, 2, -1), thousand_sep=",", ), ) # This unusual grouping/force_grouping combination may be triggered # by the intcomma filter. self.assertEqual( "10000", nformat( self.long, decimal_sep=".", decimal_pos=0, grouping=0, force_grouping=True, ), ) # date filter self.assertEqual( "31.12.2009 в 20:50", Template('{{ dt|date:"d.m.Y в H:i" }}').render(self.ctxt), ) self.assertEqual( "⌚ 10:15", Template('{{ t|time:"⌚ H:i" }}').render(self.ctxt) ) @ignore_warnings(category=RemovedInDjango50Warning) @override_settings(USE_L10N=False) def test_l10n_disabled(self): """ Catalan locale with format i18n disabled translations will be used, but not formats """ with translation.override("ca", deactivate=True): self.maxDiff = 3000 self.assertEqual("N j, Y", get_format("DATE_FORMAT")) self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(".", get_format("DECIMAL_SEPARATOR")) self.assertEqual("10:15 a.m.", time_format(self.t)) self.assertEqual("Des. 31, 2009", date_format(self.d)) self.assertEqual("desembre 2009", date_format(self.d, "YEAR_MONTH_FORMAT")) self.assertEqual( "12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) self.assertEqual("66666.666", localize(self.n)) self.assertEqual("99999.999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("Des. 31, 2009", localize(self.d)) self.assertEqual("Des. 31, 2009, 8:50 p.m.", localize(self.dt)) self.assertEqual("66666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("Des. 31, 2009", Template("{{ d }}").render(self.ctxt)) self.assertEqual( "Des. 31, 2009, 8:50 p.m.", Template("{{ dt }}").render(self.ctxt) ) self.assertEqual( "66666.67", Template('{{ n|floatformat:"2u" }}').render(self.ctxt) ) self.assertEqual( "100000.0", Template('{{ f|floatformat:"u" }}').render(self.ctxt) ) self.assertEqual( "66666.67", Template('{{ n|floatformat:"2gu" }}').render(self.ctxt), ) self.assertEqual( "100000.0", Template('{{ f|floatformat:"ug" }}').render(self.ctxt), ) self.assertEqual( "10:15 a.m.", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt) ) self.assertEqual( "12/31/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009 8:50 p.m.", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) form = I18nForm( { "decimal_field": "66666,666", "float_field": "99999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1.234", } ) self.assertFalse(form.is_valid()) self.assertEqual(["Introdu\xefu un n\xfamero."], form.errors["float_field"]) self.assertEqual( ["Introdu\xefu un n\xfamero."], form.errors["decimal_field"] ) self.assertEqual( ["Introdu\xefu una data v\xe0lida."], form.errors["date_field"] ) self.assertEqual( ["Introdu\xefu una data/hora v\xe0lides."], form.errors["datetime_field"], ) self.assertEqual( ["Introdu\xefu un n\xfamero enter."], form.errors["integer_field"] ) form2 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form2.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form2.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">gener</option>' '<option value="2">febrer</option>' '<option value="3">mar\xe7</option>' '<option value="4">abril</option>' '<option value="5">maig</option>' '<option value="6">juny</option>' '<option value="7">juliol</option>' '<option value="8">agost</option>' '<option value="9">setembre</option>' '<option value="10">octubre</option>' '<option value="11">novembre</option>' '<option value="12" selected>desembre</option>' "</select>" '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # We shouldn't change the behavior of the floatformat filter re: # thousand separator and grouping when localization is disabled # even if the USE_THOUSAND_SEPARATOR, NUMBER_GROUPING and # THOUSAND_SEPARATOR settings are specified. with self.settings( USE_THOUSAND_SEPARATOR=True, NUMBER_GROUPING=1, THOUSAND_SEPARATOR="!" ): self.assertEqual( "66666.67", Template('{{ n|floatformat:"2u" }}').render(self.ctxt) ) self.assertEqual( "100000.0", Template('{{ f|floatformat:"u" }}').render(self.ctxt) ) def test_false_like_locale_formats(self): """ The active locale's formats take precedence over the default settings even if they would be interpreted as False in a conditional test (e.g. 0 or empty string) (#16938). """ with translation.override("fr"): with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="!"): self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) # Even a second time (after the format has been cached)... self.assertEqual("\xa0", get_format("THOUSAND_SEPARATOR")) with self.settings(FIRST_DAY_OF_WEEK=0): self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) # Even a second time (after the format has been cached)... self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) def test_l10n_enabled(self): self.maxDiff = 3000 # Catalan locale with translation.override("ca", deactivate=True): self.assertEqual(r"j E \d\e Y", get_format("DATE_FORMAT")) self.assertEqual(1, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(",", get_format("DECIMAL_SEPARATOR")) self.assertEqual("10:15", time_format(self.t)) self.assertEqual("31 de desembre de 2009", date_format(self.d)) self.assertEqual( "1 d'abril de 2009", date_format(datetime.date(2009, 4, 1)) ) self.assertEqual( "desembre del 2009", date_format(self.d, "YEAR_MONTH_FORMAT") ) self.assertEqual( "31/12/2009 20:50", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66.666,666", localize(self.n)) self.assertEqual("99.999,999", localize(self.f)) self.assertEqual("10.000", localize(self.long)) self.assertEqual("True", localize(True)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666,666", localize(self.n)) self.assertEqual("99999,999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("31 de desembre de 2009", localize(self.d)) self.assertEqual( "31 de desembre de 2009 a les 20:50", localize(self.dt) ) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99.999,999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("10.000", Template("{{ l }}").render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=True): form3 = I18nForm( { "decimal_field": "66.666,666", "float_field": "99.999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1.234", } ) self.assertTrue(form3.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form3.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form3.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form3.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form3.cleaned_data["datetime_field"], ) self.assertEqual( datetime.time(20, 50), form3.cleaned_data["time_field"] ) self.assertEqual(1234, form3.cleaned_data["integer_field"]) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666,666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999,999", Template("{{ f }}").render(self.ctxt)) self.assertEqual( "31 de desembre de 2009", Template("{{ d }}").render(self.ctxt) ) self.assertEqual( "31 de desembre de 2009 a les 20:50", Template("{{ dt }}").render(self.ctxt), ) self.assertEqual( "66666,67", Template("{{ n|floatformat:2 }}").render(self.ctxt) ) self.assertEqual( "100000,0", Template("{{ f|floatformat }}").render(self.ctxt) ) self.assertEqual( "66.666,67", Template('{{ n|floatformat:"2g" }}').render(self.ctxt), ) self.assertEqual( "100.000,0", Template('{{ f|floatformat:"g" }}').render(self.ctxt), ) self.assertEqual( "10:15", Template('{{ t|time:"TIME_FORMAT" }}').render(self.ctxt) ) self.assertEqual( "31/12/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "31/12/2009 20:50", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) self.assertEqual( date_format(datetime.datetime.now(), "DATE_FORMAT"), Template('{% now "DATE_FORMAT" %}').render(self.ctxt), ) with self.settings(USE_THOUSAND_SEPARATOR=False): form4 = I18nForm( { "decimal_field": "66666,666", "float_field": "99999,999", "date_field": "31/12/2009", "datetime_field": "31/12/2009 20:50", "time_field": "20:50", "integer_field": "1234", } ) self.assertTrue(form4.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form4.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form4.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form4.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form4.cleaned_data["datetime_field"], ) self.assertEqual( datetime.time(20, 50), form4.cleaned_data["time_field"] ) self.assertEqual(1234, form4.cleaned_data["integer_field"]) form5 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form5.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">gener</option>' '<option value="2">febrer</option>' '<option value="3">mar\xe7</option>' '<option value="4">abril</option>' '<option value="5">maig</option>' '<option value="6">juny</option>' '<option value="7">juliol</option>' '<option value="8">agost</option>' '<option value="9">setembre</option>' '<option value="10">octubre</option>' '<option value="11">novembre</option>' '<option value="12" selected>desembre</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # Russian locale (with E as month) with translation.override("ru", deactivate=True): self.assertHTMLEqual( '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">\u042f\u043d\u0432\u0430\u0440\u044c</option>' '<option value="2">\u0424\u0435\u0432\u0440\u0430\u043b\u044c</option>' '<option value="3">\u041c\u0430\u0440\u0442</option>' '<option value="4">\u0410\u043f\u0440\u0435\u043b\u044c</option>' '<option value="5">\u041c\u0430\u0439</option>' '<option value="6">\u0418\u044e\u043d\u044c</option>' '<option value="7">\u0418\u044e\u043b\u044c</option>' '<option value="8">\u0410\u0432\u0433\u0443\u0441\u0442</option>' '<option value="9">\u0421\u0435\u043d\u0442\u044f\u0431\u0440\u044c' "</option>" '<option value="10">\u041e\u043a\u0442\u044f\u0431\u0440\u044c</option>' '<option value="11">\u041d\u043e\u044f\u0431\u0440\u044c</option>' '<option value="12" selected>\u0414\u0435\u043a\u0430\u0431\u0440\u044c' "</option>" "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) # English locale with translation.override("en", deactivate=True): self.assertEqual("N j, Y", get_format("DATE_FORMAT")) self.assertEqual(0, get_format("FIRST_DAY_OF_WEEK")) self.assertEqual(".", get_format("DECIMAL_SEPARATOR")) self.assertEqual("Dec. 31, 2009", date_format(self.d)) self.assertEqual("December 2009", date_format(self.d, "YEAR_MONTH_FORMAT")) self.assertEqual( "12/31/2009 8:50 p.m.", date_format(self.dt, "SHORT_DATETIME_FORMAT") ) self.assertEqual("No localizable", localize("No localizable")) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66,666.666", localize(self.n)) self.assertEqual("99,999.999", localize(self.f)) self.assertEqual("10,000", localize(self.long)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666.666", localize(self.n)) self.assertEqual("99999.999", localize(self.f)) self.assertEqual("10000", localize(self.long)) self.assertEqual("Dec. 31, 2009", localize(self.d)) self.assertEqual("Dec. 31, 2009, 8:50 p.m.", localize(self.dt)) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual("66,666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99,999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("10,000", Template("{{ l }}").render(self.ctxt)) with self.settings(USE_THOUSAND_SEPARATOR=False): self.assertEqual("66666.666", Template("{{ n }}").render(self.ctxt)) self.assertEqual("99999.999", Template("{{ f }}").render(self.ctxt)) self.assertEqual("Dec. 31, 2009", Template("{{ d }}").render(self.ctxt)) self.assertEqual( "Dec. 31, 2009, 8:50 p.m.", Template("{{ dt }}").render(self.ctxt) ) self.assertEqual( "66666.67", Template("{{ n|floatformat:2 }}").render(self.ctxt) ) self.assertEqual( "100000.0", Template("{{ f|floatformat }}").render(self.ctxt) ) self.assertEqual( "66,666.67", Template('{{ n|floatformat:"2g" }}').render(self.ctxt), ) self.assertEqual( "100,000.0", Template('{{ f|floatformat:"g" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009", Template('{{ d|date:"SHORT_DATE_FORMAT" }}').render(self.ctxt), ) self.assertEqual( "12/31/2009 8:50 p.m.", Template('{{ dt|date:"SHORT_DATETIME_FORMAT" }}').render(self.ctxt), ) form5 = I18nForm( { "decimal_field": "66666.666", "float_field": "99999.999", "date_field": "12/31/2009", "datetime_field": "12/31/2009 20:50", "time_field": "20:50", "integer_field": "1234", } ) self.assertTrue(form5.is_valid()) self.assertEqual( decimal.Decimal("66666.666"), form5.cleaned_data["decimal_field"] ) self.assertEqual(99999.999, form5.cleaned_data["float_field"]) self.assertEqual( datetime.date(2009, 12, 31), form5.cleaned_data["date_field"] ) self.assertEqual( datetime.datetime(2009, 12, 31, 20, 50), form5.cleaned_data["datetime_field"], ) self.assertEqual(datetime.time(20, 50), form5.cleaned_data["time_field"]) self.assertEqual(1234, form5.cleaned_data["integer_field"]) form6 = SelectDateForm( { "date_field_month": "12", "date_field_day": "31", "date_field_year": "2009", } ) self.assertTrue(form6.is_valid()) self.assertEqual( datetime.date(2009, 12, 31), form6.cleaned_data["date_field"] ) self.assertHTMLEqual( '<select name="mydate_month" id="id_mydate_month">' '<option value="">---</option>' '<option value="1">January</option>' '<option value="2">February</option>' '<option value="3">March</option>' '<option value="4">April</option>' '<option value="5">May</option>' '<option value="6">June</option>' '<option value="7">July</option>' '<option value="8">August</option>' '<option value="9">September</option>' '<option value="10">October</option>' '<option value="11">November</option>' '<option value="12" selected>December</option>' "</select>" '<select name="mydate_day" id="id_mydate_day">' '<option value="">---</option>' '<option value="1">1</option>' '<option value="2">2</option>' '<option value="3">3</option>' '<option value="4">4</option>' '<option value="5">5</option>' '<option value="6">6</option>' '<option value="7">7</option>' '<option value="8">8</option>' '<option value="9">9</option>' '<option value="10">10</option>' '<option value="11">11</option>' '<option value="12">12</option>' '<option value="13">13</option>' '<option value="14">14</option>' '<option value="15">15</option>' '<option value="16">16</option>' '<option value="17">17</option>' '<option value="18">18</option>' '<option value="19">19</option>' '<option value="20">20</option>' '<option value="21">21</option>' '<option value="22">22</option>' '<option value="23">23</option>' '<option value="24">24</option>' '<option value="25">25</option>' '<option value="26">26</option>' '<option value="27">27</option>' '<option value="28">28</option>' '<option value="29">29</option>' '<option value="30">30</option>' '<option value="31" selected>31</option>' "</select>" '<select name="mydate_year" id="id_mydate_year">' '<option value="">---</option>' '<option value="2009" selected>2009</option>' '<option value="2010">2010</option>' '<option value="2011">2011</option>' '<option value="2012">2012</option>' '<option value="2013">2013</option>' '<option value="2014">2014</option>' '<option value="2015">2015</option>' '<option value="2016">2016</option>' '<option value="2017">2017</option>' '<option value="2018">2018</option>' "</select>", forms.SelectDateWidget(years=range(2009, 2019)).render( "mydate", datetime.date(2009, 12, 31) ), ) def test_sub_locales(self): """ Check if sublocales fall back to the main locale """ with self.settings(USE_THOUSAND_SEPARATOR=True): with translation.override("de-at", deactivate=True): self.assertEqual("66.666,666", Template("{{ n }}").render(self.ctxt)) with translation.override("es-us", deactivate=True): self.assertEqual("31 de Diciembre de 2009", date_format(self.d)) def test_localized_input(self): """ Tests if form input is correctly localized """ self.maxDiff = 1200 with translation.override("de-at", deactivate=True): form6 = CompanyForm( { "name": "acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_paid": decimal.Decimal("59.47"), "products_delivered": 12000, } ) self.assertTrue(form6.is_valid()) self.assertHTMLEqual( form6.as_ul(), '<li><label for="id_name">Name:</label>' '<input id="id_name" type="text" name="name" value="acme" ' ' maxlength="50" required></li>' '<li><label for="id_date_added">Date added:</label>' '<input type="text" name="date_added" value="31.12.2009 06:00:00" ' ' id="id_date_added" required></li>' '<li><label for="id_cents_paid">Cents paid:</label>' '<input type="text" name="cents_paid" value="59,47" id="id_cents_paid" ' " required></li>" '<li><label for="id_products_delivered">Products delivered:</label>' '<input type="text" name="products_delivered" value="12000" ' ' id="id_products_delivered" required>' "</li>", ) self.assertEqual( localize_input(datetime.datetime(2009, 12, 31, 6, 0, 0)), "31.12.2009 06:00:00", ) self.assertEqual( datetime.datetime(2009, 12, 31, 6, 0, 0), form6.cleaned_data["date_added"], ) with self.settings(USE_THOUSAND_SEPARATOR=True): # Checking for the localized "products_delivered" field self.assertInHTML( '<input type="text" name="products_delivered" ' 'value="12.000" id="id_products_delivered" required>', form6.as_ul(), ) def test_localized_input_func(self): tests = ( (True, "True"), (datetime.date(1, 1, 1), "0001-01-01"), (datetime.datetime(1, 1, 1), "0001-01-01 00:00:00"), ) with self.settings(USE_THOUSAND_SEPARATOR=True): for value, expected in tests: with self.subTest(value=value): self.assertEqual(localize_input(value), expected) def test_sanitize_strftime_format(self): for year in (1, 99, 999, 1000): dt = datetime.date(year, 1, 1) for fmt, expected in [ ("%C", "%02d" % (year // 100)), ("%F", "%04d-01-01" % year), ("%G", "%04d" % year), ("%Y", "%04d" % year), ]: with self.subTest(year=year, fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) def test_sanitize_strftime_format_with_escaped_percent(self): dt = datetime.date(1, 1, 1) for fmt, expected in [ ("%%C", "%C"), ("%%F", "%F"), ("%%G", "%G"), ("%%Y", "%Y"), ("%%%%C", "%%C"), ("%%%%F", "%%F"), ("%%%%G", "%%G"), ("%%%%Y", "%%Y"), ]: with self.subTest(fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) for year in (1, 99, 999, 1000): dt = datetime.date(year, 1, 1) for fmt, expected in [ ("%%%C", "%%%02d" % (year // 100)), ("%%%F", "%%%04d-01-01" % year), ("%%%G", "%%%04d" % year), ("%%%Y", "%%%04d" % year), ("%%%%%C", "%%%%%02d" % (year // 100)), ("%%%%%F", "%%%%%04d-01-01" % year), ("%%%%%G", "%%%%%04d" % year), ("%%%%%Y", "%%%%%04d" % year), ]: with self.subTest(year=year, fmt=fmt): fmt = sanitize_strftime_format(fmt) self.assertEqual(dt.strftime(fmt), expected) def test_sanitize_separators(self): """ Tests django.utils.formats.sanitize_separators. """ # Non-strings are untouched self.assertEqual(sanitize_separators(123), 123) with translation.override("ru", deactivate=True): # Russian locale has non-breaking space (\xa0) as thousand separator # Usual space is accepted too when sanitizing inputs with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual(sanitize_separators("1\xa0234\xa0567"), "1234567") self.assertEqual(sanitize_separators("77\xa0777,777"), "77777.777") self.assertEqual(sanitize_separators("12 345"), "12345") self.assertEqual(sanitize_separators("77 777,777"), "77777.777") with translation.override(None): # RemovedInDjango50Warning with self.settings(USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="."): self.assertEqual(sanitize_separators("12\xa0345"), "12\xa0345") with self.settings(USE_THOUSAND_SEPARATOR=True): with patch_formats( get_language(), THOUSAND_SEPARATOR=".", DECIMAL_SEPARATOR="," ): self.assertEqual(sanitize_separators("10.234"), "10234") # Suspicion that user entered dot as decimal separator (#22171) self.assertEqual(sanitize_separators("10.10"), "10.10") # RemovedInDjango50Warning: When the deprecation ends, remove # @ignore_warnings and USE_L10N=False. The assertions should remain # because format-related settings will take precedence over # locale-dictated formats. with ignore_warnings(category=RemovedInDjango50Warning): with self.settings(USE_L10N=False): with self.settings(DECIMAL_SEPARATOR=","): self.assertEqual(sanitize_separators("1001,10"), "1001.10") self.assertEqual(sanitize_separators("1001.10"), "1001.10") with self.settings( DECIMAL_SEPARATOR=",", THOUSAND_SEPARATOR=".", USE_THOUSAND_SEPARATOR=True, ): self.assertEqual(sanitize_separators("1.001,10"), "1001.10") self.assertEqual(sanitize_separators("1001,10"), "1001.10") self.assertEqual(sanitize_separators("1001.10"), "1001.10") # Invalid output. self.assertEqual(sanitize_separators("1,001.10"), "1.001.10") def test_iter_format_modules(self): """ Tests the iter_format_modules function. """ # Importing some format modules so that we can compare the returned # modules with these expected modules default_mod = import_module("django.conf.locale.de.formats") test_mod = import_module("i18n.other.locale.de.formats") test_mod2 = import_module("i18n.other2.locale.de.formats") with translation.override("de-at", deactivate=True): # Should return the correct default module when no setting is set self.assertEqual(list(iter_format_modules("de")), [default_mod]) # When the setting is a string, should return the given module and # the default module self.assertEqual( list(iter_format_modules("de", "i18n.other.locale")), [test_mod, default_mod], ) # When setting is a list of strings, should return the given # modules and the default module self.assertEqual( list( iter_format_modules( "de", ["i18n.other.locale", "i18n.other2.locale"] ) ), [test_mod, test_mod2, default_mod], ) def test_iter_format_modules_stability(self): """ Tests the iter_format_modules function always yields format modules in a stable and correct order in presence of both base ll and ll_CC formats. """ en_format_mod = import_module("django.conf.locale.en.formats") en_gb_format_mod = import_module("django.conf.locale.en_GB.formats") self.assertEqual( list(iter_format_modules("en-gb")), [en_gb_format_mod, en_format_mod] ) def test_get_format_modules_lang(self): with translation.override("de", deactivate=True): self.assertEqual(".", get_format("DECIMAL_SEPARATOR", lang="en")) def test_get_format_lazy_format(self): self.assertEqual(get_format(gettext_lazy("DATE_FORMAT")), "N j, Y") def test_localize_templatetag_and_filter(self): """ Test the {% localize %} templatetag and the localize/unlocalize filters. """ context = Context( {"int": 1455, "float": 3.14, "date": datetime.date(2016, 12, 31)} ) template1 = Template( "{% load l10n %}{% localize %}" "{{ int }}/{{ float }}/{{ date }}{% endlocalize %}; " "{% localize on %}{{ int }}/{{ float }}/{{ date }}{% endlocalize %}" ) template2 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{% localize off %}{{ int }}/{{ float }}/{{ date }};{% endlocalize %} " "{{ int }}/{{ float }}/{{ date }}" ) template3 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{{ int|unlocalize }}/{{ float|unlocalize }}/{{ date|unlocalize }}" ) template4 = Template( "{% load l10n %}{{ int }}/{{ float }}/{{ date }}; " "{{ int|localize }}/{{ float|localize }}/{{ date|localize }}" ) expected_localized = "1.455/3,14/31. Dezember 2016" expected_unlocalized = "1455/3.14/Dez. 31, 2016" output1 = "; ".join([expected_localized, expected_localized]) output2 = "; ".join( [expected_localized, expected_unlocalized, expected_localized] ) output3 = "; ".join([expected_localized, expected_unlocalized]) output4 = "; ".join([expected_unlocalized, expected_localized]) with translation.override("de", deactivate=True): # RemovedInDjango50Warning: When the deprecation ends, remove # @ignore_warnings and USE_L10N=False. The assertions should remain # because format-related settings will take precedence over # locale-dictated formats. with ignore_warnings(category=RemovedInDjango50Warning): with self.settings( USE_L10N=False, DATE_FORMAT="N j, Y", DECIMAL_SEPARATOR=".", NUMBER_GROUPING=0, USE_THOUSAND_SEPARATOR=True, ): self.assertEqual(template1.render(context), output1) self.assertEqual(template4.render(context), output4) with self.settings(USE_THOUSAND_SEPARATOR=True): self.assertEqual(template1.render(context), output1) self.assertEqual(template2.render(context), output2) self.assertEqual(template3.render(context), output3) def test_localized_off_numbers(self): """A string representation is returned for unlocalized numbers.""" template = Template( "{% load l10n %}{% localize off %}" "{{ int }}/{{ float }}/{{ decimal }}{% endlocalize %}" ) context = Context( {"int": 1455, "float": 3.14, "decimal": decimal.Decimal("24.1567")} ) with self.settings( DECIMAL_SEPARATOR=",", USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="°", NUMBER_GROUPING=2, ): self.assertEqual(template.render(context), "1455/3.14/24.1567") # RemovedInDjango50Warning. with ignore_warnings(category=RemovedInDjango50Warning): with self.settings( USE_L10N=False, DECIMAL_SEPARATOR=",", USE_THOUSAND_SEPARATOR=True, THOUSAND_SEPARATOR="°", NUMBER_GROUPING=2, ): self.assertEqual(template.render(context), "1455/3.14/24.1567") def test_localized_as_text_as_hidden_input(self): """ Form input with 'as_hidden' or 'as_text' is correctly localized. """ self.maxDiff = 1200 with translation.override("de-at", deactivate=True): template = Template( "{% load l10n %}{{ form.date_added }}; {{ form.cents_paid }}" ) template_as_text = Template( "{% load l10n %}" "{{ form.date_added.as_text }}; {{ form.cents_paid.as_text }}" ) template_as_hidden = Template( "{% load l10n %}" "{{ form.date_added.as_hidden }}; {{ form.cents_paid.as_hidden }}" ) form = CompanyForm( { "name": "acme", "date_added": datetime.datetime(2009, 12, 31, 6, 0, 0), "cents_paid": decimal.Decimal("59.47"), "products_delivered": 12000, } ) context = Context({"form": form}) self.assertTrue(form.is_valid()) self.assertHTMLEqual( template.render(context), '<input id="id_date_added" name="date_added" type="text" ' 'value="31.12.2009 06:00:00" required>;' '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' "required>", ) self.assertHTMLEqual( template_as_text.render(context), '<input id="id_date_added" name="date_added" type="text" ' 'value="31.12.2009 06:00:00" required>;' '<input id="id_cents_paid" name="cents_paid" type="text" value="59,47" ' "required>", ) self.assertHTMLEqual( template_as_hidden.render(context), '<input id="id_date_added" name="date_added" type="hidden" ' 'value="31.12.2009 06:00:00">;' '<input id="id_cents_paid" name="cents_paid" type="hidden" ' 'value="59,47">', ) def test_format_arbitrary_settings(self): self.assertEqual(get_format("DEBUG"), "DEBUG") def test_get_custom_format(self): reset_format_cache() with self.settings(FORMAT_MODULE_PATH="i18n.other.locale"): with translation.override("fr", deactivate=True): self.assertEqual("d/m/Y CUSTOM", get_format("CUSTOM_DAY_FORMAT")) def test_admin_javascript_supported_input_formats(self): """ The first input format for DATE_INPUT_FORMATS, TIME_INPUT_FORMATS, and DATETIME_INPUT_FORMATS must not contain %f since that's unsupported by the admin's time picker widget. """ regex = re.compile("%([^BcdHImMpSwxXyY%])") for language_code, language_name in settings.LANGUAGES: for format_name in ( "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ): with self.subTest(language=language_code, format=format_name): formatter = get_format(format_name, lang=language_code)[0] self.assertEqual( regex.findall(formatter), [], "%s locale's %s uses an unsupported format code." % (language_code, format_name), ) class MiscTests(SimpleTestCase): rf = RequestFactory() @override_settings(LANGUAGE_CODE="de") def test_english_fallback(self): """ With a non-English LANGUAGE_CODE and if the active language is English or one of its variants, the untranslated string should be returned (instead of falling back to LANGUAGE_CODE) (See #24413). """ self.assertEqual(gettext("Image"), "Bild") with translation.override("en"): self.assertEqual(gettext("Image"), "Image") with translation.override("en-us"): self.assertEqual(gettext("Image"), "Image") with translation.override("en-ca"): self.assertEqual(gettext("Image"), "Image") def test_parse_spec_http_header(self): """ Testing HTTP header parsing. First, we test that we can parse the values according to the spec (and that we extract all the pieces in the right order). """ tests = [ # Good headers ("de", [("de", 1.0)]), ("en-AU", [("en-au", 1.0)]), ("es-419", [("es-419", 1.0)]), ("*;q=1.00", [("*", 1.0)]), ("en-AU;q=0.123", [("en-au", 0.123)]), ("en-au;q=0.5", [("en-au", 0.5)]), ("en-au;q=1.0", [("en-au", 1.0)]), ("da, en-gb;q=0.25, en;q=0.5", [("da", 1.0), ("en", 0.5), ("en-gb", 0.25)]), ("en-au-xx", [("en-au-xx", 1.0)]), ( "de,en-au;q=0.75,en-us;q=0.5,en;q=0.25,es;q=0.125,fa;q=0.125", [ ("de", 1.0), ("en-au", 0.75), ("en-us", 0.5), ("en", 0.25), ("es", 0.125), ("fa", 0.125), ], ), ("*", [("*", 1.0)]), ("de;q=0.", [("de", 0.0)]), ("en; q=1,", [("en", 1.0)]), ("en; q=1.0, * ; q=0.5", [("en", 1.0), ("*", 0.5)]), # Bad headers ("en-gb;q=1.0000", []), ("en;q=0.1234", []), ("en;q=.2", []), ("abcdefghi-au", []), ("**", []), ("en,,gb", []), ("en-au;q=0.1.0", []), (("X" * 97) + "Z,en", []), ("da, en-gb;q=0.8, en;q=0.7,#", []), ("de;q=2.0", []), ("de;q=0.a", []), ("12-345", []), ("", []), ("en;q=1e0", []), ("en-au;q=1.0", []), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual( trans_real.parse_accept_lang_header(value), tuple(expected) ) def test_parse_literal_http_header(self): """ Now test that we parse a literal HTTP header correctly. """ g = get_language_from_request r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "pt-br"} self.assertEqual("pt-br", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "pt"} self.assertEqual("pt", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "es,de"} self.assertEqual("es", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "es-ar,de"} self.assertEqual("es-ar", g(r)) # This test assumes there won't be a Django translation to a US # variation of the Spanish language, a safe assumption. When the # user sets it as the preferred language, the main 'es' # translation should be selected instead. r.META = {"HTTP_ACCEPT_LANGUAGE": "es-us"} self.assertEqual(g(r), "es") # This tests the following scenario: there isn't a main language (zh) # translation of Django but there is a translation to variation (zh-hans) # the user sets zh-hans as the preferred language, it should be selected # by Django without falling back nor ignoring it. r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-hans,de"} self.assertEqual(g(r), "zh-hans") r.META = {"HTTP_ACCEPT_LANGUAGE": "NL"} self.assertEqual("nl", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "fy"} self.assertEqual("fy", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "ia"} self.assertEqual("ia", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "sr-latn"} self.assertEqual("sr-latn", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-hans"} self.assertEqual("zh-hans", g(r)) r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-hant"} self.assertEqual("zh-hant", g(r)) @override_settings( LANGUAGES=[ ("en", "English"), ("zh-hans", "Simplified Chinese"), ("zh-hant", "Traditional Chinese"), ] ) def test_support_for_deprecated_chinese_language_codes(self): """ Some browsers (Firefox, IE, etc.) use deprecated language codes. As these language codes will be removed in Django 1.9, these will be incorrectly matched. For example zh-tw (traditional) will be interpreted as zh-hans (simplified), which is wrong. So we should also accept these deprecated language codes. refs #18419 -- this is explicitly for browser compatibility """ g = get_language_from_request r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-cn,en"} self.assertEqual(g(r), "zh-hans") r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-tw,en"} self.assertEqual(g(r), "zh-hant") def test_special_fallback_language(self): """ Some languages may have special fallbacks that don't follow the simple 'fr-ca' -> 'fr' logic (notably Chinese codes). """ r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "zh-my,en"} self.assertEqual(get_language_from_request(r), "zh-hans") def test_subsequent_code_fallback_language(self): """ Subsequent language codes should be used when the language code is not supported. """ tests = [ ("zh-Hans-CN", "zh-hans"), ("zh-hans-mo", "zh-hans"), ("zh-hans-HK", "zh-hans"), ("zh-Hant-HK", "zh-hant"), ("zh-hant-tw", "zh-hant"), ("zh-hant-SG", "zh-hant"), ] r = self.rf.get("/") r.COOKIES = {} for value, expected in tests: with self.subTest(value=value): r.META = {"HTTP_ACCEPT_LANGUAGE": f"{value},en"} self.assertEqual(get_language_from_request(r), expected) def test_parse_language_cookie(self): """ Now test that we parse language preferences stored in a cookie correctly. """ g = get_language_from_request r = self.rf.get("/") r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: "pt-br"} r.META = {} self.assertEqual("pt-br", g(r)) r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: "pt"} r.META = {} self.assertEqual("pt", g(r)) r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: "es"} r.META = {"HTTP_ACCEPT_LANGUAGE": "de"} self.assertEqual("es", g(r)) # This test assumes there won't be a Django translation to a US # variation of the Spanish language, a safe assumption. When the # user sets it as the preferred language, the main 'es' # translation should be selected instead. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: "es-us"} r.META = {} self.assertEqual(g(r), "es") # This tests the following scenario: there isn't a main language (zh) # translation of Django but there is a translation to variation (zh-hans) # the user sets zh-hans as the preferred language, it should be selected # by Django without falling back nor ignoring it. r.COOKIES = {settings.LANGUAGE_COOKIE_NAME: "zh-hans"} r.META = {"HTTP_ACCEPT_LANGUAGE": "de"} self.assertEqual(g(r), "zh-hans") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("de", "German"), ("de-at", "Austrian German"), ("pt-br", "Portuguese (Brazil)"), ], ) def test_get_supported_language_variant_real(self): g = trans_real.get_supported_language_variant self.assertEqual(g("en"), "en") self.assertEqual(g("en-gb"), "en") self.assertEqual(g("de"), "de") self.assertEqual(g("de-at"), "de-at") self.assertEqual(g("de-ch"), "de") self.assertEqual(g("pt-br"), "pt-br") self.assertEqual(g("pt"), "pt-br") self.assertEqual(g("pt-pt"), "pt-br") with self.assertRaises(LookupError): g("pt", strict=True) with self.assertRaises(LookupError): g("pt-pt", strict=True) with self.assertRaises(LookupError): g("xyz") with self.assertRaises(LookupError): g("xy-zz") def test_get_supported_language_variant_null(self): g = trans_null.get_supported_language_variant self.assertEqual(g(settings.LANGUAGE_CODE), settings.LANGUAGE_CODE) with self.assertRaises(LookupError): g("pt") with self.assertRaises(LookupError): g("de") with self.assertRaises(LookupError): g("de-at") with self.assertRaises(LookupError): g("de", strict=True) with self.assertRaises(LookupError): g("de-at", strict=True) with self.assertRaises(LookupError): g("xyz") @override_settings( LANGUAGES=[ ("en", "English"), ("en-latn-us", "Latin English"), ("en-Latn-US", "BCP 47 case format"), ("de", "German"), ("de-1996", "German, orthography of 1996"), ("de-at", "Austrian German"), ("de-ch-1901", "German, Swiss variant, traditional orthography"), ("i-mingo", "Mingo"), ("kl-tunumiit", "Tunumiisiut"), ("nan-hani-tw", "Hanji"), ("pl", "Polish"), ], ) def test_get_language_from_path_real(self): g = trans_real.get_language_from_path tests = [ ("/pl/", "pl"), ("/pl", "pl"), ("/xyz/", None), ("/en/", "en"), ("/en-gb/", "en"), ("/en-latn-us/", "en-latn-us"), ("/en-Latn-US/", "en-Latn-US"), ("/de/", "de"), ("/de-1996/", "de-1996"), ("/de-at/", "de-at"), ("/de-ch/", "de"), ("/de-ch-1901/", "de-ch-1901"), ("/de-simple-page-test/", None), ("/i-mingo/", "i-mingo"), ("/kl-tunumiit/", "kl-tunumiit"), ("/nan-hani-tw/", "nan-hani-tw"), ] for path, language in tests: with self.subTest(path=path): self.assertEqual(g(path), language) def test_get_language_from_path_null(self): g = trans_null.get_language_from_path self.assertIsNone(g("/pl/")) self.assertIsNone(g("/pl")) self.assertIsNone(g("/xyz/")) def test_cache_resetting(self): """ After setting LANGUAGE, the cache should be cleared and languages previously valid should not be used (#14170). """ g = get_language_from_request r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "pt-br"} self.assertEqual("pt-br", g(r)) with self.settings(LANGUAGES=[("en", "English")]): self.assertNotEqual("pt-br", g(r)) def test_i18n_patterns_returns_list(self): with override_settings(USE_I18N=False): self.assertIsInstance(i18n_patterns([]), list) with override_settings(USE_I18N=True): self.assertIsInstance(i18n_patterns([]), list) class ResolutionOrderI18NTests(SimpleTestCase): def setUp(self): super().setUp() activate("de") def tearDown(self): deactivate() super().tearDown() def assertGettext(self, msgid, msgstr): result = gettext(msgid) self.assertIn( msgstr, result, "The string '%s' isn't in the translation of '%s'; the actual result is " "'%s'." % (msgstr, msgid, result), ) class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): @override_settings(LANGUAGE_CODE="de") def test_app_translation(self): # Original translation. self.assertGettext("Date/time", "Datum/Zeit") # Different translation. with self.modify_settings(INSTALLED_APPS={"append": "i18n.resolution"}): # Force refreshing translations. activate("de") # Doesn't work because it's added later in the list. self.assertGettext("Date/time", "Datum/Zeit") with self.modify_settings( INSTALLED_APPS={"remove": "django.contrib.admin.apps.SimpleAdminConfig"} ): # Force refreshing translations. activate("de") # Unless the original is removed from the list. self.assertGettext("Date/time", "Datum/Zeit (APP)") @override_settings(LOCALE_PATHS=extended_locale_paths) class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_locale_paths_translation(self): self.assertGettext("Time", "LOCALE_PATHS") def test_locale_paths_override_app_translation(self): with self.settings(INSTALLED_APPS=["i18n.resolution"]): self.assertGettext("Time", "LOCALE_PATHS") class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_django_fallback(self): self.assertEqual(gettext("Date/time"), "Datum/Zeit") @override_settings(INSTALLED_APPS=["i18n.territorial_fallback"]) class TranslationFallbackI18NTests(ResolutionOrderI18NTests): def test_sparse_territory_catalog(self): """ Untranslated strings for territorial language variants use the translations of the generic language. In this case, the de-de translation falls back to de. """ with translation.override("de-de"): self.assertGettext("Test 1 (en)", "(de-de)") self.assertGettext("Test 2 (en)", "(de)") class TestModels(TestCase): def test_lazy(self): tm = TestModel() tm.save() def test_safestr(self): c = Company(cents_paid=12, products_delivered=1) c.name = SafeString("Iñtërnâtiônàlizætiøn1") c.save() class TestLanguageInfo(SimpleTestCase): def test_localized_language_info(self): li = get_language_info("de") self.assertEqual(li["code"], "de") self.assertEqual(li["name_local"], "Deutsch") self.assertEqual(li["name"], "German") self.assertIs(li["bidi"], False) def test_unknown_language_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx"): get_language_info("xx") with translation.override("xx"): # A language with no translation catalogs should fallback to the # untranslated string. self.assertEqual(gettext("Title"), "Title") def test_unknown_only_country_code(self): li = get_language_info("de-xx") self.assertEqual(li["code"], "de") self.assertEqual(li["name_local"], "Deutsch") self.assertEqual(li["name"], "German") self.assertIs(li["bidi"], False) def test_unknown_language_code_and_country_code(self): with self.assertRaisesMessage(KeyError, "Unknown language code xx-xx and xx"): get_language_info("xx-xx") def test_fallback_language_code(self): """ get_language_info return the first fallback language info if the lang_info struct does not contain the 'name' key. """ li = get_language_info("zh-my") self.assertEqual(li["code"], "zh-hans") li = get_language_info("zh-hans") self.assertEqual(li["code"], "zh-hans") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("fr", "French"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls", ) class LocaleMiddlewareTests(TestCase): def test_streaming_response(self): # Regression test for #5241 response = self.client.get("/fr/streaming/") self.assertContains(response, "Oui/Non") response = self.client.get("/en/streaming/") self.assertContains(response, "Yes/No") @override_settings( USE_I18N=True, LANGUAGES=[ ("en", "English"), ("de", "German"), ("fr", "French"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls_default_unprefixed", LANGUAGE_CODE="en", ) class UnprefixedDefaultLanguageTests(SimpleTestCase): def test_default_lang_without_prefix(self): """ With i18n_patterns(..., prefix_default_language=False), the default language (settings.LANGUAGE_CODE) should be accessible without a prefix. """ response = self.client.get("/simple/") self.assertEqual(response.content, b"Yes") def test_other_lang_with_prefix(self): response = self.client.get("/fr/simple/") self.assertEqual(response.content, b"Oui") def test_unprefixed_language_other_than_accept_language(self): response = self.client.get("/simple/", HTTP_ACCEPT_LANGUAGE="fr") self.assertEqual(response.content, b"Yes") def test_page_with_dash(self): # A page starting with /de* shouldn't match the 'de' language code. response = self.client.get("/de-simple-page-test/") self.assertEqual(response.content, b"Yes") def test_no_redirect_on_404(self): """ A request for a nonexistent URL shouldn't cause a redirect to /<default_language>/<request_url> when prefix_default_language=False and /<default_language>/<request_url> has a URL match (#27402). """ # A match for /group1/group2/ must exist for this to act as a # regression test. response = self.client.get("/group1/group2/") self.assertEqual(response.status_code, 200) response = self.client.get("/nonexistent/") self.assertEqual(response.status_code, 404) @override_settings( USE_I18N=True, LANGUAGES=[ ("bg", "Bulgarian"), ("en-us", "English"), ("pt-br", "Portuguese (Brazil)"), ], MIDDLEWARE=[ "django.middleware.locale.LocaleMiddleware", "django.middleware.common.CommonMiddleware", ], ROOT_URLCONF="i18n.urls", ) class CountrySpecificLanguageTests(SimpleTestCase): rf = RequestFactory() def test_check_for_language(self): self.assertTrue(check_for_language("en")) self.assertTrue(check_for_language("en-us")) self.assertTrue(check_for_language("en-US")) self.assertFalse(check_for_language("en_US")) self.assertTrue(check_for_language("be")) self.assertTrue(check_for_language("be@latin")) self.assertTrue(check_for_language("sr-RS@latin")) self.assertTrue(check_for_language("sr-RS@12345")) self.assertFalse(check_for_language("en-ü")) self.assertFalse(check_for_language("en\x00")) self.assertFalse(check_for_language(None)) self.assertFalse(check_for_language("be@ ")) # Specifying encoding is not supported (Django enforces UTF-8) self.assertFalse(check_for_language("tr-TR.UTF-8")) self.assertFalse(check_for_language("tr-TR.UTF8")) self.assertFalse(check_for_language("de-DE.utf-8")) def test_check_for_language_null(self): self.assertIs(trans_null.check_for_language("en"), True) def test_get_language_from_request(self): # issue 19919 r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "en-US,en;q=0.8,bg;q=0.6,ru;q=0.4"} lang = get_language_from_request(r) self.assertEqual("en-us", lang) r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "bg-bg,en-US;q=0.8,en;q=0.6,ru;q=0.4"} lang = get_language_from_request(r) self.assertEqual("bg", lang) def test_get_language_from_request_null(self): lang = trans_null.get_language_from_request(None) self.assertEqual(lang, "en") with override_settings(LANGUAGE_CODE="de"): lang = trans_null.get_language_from_request(None) self.assertEqual(lang, "de") def test_specific_language_codes(self): # issue 11915 r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} lang = get_language_from_request(r) self.assertEqual("pt-br", lang) r = self.rf.get("/") r.COOKIES = {} r.META = {"HTTP_ACCEPT_LANGUAGE": "pt-pt,en-US;q=0.8,en;q=0.6,ru;q=0.4"} lang = get_language_from_request(r) self.assertEqual("pt-br", lang) class TranslationFilesMissing(SimpleTestCase): def setUp(self): super().setUp() self.gettext_find_builtin = gettext_module.find def tearDown(self): gettext_module.find = self.gettext_find_builtin super().tearDown() def patchGettextFind(self): gettext_module.find = lambda *args, **kw: None def test_failure_finding_default_mo_files(self): """OSError is raised if the default language is unparseable.""" self.patchGettextFind() trans_real._translations = {} with self.assertRaises(OSError): activate("en") class NonDjangoLanguageTests(SimpleTestCase): """ A language non present in default Django languages can still be installed/used by a Django project. """ @override_settings( USE_I18N=True, LANGUAGES=[ ("en-us", "English"), ("xxx", "Somelanguage"), ], LANGUAGE_CODE="xxx", LOCALE_PATHS=[os.path.join(here, "commands", "locale")], ) def test_non_django_language(self): self.assertEqual(get_language(), "xxx") self.assertEqual(gettext("year"), "reay") @override_settings(USE_I18N=True) def test_check_for_language(self): with tempfile.TemporaryDirectory() as app_dir: os.makedirs(os.path.join(app_dir, "locale", "dummy_Lang", "LC_MESSAGES")) open( os.path.join( app_dir, "locale", "dummy_Lang", "LC_MESSAGES", "django.mo" ), "w", ).close() app_config = AppConfig("dummy_app", AppModuleStub(__path__=[app_dir])) with mock.patch( "django.apps.apps.get_app_configs", return_value=[app_config] ): self.assertIs(check_for_language("dummy-lang"), True) @override_settings( USE_I18N=True, LANGUAGES=[ ("en-us", "English"), # xyz language has no locale files ("xyz", "XYZ"), ], ) @translation.override("xyz") def test_plural_non_django_language(self): self.assertEqual(get_language(), "xyz") self.assertEqual(ngettext("year", "years", 2), "years") @override_settings(USE_I18N=True) class WatchForTranslationChangesTests(SimpleTestCase): @override_settings(USE_I18N=False) def test_i18n_disabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_not_called() def test_i18n_enabled(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) self.assertGreater(mocked_sender.watch_dir.call_count, 1) def test_i18n_locale_paths(self): mocked_sender = mock.MagicMock() with tempfile.TemporaryDirectory() as app_dir: with self.settings(LOCALE_PATHS=[app_dir]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_any_call(Path(app_dir), "**/*.mo") def test_i18n_app_dirs(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["i18n.sampleproject"]): watch_for_translation_changes(mocked_sender) project_dir = Path(__file__).parent / "sampleproject" / "locale" mocked_sender.watch_dir.assert_any_call(project_dir, "**/*.mo") def test_i18n_app_dirs_ignore_django_apps(self): mocked_sender = mock.MagicMock() with self.settings(INSTALLED_APPS=["django.contrib.admin"]): watch_for_translation_changes(mocked_sender) mocked_sender.watch_dir.assert_called_once_with(Path("locale"), "**/*.mo") def test_i18n_local_locale(self): mocked_sender = mock.MagicMock() watch_for_translation_changes(mocked_sender) locale_dir = Path(__file__).parent / "locale" mocked_sender.watch_dir.assert_any_call(locale_dir, "**/*.mo") class TranslationFileChangedTests(SimpleTestCase): def setUp(self): self.gettext_translations = gettext_module._translations.copy() self.trans_real_translations = trans_real._translations.copy() def tearDown(self): gettext._translations = self.gettext_translations trans_real._translations = self.trans_real_translations def test_ignores_non_mo_files(self): gettext_module._translations = {"foo": "bar"} path = Path("test.py") self.assertIsNone(translation_file_changed(None, path)) self.assertEqual(gettext_module._translations, {"foo": "bar"}) def test_resets_cache_with_mo_files(self): gettext_module._translations = {"foo": "bar"} trans_real._translations = {"foo": "bar"} trans_real._default = 1 trans_real._active = False path = Path("test.mo") self.assertIs(translation_file_changed(None, path), True) self.assertEqual(gettext_module._translations, {}) self.assertEqual(trans_real._translations, {}) self.assertIsNone(trans_real._default) self.assertIsInstance(trans_real._active, Local) class UtilsTests(SimpleTestCase): def test_round_away_from_one(self): tests = [ (0, 0), (0.0, 0), (0.25, 0), (0.5, 0), (0.75, 0), (1, 1), (1.0, 1), (1.25, 2), (1.5, 2), (1.75, 2), (-0.0, 0), (-0.25, -1), (-0.5, -1), (-0.75, -1), (-1, -1), (-1.0, -1), (-1.25, -2), (-1.5, -2), (-1.75, -2), ] for value, expected in tests: with self.subTest(value=value): self.assertEqual(round_away_from_one(value), expected)
c1aec63ca39b765dfcb9595598386314a4fafc1f20a44062bfa4257a5c2dd82d
import collections.abc from datetime import datetime from math import ceil from operator import attrgetter from unittest import skipUnless from django.core.exceptions import FieldError from django.db import connection, models from django.db.models import ( BooleanField, Case, Exists, ExpressionWrapper, F, Max, OuterRef, Q, Subquery, Value, When, ) from django.db.models.functions import Cast, Substr from django.db.models.lookups import ( Exact, GreaterThan, GreaterThanOrEqual, IsNull, LessThan, LessThanOrEqual, ) from django.test import TestCase, skipUnlessDBFeature from django.test.utils import isolate_apps from .models import ( Article, Author, Freebie, Game, IsNullWithNoneAsRHS, Player, Product, Season, Stock, Tag, ) class LookupTests(TestCase): @classmethod def setUpTestData(cls): # Create a few Authors. cls.au1 = Author.objects.create(name="Author 1", alias="a1") cls.au2 = Author.objects.create(name="Author 2", alias="a2") # Create a few Articles. cls.a1 = Article.objects.create( headline="Article 1", pub_date=datetime(2005, 7, 26), author=cls.au1, slug="a1", ) cls.a2 = Article.objects.create( headline="Article 2", pub_date=datetime(2005, 7, 27), author=cls.au1, slug="a2", ) cls.a3 = Article.objects.create( headline="Article 3", pub_date=datetime(2005, 7, 27), author=cls.au1, slug="a3", ) cls.a4 = Article.objects.create( headline="Article 4", pub_date=datetime(2005, 7, 28), author=cls.au1, slug="a4", ) cls.a5 = Article.objects.create( headline="Article 5", pub_date=datetime(2005, 8, 1, 9, 0), author=cls.au2, slug="a5", ) cls.a6 = Article.objects.create( headline="Article 6", pub_date=datetime(2005, 8, 1, 8, 0), author=cls.au2, slug="a6", ) cls.a7 = Article.objects.create( headline="Article 7", pub_date=datetime(2005, 7, 27), author=cls.au2, slug="a7", ) # Create a few Tags. cls.t1 = Tag.objects.create(name="Tag 1") cls.t1.articles.add(cls.a1, cls.a2, cls.a3) cls.t2 = Tag.objects.create(name="Tag 2") cls.t2.articles.add(cls.a3, cls.a4, cls.a5) cls.t3 = Tag.objects.create(name="Tag 3") cls.t3.articles.add(cls.a5, cls.a6, cls.a7) def test_exists(self): # We can use .exists() to check that there are some self.assertTrue(Article.objects.exists()) for a in Article.objects.all(): a.delete() # There should be none now! self.assertFalse(Article.objects.exists()) def test_lookup_int_as_str(self): # Integer value can be queried using string self.assertSequenceEqual( Article.objects.filter(id__iexact=str(self.a1.id)), [self.a1], ) @skipUnlessDBFeature("supports_date_lookup_using_string") def test_lookup_date_as_str(self): # A date lookup can be performed using a string search self.assertSequenceEqual( Article.objects.filter(pub_date__startswith="2005"), [self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) def test_iterator(self): # Each QuerySet gets iterator(), which is a generator that "lazily" # returns results using database-level iteration. self.assertIsInstance(Article.objects.iterator(), collections.abc.Iterator) self.assertQuerysetEqual( Article.objects.iterator(), [ "Article 5", "Article 6", "Article 4", "Article 2", "Article 3", "Article 7", "Article 1", ], transform=attrgetter("headline"), ) # iterator() can be used on any QuerySet. self.assertQuerysetEqual( Article.objects.filter(headline__endswith="4").iterator(), ["Article 4"], transform=attrgetter("headline"), ) def test_count(self): # count() returns the number of objects matching search criteria. self.assertEqual(Article.objects.count(), 7) self.assertEqual( Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).count(), 3 ) self.assertEqual( Article.objects.filter(headline__startswith="Blah blah").count(), 0 ) # count() should respect sliced query sets. articles = Article.objects.all() self.assertEqual(articles.count(), 7) self.assertEqual(articles[:4].count(), 4) self.assertEqual(articles[1:100].count(), 6) self.assertEqual(articles[10:100].count(), 0) # Date and date/time lookups can also be done with strings. self.assertEqual( Article.objects.filter(pub_date__exact="2005-07-27 00:00:00").count(), 3 ) def test_in_bulk(self): # in_bulk() takes a list of IDs and returns a dictionary mapping IDs to objects. arts = Article.objects.in_bulk([self.a1.id, self.a2.id]) self.assertEqual(arts[self.a1.id], self.a1) self.assertEqual(arts[self.a2.id], self.a2) self.assertEqual( Article.objects.in_bulk(), { self.a1.id: self.a1, self.a2.id: self.a2, self.a3.id: self.a3, self.a4.id: self.a4, self.a5.id: self.a5, self.a6.id: self.a6, self.a7.id: self.a7, }, ) self.assertEqual(Article.objects.in_bulk([self.a3.id]), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk({self.a3.id}), {self.a3.id: self.a3}) self.assertEqual( Article.objects.in_bulk(frozenset([self.a3.id])), {self.a3.id: self.a3} ) self.assertEqual(Article.objects.in_bulk((self.a3.id,)), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk([1000]), {}) self.assertEqual(Article.objects.in_bulk([]), {}) self.assertEqual( Article.objects.in_bulk(iter([self.a1.id])), {self.a1.id: self.a1} ) self.assertEqual(Article.objects.in_bulk(iter([])), {}) with self.assertRaises(TypeError): Article.objects.in_bulk(headline__startswith="Blah") def test_in_bulk_lots_of_ids(self): test_range = 2000 max_query_params = connection.features.max_query_params expected_num_queries = ( ceil(test_range / max_query_params) if max_query_params else 1 ) Author.objects.bulk_create( [Author() for i in range(test_range - Author.objects.count())] ) authors = {author.pk: author for author in Author.objects.all()} with self.assertNumQueries(expected_num_queries): self.assertEqual(Author.objects.in_bulk(authors), authors) def test_in_bulk_with_field(self): self.assertEqual( Article.objects.in_bulk( [self.a1.slug, self.a2.slug, self.a3.slug], field_name="slug" ), { self.a1.slug: self.a1, self.a2.slug: self.a2, self.a3.slug: self.a3, }, ) def test_in_bulk_meta_constraint(self): season_2011 = Season.objects.create(year=2011) season_2012 = Season.objects.create(year=2012) Season.objects.create(year=2013) self.assertEqual( Season.objects.in_bulk( [season_2011.year, season_2012.year], field_name="year", ), {season_2011.year: season_2011, season_2012.year: season_2012}, ) def test_in_bulk_non_unique_field(self): msg = "in_bulk()'s field_name must be a unique field but 'author' isn't." with self.assertRaisesMessage(ValueError, msg): Article.objects.in_bulk([self.au1], field_name="author") @skipUnlessDBFeature("can_distinct_on_fields") def test_in_bulk_distinct_field(self): self.assertEqual( Article.objects.order_by("headline") .distinct("headline") .in_bulk( [self.a1.headline, self.a5.headline], field_name="headline", ), {self.a1.headline: self.a1, self.a5.headline: self.a5}, ) @skipUnlessDBFeature("can_distinct_on_fields") def test_in_bulk_multiple_distinct_field(self): msg = "in_bulk()'s field_name must be a unique field but 'pub_date' isn't." with self.assertRaisesMessage(ValueError, msg): Article.objects.order_by("headline", "pub_date").distinct( "headline", "pub_date", ).in_bulk(field_name="pub_date") @isolate_apps("lookup") def test_in_bulk_non_unique_meta_constaint(self): class Model(models.Model): ean = models.CharField(max_length=100) brand = models.CharField(max_length=100) name = models.CharField(max_length=80) class Meta: constraints = [ models.UniqueConstraint( fields=["ean"], name="partial_ean_unique", condition=models.Q(is_active=True), ), models.UniqueConstraint( fields=["brand", "name"], name="together_brand_name_unique", ), ] msg = "in_bulk()'s field_name must be a unique field but '%s' isn't." for field_name in ["brand", "ean"]: with self.subTest(field_name=field_name): with self.assertRaisesMessage(ValueError, msg % field_name): Model.objects.in_bulk(field_name=field_name) def test_in_bulk_sliced_queryset(self): msg = "Cannot use 'limit' or 'offset' with in_bulk()." with self.assertRaisesMessage(TypeError, msg): Article.objects.all()[0:5].in_bulk([self.a1.id, self.a2.id]) def test_values(self): # values() returns a list of dictionaries instead of object instances -- # and you can specify which fields you want to retrieve. self.assertSequenceEqual( Article.objects.values("headline"), [ {"headline": "Article 5"}, {"headline": "Article 6"}, {"headline": "Article 4"}, {"headline": "Article 2"}, {"headline": "Article 3"}, {"headline": "Article 7"}, {"headline": "Article 1"}, ], ) self.assertSequenceEqual( Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).values("id"), [{"id": self.a2.id}, {"id": self.a3.id}, {"id": self.a7.id}], ) self.assertSequenceEqual( Article.objects.values("id", "headline"), [ {"id": self.a5.id, "headline": "Article 5"}, {"id": self.a6.id, "headline": "Article 6"}, {"id": self.a4.id, "headline": "Article 4"}, {"id": self.a2.id, "headline": "Article 2"}, {"id": self.a3.id, "headline": "Article 3"}, {"id": self.a7.id, "headline": "Article 7"}, {"id": self.a1.id, "headline": "Article 1"}, ], ) # You can use values() with iterator() for memory savings, # because iterator() uses database-level iteration. self.assertSequenceEqual( list(Article.objects.values("id", "headline").iterator()), [ {"headline": "Article 5", "id": self.a5.id}, {"headline": "Article 6", "id": self.a6.id}, {"headline": "Article 4", "id": self.a4.id}, {"headline": "Article 2", "id": self.a2.id}, {"headline": "Article 3", "id": self.a3.id}, {"headline": "Article 7", "id": self.a7.id}, {"headline": "Article 1", "id": self.a1.id}, ], ) # The values() method works with "extra" fields specified in extra(select). self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id + 1"}).values( "id", "id_plus_one" ), [ {"id": self.a5.id, "id_plus_one": self.a5.id + 1}, {"id": self.a6.id, "id_plus_one": self.a6.id + 1}, {"id": self.a4.id, "id_plus_one": self.a4.id + 1}, {"id": self.a2.id, "id_plus_one": self.a2.id + 1}, {"id": self.a3.id, "id_plus_one": self.a3.id + 1}, {"id": self.a7.id, "id_plus_one": self.a7.id + 1}, {"id": self.a1.id, "id_plus_one": self.a1.id + 1}, ], ) data = { "id_plus_one": "id+1", "id_plus_two": "id+2", "id_plus_three": "id+3", "id_plus_four": "id+4", "id_plus_five": "id+5", "id_plus_six": "id+6", "id_plus_seven": "id+7", "id_plus_eight": "id+8", } self.assertSequenceEqual( Article.objects.filter(id=self.a1.id).extra(select=data).values(*data), [ { "id_plus_one": self.a1.id + 1, "id_plus_two": self.a1.id + 2, "id_plus_three": self.a1.id + 3, "id_plus_four": self.a1.id + 4, "id_plus_five": self.a1.id + 5, "id_plus_six": self.a1.id + 6, "id_plus_seven": self.a1.id + 7, "id_plus_eight": self.a1.id + 8, } ], ) # You can specify fields from forward and reverse relations, just like filter(). self.assertSequenceEqual( Article.objects.values("headline", "author__name"), [ {"headline": self.a5.headline, "author__name": self.au2.name}, {"headline": self.a6.headline, "author__name": self.au2.name}, {"headline": self.a4.headline, "author__name": self.au1.name}, {"headline": self.a2.headline, "author__name": self.au1.name}, {"headline": self.a3.headline, "author__name": self.au1.name}, {"headline": self.a7.headline, "author__name": self.au2.name}, {"headline": self.a1.headline, "author__name": self.au1.name}, ], ) self.assertSequenceEqual( Author.objects.values("name", "article__headline").order_by( "name", "article__headline" ), [ {"name": self.au1.name, "article__headline": self.a1.headline}, {"name": self.au1.name, "article__headline": self.a2.headline}, {"name": self.au1.name, "article__headline": self.a3.headline}, {"name": self.au1.name, "article__headline": self.a4.headline}, {"name": self.au2.name, "article__headline": self.a5.headline}, {"name": self.au2.name, "article__headline": self.a6.headline}, {"name": self.au2.name, "article__headline": self.a7.headline}, ], ) self.assertSequenceEqual( ( Author.objects.values( "name", "article__headline", "article__tag__name" ).order_by("name", "article__headline", "article__tag__name") ), [ { "name": self.au1.name, "article__headline": self.a1.headline, "article__tag__name": self.t1.name, }, { "name": self.au1.name, "article__headline": self.a2.headline, "article__tag__name": self.t1.name, }, { "name": self.au1.name, "article__headline": self.a3.headline, "article__tag__name": self.t1.name, }, { "name": self.au1.name, "article__headline": self.a3.headline, "article__tag__name": self.t2.name, }, { "name": self.au1.name, "article__headline": self.a4.headline, "article__tag__name": self.t2.name, }, { "name": self.au2.name, "article__headline": self.a5.headline, "article__tag__name": self.t2.name, }, { "name": self.au2.name, "article__headline": self.a5.headline, "article__tag__name": self.t3.name, }, { "name": self.au2.name, "article__headline": self.a6.headline, "article__tag__name": self.t3.name, }, { "name": self.au2.name, "article__headline": self.a7.headline, "article__tag__name": self.t3.name, }, ], ) # However, an exception FieldDoesNotExist will be thrown if you specify # a nonexistent field name in values() (a field that is neither in the # model nor in extra(select)). msg = ( "Cannot resolve keyword 'id_plus_two' into field. Choices are: " "author, author_id, headline, id, id_plus_one, pub_date, slug, tag" ) with self.assertRaisesMessage(FieldError, msg): Article.objects.extra(select={"id_plus_one": "id + 1"}).values( "id", "id_plus_two" ) # If you don't specify field names to values(), all are returned. self.assertSequenceEqual( Article.objects.filter(id=self.a5.id).values(), [ { "id": self.a5.id, "author_id": self.au2.id, "headline": "Article 5", "pub_date": datetime(2005, 8, 1, 9, 0), "slug": "a5", } ], ) def test_values_list(self): # values_list() is similar to values(), except that the results are # returned as a list of tuples, rather than a list of dictionaries. # Within each tuple, the order of the elements is the same as the order # of fields in the values_list() call. self.assertSequenceEqual( Article.objects.values_list("headline"), [ ("Article 5",), ("Article 6",), ("Article 4",), ("Article 2",), ("Article 3",), ("Article 7",), ("Article 1",), ], ) self.assertSequenceEqual( Article.objects.values_list("id").order_by("id"), [ (self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,), ], ) self.assertSequenceEqual( Article.objects.values_list("id", flat=True).order_by("id"), [ self.a1.id, self.a2.id, self.a3.id, self.a4.id, self.a5.id, self.a6.id, self.a7.id, ], ) self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id+1"}) .order_by("id") .values_list("id"), [ (self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,), ], ) self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id+1"}) .order_by("id") .values_list("id_plus_one", "id"), [ (self.a1.id + 1, self.a1.id), (self.a2.id + 1, self.a2.id), (self.a3.id + 1, self.a3.id), (self.a4.id + 1, self.a4.id), (self.a5.id + 1, self.a5.id), (self.a6.id + 1, self.a6.id), (self.a7.id + 1, self.a7.id), ], ) self.assertSequenceEqual( Article.objects.extra(select={"id_plus_one": "id+1"}) .order_by("id") .values_list("id", "id_plus_one"), [ (self.a1.id, self.a1.id + 1), (self.a2.id, self.a2.id + 1), (self.a3.id, self.a3.id + 1), (self.a4.id, self.a4.id + 1), (self.a5.id, self.a5.id + 1), (self.a6.id, self.a6.id + 1), (self.a7.id, self.a7.id + 1), ], ) args = ("name", "article__headline", "article__tag__name") self.assertSequenceEqual( Author.objects.values_list(*args).order_by(*args), [ (self.au1.name, self.a1.headline, self.t1.name), (self.au1.name, self.a2.headline, self.t1.name), (self.au1.name, self.a3.headline, self.t1.name), (self.au1.name, self.a3.headline, self.t2.name), (self.au1.name, self.a4.headline, self.t2.name), (self.au2.name, self.a5.headline, self.t2.name), (self.au2.name, self.a5.headline, self.t3.name), (self.au2.name, self.a6.headline, self.t3.name), (self.au2.name, self.a7.headline, self.t3.name), ], ) with self.assertRaises(TypeError): Article.objects.values_list("id", "headline", flat=True) def test_get_next_previous_by(self): # Every DateField and DateTimeField creates get_next_by_FOO() and # get_previous_by_FOO() methods. In the case of identical date values, # these methods will use the ID as a fallback check. This guarantees # that no records are skipped or duplicated. self.assertEqual(repr(self.a1.get_next_by_pub_date()), "<Article: Article 2>") self.assertEqual(repr(self.a2.get_next_by_pub_date()), "<Article: Article 3>") self.assertEqual( repr(self.a2.get_next_by_pub_date(headline__endswith="6")), "<Article: Article 6>", ) self.assertEqual(repr(self.a3.get_next_by_pub_date()), "<Article: Article 7>") self.assertEqual(repr(self.a4.get_next_by_pub_date()), "<Article: Article 6>") with self.assertRaises(Article.DoesNotExist): self.a5.get_next_by_pub_date() self.assertEqual(repr(self.a6.get_next_by_pub_date()), "<Article: Article 5>") self.assertEqual(repr(self.a7.get_next_by_pub_date()), "<Article: Article 4>") self.assertEqual( repr(self.a7.get_previous_by_pub_date()), "<Article: Article 3>" ) self.assertEqual( repr(self.a6.get_previous_by_pub_date()), "<Article: Article 4>" ) self.assertEqual( repr(self.a5.get_previous_by_pub_date()), "<Article: Article 6>" ) self.assertEqual( repr(self.a4.get_previous_by_pub_date()), "<Article: Article 7>" ) self.assertEqual( repr(self.a3.get_previous_by_pub_date()), "<Article: Article 2>" ) self.assertEqual( repr(self.a2.get_previous_by_pub_date()), "<Article: Article 1>" ) def test_escaping(self): # Underscores, percent signs and backslashes have special meaning in the # underlying SQL code, but Django handles the quoting of them automatically. a8 = Article.objects.create( headline="Article_ with underscore", pub_date=datetime(2005, 11, 20) ) self.assertSequenceEqual( Article.objects.filter(headline__startswith="Article"), [a8, self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) self.assertSequenceEqual( Article.objects.filter(headline__startswith="Article_"), [a8], ) a9 = Article.objects.create( headline="Article% with percent sign", pub_date=datetime(2005, 11, 21) ) self.assertSequenceEqual( Article.objects.filter(headline__startswith="Article"), [a9, a8, self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) self.assertSequenceEqual( Article.objects.filter(headline__startswith="Article%"), [a9], ) a10 = Article.objects.create( headline="Article with \\ backslash", pub_date=datetime(2005, 11, 22) ) self.assertSequenceEqual( Article.objects.filter(headline__contains="\\"), [a10], ) def test_exclude(self): pub_date = datetime(2005, 11, 20) a8 = Article.objects.create( headline="Article_ with underscore", pub_date=pub_date ) a9 = Article.objects.create( headline="Article% with percent sign", pub_date=pub_date ) a10 = Article.objects.create( headline="Article with \\ backslash", pub_date=pub_date ) # exclude() is the opposite of filter() when doing lookups: self.assertSequenceEqual( Article.objects.filter(headline__contains="Article").exclude( headline__contains="with" ), [self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) self.assertSequenceEqual( Article.objects.exclude(headline__startswith="Article_"), [a10, a9, self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) self.assertSequenceEqual( Article.objects.exclude(headline="Article 7"), [a10, a9, a8, self.a5, self.a6, self.a4, self.a2, self.a3, self.a1], ) def test_none(self): # none() returns a QuerySet that behaves like any other QuerySet object self.assertQuerysetEqual(Article.objects.none(), []) self.assertQuerysetEqual( Article.objects.none().filter(headline__startswith="Article"), [] ) self.assertQuerysetEqual( Article.objects.filter(headline__startswith="Article").none(), [] ) self.assertEqual(Article.objects.none().count(), 0) self.assertEqual( Article.objects.none().update(headline="This should not take effect"), 0 ) self.assertQuerysetEqual(Article.objects.none().iterator(), []) def test_in(self): self.assertSequenceEqual( Article.objects.exclude(id__in=[]), [self.a5, self.a6, self.a4, self.a2, self.a3, self.a7, self.a1], ) def test_in_empty_list(self): self.assertSequenceEqual(Article.objects.filter(id__in=[]), []) def test_in_different_database(self): with self.assertRaisesMessage( ValueError, "Subqueries aren't allowed across different databases. Force the " "inner query to be evaluated using `list(inner_query)`.", ): list(Article.objects.filter(id__in=Article.objects.using("other").all())) def test_in_keeps_value_ordering(self): query = ( Article.objects.filter(slug__in=["a%d" % i for i in range(1, 8)]) .values("pk") .query ) self.assertIn(" IN (a1, a2, a3, a4, a5, a6, a7) ", str(query)) def test_in_ignore_none(self): with self.assertNumQueries(1) as ctx: self.assertSequenceEqual( Article.objects.filter(id__in=[None, self.a1.id]), [self.a1], ) sql = ctx.captured_queries[0]["sql"] self.assertIn("IN (%s)" % self.a1.pk, sql) def test_in_ignore_solo_none(self): with self.assertNumQueries(0): self.assertSequenceEqual(Article.objects.filter(id__in=[None]), []) def test_in_ignore_none_with_unhashable_items(self): class UnhashableInt(int): __hash__ = None with self.assertNumQueries(1) as ctx: self.assertSequenceEqual( Article.objects.filter(id__in=[None, UnhashableInt(self.a1.id)]), [self.a1], ) sql = ctx.captured_queries[0]["sql"] self.assertIn("IN (%s)" % self.a1.pk, sql) def test_error_messages(self): # Programming errors are pointed out with nice error messages with self.assertRaisesMessage( FieldError, "Cannot resolve keyword 'pub_date_year' into field. Choices are: " "author, author_id, headline, id, pub_date, slug, tag", ): Article.objects.filter(pub_date_year="2005").count() def test_unsupported_lookups(self): with self.assertRaisesMessage( FieldError, "Unsupported lookup 'starts' for CharField or join on the field " "not permitted, perhaps you meant startswith or istartswith?", ): Article.objects.filter(headline__starts="Article") with self.assertRaisesMessage( FieldError, "Unsupported lookup 'is_null' for DateTimeField or join on the field " "not permitted, perhaps you meant isnull?", ): Article.objects.filter(pub_date__is_null=True) with self.assertRaisesMessage( FieldError, "Unsupported lookup 'gobbledygook' for DateTimeField or join on the field " "not permitted.", ): Article.objects.filter(pub_date__gobbledygook="blahblah") def test_relation_nested_lookup_error(self): # An invalid nested lookup on a related field raises a useful error. msg = "Related Field got invalid lookup: editor" with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(author__editor__name="James") msg = "Related Field got invalid lookup: foo" with self.assertRaisesMessage(FieldError, msg): Tag.objects.filter(articles__foo="bar") def test_regex(self): # Create some articles with a bit more interesting headlines for # testing field lookups. Article.objects.all().delete() now = datetime.now() Article.objects.bulk_create( [ Article(pub_date=now, headline="f"), Article(pub_date=now, headline="fo"), Article(pub_date=now, headline="foo"), Article(pub_date=now, headline="fooo"), Article(pub_date=now, headline="hey-Foo"), Article(pub_date=now, headline="bar"), Article(pub_date=now, headline="AbBa"), Article(pub_date=now, headline="baz"), Article(pub_date=now, headline="baxZ"), ] ) # zero-or-more self.assertQuerysetEqual( Article.objects.filter(headline__regex=r"fo*"), Article.objects.filter(headline__in=["f", "fo", "foo", "fooo"]), ) self.assertQuerysetEqual( Article.objects.filter(headline__iregex=r"fo*"), Article.objects.filter(headline__in=["f", "fo", "foo", "fooo", "hey-Foo"]), ) # one-or-more self.assertQuerysetEqual( Article.objects.filter(headline__regex=r"fo+"), Article.objects.filter(headline__in=["fo", "foo", "fooo"]), ) # wildcard self.assertQuerysetEqual( Article.objects.filter(headline__regex=r"fooo?"), Article.objects.filter(headline__in=["foo", "fooo"]), ) # leading anchor self.assertQuerysetEqual( Article.objects.filter(headline__regex=r"^b"), Article.objects.filter(headline__in=["bar", "baxZ", "baz"]), ) self.assertQuerysetEqual( Article.objects.filter(headline__iregex=r"^a"), Article.objects.filter(headline="AbBa"), ) # trailing anchor self.assertQuerysetEqual( Article.objects.filter(headline__regex=r"z$"), Article.objects.filter(headline="baz"), ) self.assertQuerysetEqual( Article.objects.filter(headline__iregex=r"z$"), Article.objects.filter(headline__in=["baxZ", "baz"]), ) # character sets self.assertQuerysetEqual( Article.objects.filter(headline__regex=r"ba[rz]"), Article.objects.filter(headline__in=["bar", "baz"]), ) self.assertQuerysetEqual( Article.objects.filter(headline__regex=r"ba.[RxZ]"), Article.objects.filter(headline="baxZ"), ) self.assertQuerysetEqual( Article.objects.filter(headline__iregex=r"ba[RxZ]"), Article.objects.filter(headline__in=["bar", "baxZ", "baz"]), ) # and more articles: Article.objects.bulk_create( [ Article(pub_date=now, headline="foobar"), Article(pub_date=now, headline="foobaz"), Article(pub_date=now, headline="ooF"), Article(pub_date=now, headline="foobarbaz"), Article(pub_date=now, headline="zoocarfaz"), Article(pub_date=now, headline="barfoobaz"), Article(pub_date=now, headline="bazbaRFOO"), ] ) # alternation self.assertQuerysetEqual( Article.objects.filter(headline__regex=r"oo(f|b)"), Article.objects.filter( headline__in=[ "barfoobaz", "foobar", "foobarbaz", "foobaz", ] ), ) self.assertQuerysetEqual( Article.objects.filter(headline__iregex=r"oo(f|b)"), Article.objects.filter( headline__in=[ "barfoobaz", "foobar", "foobarbaz", "foobaz", "ooF", ] ), ) self.assertQuerysetEqual( Article.objects.filter(headline__regex=r"^foo(f|b)"), Article.objects.filter(headline__in=["foobar", "foobarbaz", "foobaz"]), ) # greedy matching self.assertQuerysetEqual( Article.objects.filter(headline__regex=r"b.*az"), Article.objects.filter( headline__in=[ "barfoobaz", "baz", "bazbaRFOO", "foobarbaz", "foobaz", ] ), ) self.assertQuerysetEqual( Article.objects.filter(headline__iregex=r"b.*ar"), Article.objects.filter( headline__in=[ "bar", "barfoobaz", "bazbaRFOO", "foobar", "foobarbaz", ] ), ) @skipUnlessDBFeature("supports_regex_backreferencing") def test_regex_backreferencing(self): # grouping and backreferences now = datetime.now() Article.objects.bulk_create( [ Article(pub_date=now, headline="foobar"), Article(pub_date=now, headline="foobaz"), Article(pub_date=now, headline="ooF"), Article(pub_date=now, headline="foobarbaz"), Article(pub_date=now, headline="zoocarfaz"), Article(pub_date=now, headline="barfoobaz"), Article(pub_date=now, headline="bazbaRFOO"), ] ) self.assertQuerysetEqual( Article.objects.filter(headline__regex=r"b(.).*b\1").values_list( "headline", flat=True ), ["barfoobaz", "bazbaRFOO", "foobarbaz"], ) def test_regex_null(self): """ A regex lookup does not fail on null/None values """ Season.objects.create(year=2012, gt=None) self.assertQuerysetEqual(Season.objects.filter(gt__regex=r"^$"), []) def test_regex_non_string(self): """ A regex lookup does not fail on non-string fields """ s = Season.objects.create(year=2013, gt=444) self.assertQuerysetEqual(Season.objects.filter(gt__regex=r"^444$"), [s]) def test_regex_non_ascii(self): """ A regex lookup does not trip on non-ASCII characters. """ Player.objects.create(name="\u2660") Player.objects.get(name__regex="\u2660") def test_nonfield_lookups(self): """ A lookup query containing non-fields raises the proper exception. """ msg = ( "Unsupported lookup 'blahblah' for CharField or join on the field not " "permitted." ) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(headline__blahblah=99) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(headline__blahblah__exact=99) msg = ( "Cannot resolve keyword 'blahblah' into field. Choices are: " "author, author_id, headline, id, pub_date, slug, tag" ) with self.assertRaisesMessage(FieldError, msg): Article.objects.filter(blahblah=99) def test_lookup_collision(self): """ Genuine field names don't collide with built-in lookup types ('year', 'gt', 'range', 'in' etc.) (#11670). """ # 'gt' is used as a code number for the year, e.g. 111=>2009. season_2009 = Season.objects.create(year=2009, gt=111) season_2009.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2010 = Season.objects.create(year=2010, gt=222) season_2010.games.create(home="Houston Astros", away="Chicago Cubs") season_2010.games.create(home="Houston Astros", away="Milwaukee Brewers") season_2010.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2011 = Season.objects.create(year=2011, gt=333) season_2011.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2011.games.create(home="Houston Astros", away="Milwaukee Brewers") hunter_pence = Player.objects.create(name="Hunter Pence") hunter_pence.games.set(Game.objects.filter(season__year__in=[2009, 2010])) pudge = Player.objects.create(name="Ivan Rodriquez") pudge.games.set(Game.objects.filter(season__year=2009)) pedro_feliz = Player.objects.create(name="Pedro Feliz") pedro_feliz.games.set(Game.objects.filter(season__year__in=[2011])) johnson = Player.objects.create(name="Johnson") johnson.games.set(Game.objects.filter(season__year__in=[2011])) # Games in 2010 self.assertEqual(Game.objects.filter(season__year=2010).count(), 3) self.assertEqual(Game.objects.filter(season__year__exact=2010).count(), 3) self.assertEqual(Game.objects.filter(season__gt=222).count(), 3) self.assertEqual(Game.objects.filter(season__gt__exact=222).count(), 3) # Games in 2011 self.assertEqual(Game.objects.filter(season__year=2011).count(), 2) self.assertEqual(Game.objects.filter(season__year__exact=2011).count(), 2) self.assertEqual(Game.objects.filter(season__gt=333).count(), 2) self.assertEqual(Game.objects.filter(season__gt__exact=333).count(), 2) self.assertEqual(Game.objects.filter(season__year__gt=2010).count(), 2) self.assertEqual(Game.objects.filter(season__gt__gt=222).count(), 2) # Games played in 2010 and 2011 self.assertEqual(Game.objects.filter(season__year__in=[2010, 2011]).count(), 5) self.assertEqual(Game.objects.filter(season__year__gt=2009).count(), 5) self.assertEqual(Game.objects.filter(season__gt__in=[222, 333]).count(), 5) self.assertEqual(Game.objects.filter(season__gt__gt=111).count(), 5) # Players who played in 2009 self.assertEqual( Player.objects.filter(games__season__year=2009).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__year__exact=2009).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__gt=111).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__gt__exact=111).distinct().count(), 2 ) # Players who played in 2010 self.assertEqual( Player.objects.filter(games__season__year=2010).distinct().count(), 1 ) self.assertEqual( Player.objects.filter(games__season__year__exact=2010).distinct().count(), 1 ) self.assertEqual( Player.objects.filter(games__season__gt=222).distinct().count(), 1 ) self.assertEqual( Player.objects.filter(games__season__gt__exact=222).distinct().count(), 1 ) # Players who played in 2011 self.assertEqual( Player.objects.filter(games__season__year=2011).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__year__exact=2011).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__gt=333).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__year__gt=2010).distinct().count(), 2 ) self.assertEqual( Player.objects.filter(games__season__gt__gt=222).distinct().count(), 2 ) def test_chain_date_time_lookups(self): self.assertCountEqual( Article.objects.filter(pub_date__month__gt=7), [self.a5, self.a6], ) self.assertCountEqual( Article.objects.filter(pub_date__day__gte=27), [self.a2, self.a3, self.a4, self.a7], ) self.assertCountEqual( Article.objects.filter(pub_date__hour__lt=8), [self.a1, self.a2, self.a3, self.a4, self.a7], ) self.assertCountEqual( Article.objects.filter(pub_date__minute__lte=0), [self.a1, self.a2, self.a3, self.a4, self.a5, self.a6, self.a7], ) def test_exact_none_transform(self): """Transforms are used for __exact=None.""" Season.objects.create(year=1, nulled_text_field="not null") self.assertFalse(Season.objects.filter(nulled_text_field__isnull=True)) self.assertTrue(Season.objects.filter(nulled_text_field__nulled__isnull=True)) self.assertTrue(Season.objects.filter(nulled_text_field__nulled__exact=None)) self.assertTrue(Season.objects.filter(nulled_text_field__nulled=None)) def test_exact_sliced_queryset_limit_one(self): self.assertCountEqual( Article.objects.filter(author=Author.objects.all()[:1]), [self.a1, self.a2, self.a3, self.a4], ) def test_exact_sliced_queryset_limit_one_offset(self): self.assertCountEqual( Article.objects.filter(author=Author.objects.all()[1:2]), [self.a5, self.a6, self.a7], ) def test_exact_sliced_queryset_not_limited_to_one(self): msg = ( "The QuerySet value for an exact lookup must be limited to one " "result using slicing." ) with self.assertRaisesMessage(ValueError, msg): list(Article.objects.filter(author=Author.objects.all()[:2])) with self.assertRaisesMessage(ValueError, msg): list(Article.objects.filter(author=Author.objects.all()[1:])) @skipUnless(connection.vendor == "mysql", "MySQL-specific workaround.") def test_exact_booleanfield(self): # MySQL ignores indexes with boolean fields unless they're compared # directly to a boolean value. product = Product.objects.create(name="Paper", qty_target=5000) Stock.objects.create(product=product, short=False, qty_available=5100) stock_1 = Stock.objects.create(product=product, short=True, qty_available=180) qs = Stock.objects.filter(short=True) self.assertSequenceEqual(qs, [stock_1]) self.assertIn( "%s = True" % connection.ops.quote_name("short"), str(qs.query), ) @skipUnless(connection.vendor == "mysql", "MySQL-specific workaround.") def test_exact_booleanfield_annotation(self): # MySQL ignores indexes with boolean fields unless they're compared # directly to a boolean value. qs = Author.objects.annotate( case=Case( When(alias="a1", then=True), default=False, output_field=BooleanField(), ) ).filter(case=True) self.assertSequenceEqual(qs, [self.au1]) self.assertIn(" = True", str(qs.query)) qs = Author.objects.annotate( wrapped=ExpressionWrapper(Q(alias="a1"), output_field=BooleanField()), ).filter(wrapped=True) self.assertSequenceEqual(qs, [self.au1]) self.assertIn(" = True", str(qs.query)) # EXISTS(...) shouldn't be compared to a boolean value. qs = Author.objects.annotate( exists=Exists(Author.objects.filter(alias="a1", pk=OuterRef("pk"))), ).filter(exists=True) self.assertSequenceEqual(qs, [self.au1]) self.assertNotIn(" = True", str(qs.query)) def test_custom_field_none_rhs(self): """ __exact=value is transformed to __isnull=True if Field.get_prep_value() converts value to None. """ season = Season.objects.create(year=2012, nulled_text_field=None) self.assertTrue( Season.objects.filter(pk=season.pk, nulled_text_field__isnull=True) ) self.assertTrue(Season.objects.filter(pk=season.pk, nulled_text_field="")) def test_pattern_lookups_with_substr(self): a = Author.objects.create(name="John Smith", alias="Johx") b = Author.objects.create(name="Rhonda Simpson", alias="sonx") tests = ( ("startswith", [a]), ("istartswith", [a]), ("contains", [a, b]), ("icontains", [a, b]), ("endswith", [b]), ("iendswith", [b]), ) for lookup, result in tests: with self.subTest(lookup=lookup): authors = Author.objects.filter( **{"name__%s" % lookup: Substr("alias", 1, 3)} ) self.assertCountEqual(authors, result) def test_custom_lookup_none_rhs(self): """Lookup.can_use_none_as_rhs=True allows None as a lookup value.""" season = Season.objects.create(year=2012, nulled_text_field=None) query = Season.objects.get_queryset().query field = query.model._meta.get_field("nulled_text_field") self.assertIsInstance( query.build_lookup(["isnull_none_rhs"], field, None), IsNullWithNoneAsRHS ) self.assertTrue( Season.objects.filter(pk=season.pk, nulled_text_field__isnull_none_rhs=True) ) def test_exact_exists(self): qs = Article.objects.filter(pk=OuterRef("pk")) seasons = Season.objects.annotate(pk_exists=Exists(qs),).filter( pk_exists=Exists(qs), ) self.assertCountEqual(seasons, Season.objects.all()) def test_nested_outerref_lhs(self): tag = Tag.objects.create(name=self.au1.alias) tag.articles.add(self.a1) qs = Tag.objects.annotate( has_author_alias_match=Exists( Article.objects.annotate( author_exists=Exists( Author.objects.filter(alias=OuterRef(OuterRef("name"))) ), ).filter(author_exists=True) ), ) self.assertEqual(qs.get(has_author_alias_match=True), tag) def test_exact_query_rhs_with_selected_columns(self): newest_author = Author.objects.create(name="Author 2") authors_max_ids = ( Author.objects.filter( name="Author 2", ) .values( "name", ) .annotate( max_id=Max("id"), ) .values("max_id") ) authors = Author.objects.filter(id=authors_max_ids[:1]) self.assertEqual(authors.get(), newest_author) def test_isnull_non_boolean_value(self): msg = "The QuerySet value for an isnull lookup must be True or False." tests = [ Author.objects.filter(alias__isnull=1), Article.objects.filter(author__isnull=1), Season.objects.filter(games__isnull=1), Freebie.objects.filter(stock__isnull=1), ] for qs in tests: with self.subTest(qs=qs): with self.assertRaisesMessage(ValueError, msg): qs.exists() def test_lookup_rhs(self): product = Product.objects.create(name="GME", qty_target=5000) stock_1 = Stock.objects.create(product=product, short=True, qty_available=180) stock_2 = Stock.objects.create(product=product, short=False, qty_available=5100) Stock.objects.create(product=product, short=False, qty_available=4000) self.assertCountEqual( Stock.objects.filter(short=Q(qty_available__lt=F("product__qty_target"))), [stock_1, stock_2], ) self.assertCountEqual( Stock.objects.filter( short=ExpressionWrapper( Q(qty_available__lt=F("product__qty_target")), output_field=BooleanField(), ) ), [stock_1, stock_2], ) class LookupQueryingTests(TestCase): @classmethod def setUpTestData(cls): cls.s1 = Season.objects.create(year=1942, gt=1942) cls.s2 = Season.objects.create(year=1842, gt=1942, nulled_text_field="text") cls.s3 = Season.objects.create(year=2042, gt=1942) def test_annotate(self): qs = Season.objects.annotate(equal=Exact(F("year"), 1942)) self.assertCountEqual( qs.values_list("year", "equal"), ((1942, True), (1842, False), (2042, False)), ) def test_alias(self): qs = Season.objects.alias(greater=GreaterThan(F("year"), 1910)) self.assertCountEqual(qs.filter(greater=True), [self.s1, self.s3]) def test_annotate_value_greater_than_value(self): qs = Season.objects.annotate(greater=GreaterThan(Value(40), Value(30))) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, True), (1842, True), (2042, True)), ) def test_annotate_field_greater_than_field(self): qs = Season.objects.annotate(greater=GreaterThan(F("year"), F("gt"))) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, False), (1842, False), (2042, True)), ) def test_annotate_field_greater_than_value(self): qs = Season.objects.annotate(greater=GreaterThan(F("year"), Value(1930))) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, True), (1842, False), (2042, True)), ) def test_annotate_field_greater_than_literal(self): qs = Season.objects.annotate(greater=GreaterThan(F("year"), 1930)) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, True), (1842, False), (2042, True)), ) def test_annotate_literal_greater_than_field(self): qs = Season.objects.annotate(greater=GreaterThan(1930, F("year"))) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, False), (1842, True), (2042, False)), ) def test_annotate_less_than_float(self): qs = Season.objects.annotate(lesser=LessThan(F("year"), 1942.1)) self.assertCountEqual( qs.values_list("year", "lesser"), ((1942, True), (1842, True), (2042, False)), ) def test_annotate_greater_than_or_equal(self): qs = Season.objects.annotate(greater=GreaterThanOrEqual(F("year"), 1942)) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, True), (1842, False), (2042, True)), ) def test_annotate_greater_than_or_equal_float(self): qs = Season.objects.annotate(greater=GreaterThanOrEqual(F("year"), 1942.1)) self.assertCountEqual( qs.values_list("year", "greater"), ((1942, False), (1842, False), (2042, True)), ) def test_combined_lookups(self): expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942) qs = Season.objects.annotate(gte=expression) self.assertCountEqual( qs.values_list("year", "gte"), ((1942, True), (1842, False), (2042, True)), ) def test_lookup_in_filter(self): qs = Season.objects.filter(GreaterThan(F("year"), 1910)) self.assertCountEqual(qs, [self.s1, self.s3]) def test_isnull_lookup_in_filter(self): self.assertSequenceEqual( Season.objects.filter(IsNull(F("nulled_text_field"), False)), [self.s2], ) self.assertCountEqual( Season.objects.filter(IsNull(F("nulled_text_field"), True)), [self.s1, self.s3], ) def test_filter_lookup_lhs(self): qs = Season.objects.annotate(before_20=LessThan(F("year"), 2000)).filter( before_20=LessThan(F("year"), 1900), ) self.assertCountEqual(qs, [self.s2, self.s3]) def test_filter_wrapped_lookup_lhs(self): qs = ( Season.objects.annotate( before_20=ExpressionWrapper( Q(year__lt=2000), output_field=BooleanField(), ) ) .filter(before_20=LessThan(F("year"), 1900)) .values_list("year", flat=True) ) self.assertCountEqual(qs, [1842, 2042]) def test_filter_exists_lhs(self): qs = Season.objects.annotate( before_20=Exists( Season.objects.filter(pk=OuterRef("pk"), year__lt=2000), ) ).filter(before_20=LessThan(F("year"), 1900)) self.assertCountEqual(qs, [self.s2, self.s3]) def test_filter_subquery_lhs(self): qs = Season.objects.annotate( before_20=Subquery( Season.objects.filter(pk=OuterRef("pk")).values( lesser=LessThan(F("year"), 2000), ), ) ).filter(before_20=LessThan(F("year"), 1900)) self.assertCountEqual(qs, [self.s2, self.s3]) def test_combined_lookups_in_filter(self): expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942) qs = Season.objects.filter(expression) self.assertCountEqual(qs, [self.s1, self.s3]) def test_combined_annotated_lookups_in_filter(self): expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942) qs = Season.objects.annotate(gte=expression).filter(gte=True) self.assertCountEqual(qs, [self.s1, self.s3]) def test_combined_annotated_lookups_in_filter_false(self): expression = Exact(F("year"), 1942) | GreaterThan(F("year"), 1942) qs = Season.objects.annotate(gte=expression).filter(gte=False) self.assertSequenceEqual(qs, [self.s2]) def test_lookup_in_order_by(self): qs = Season.objects.order_by(LessThan(F("year"), 1910), F("year")) self.assertSequenceEqual(qs, [self.s1, self.s3, self.s2]) @skipUnlessDBFeature("supports_boolean_expr_in_select_clause") def test_aggregate_combined_lookup(self): expression = Cast(GreaterThan(F("year"), 1900), models.IntegerField()) qs = Season.objects.aggregate(modern=models.Sum(expression)) self.assertEqual(qs["modern"], 2) def test_conditional_expression(self): qs = Season.objects.annotate( century=Case( When( GreaterThan(F("year"), 1900) & LessThanOrEqual(F("year"), 2000), then=Value("20th"), ), default=Value("other"), ) ).values("year", "century") self.assertCountEqual( qs, [ {"year": 1942, "century": "20th"}, {"year": 1842, "century": "other"}, {"year": 2042, "century": "other"}, ], )
3a06c46ddf1b0becc9fcaafb8356a07e335237b650d91a579f2a561c42b32e58
import os import signal import subprocess import sys from pathlib import Path from unittest import mock, skipUnless from django.db import connection from django.db.backends.mysql.client import DatabaseClient from django.test import SimpleTestCase class MySqlDbshellCommandTestCase(SimpleTestCase): def settings_to_cmd_args_env(self, settings_dict, parameters=None): if parameters is None: parameters = [] return DatabaseClient.settings_to_cmd_args_env(settings_dict, parameters) def test_fails_with_keyerror_on_incomplete_config(self): with self.assertRaises(KeyError): self.settings_to_cmd_args_env({}) def test_basic_params_specified_in_settings(self): expected_args = [ "mysql", "--user=someuser", "--host=somehost", "--port=444", "somedbname", ] expected_env = {"MYSQL_PWD": "somepassword"} self.assertEqual( self.settings_to_cmd_args_env( { "NAME": "somedbname", "USER": "someuser", "PASSWORD": "somepassword", "HOST": "somehost", "PORT": 444, "OPTIONS": {}, } ), (expected_args, expected_env), ) def test_options_override_settings_proper_values(self): settings_port = 444 options_port = 555 self.assertNotEqual(settings_port, options_port, "test pre-req") expected_args = [ "mysql", "--user=optionuser", "--host=optionhost", "--port=%s" % options_port, "optiondbname", ] expected_env = {"MYSQL_PWD": "optionpassword"} for keys in [("database", "password"), ("db", "passwd")]: with self.subTest(keys=keys): database, password = keys self.assertEqual( self.settings_to_cmd_args_env( { "NAME": "settingdbname", "USER": "settinguser", "PASSWORD": "settingpassword", "HOST": "settinghost", "PORT": settings_port, "OPTIONS": { database: "optiondbname", "user": "optionuser", password: "optionpassword", "host": "optionhost", "port": options_port, }, } ), (expected_args, expected_env), ) def test_options_non_deprecated_keys_preferred(self): expected_args = [ "mysql", "--user=someuser", "--host=somehost", "--port=444", "optiondbname", ] expected_env = {"MYSQL_PWD": "optionpassword"} self.assertEqual( self.settings_to_cmd_args_env( { "NAME": "settingdbname", "USER": "someuser", "PASSWORD": "settingpassword", "HOST": "somehost", "PORT": 444, "OPTIONS": { "database": "optiondbname", "db": "deprecatedoptiondbname", "password": "optionpassword", "passwd": "deprecatedoptionpassword", }, } ), (expected_args, expected_env), ) def test_options_charset(self): expected_args = [ "mysql", "--user=someuser", "--host=somehost", "--port=444", "--default-character-set=utf8", "somedbname", ] expected_env = {"MYSQL_PWD": "somepassword"} self.assertEqual( self.settings_to_cmd_args_env( { "NAME": "somedbname", "USER": "someuser", "PASSWORD": "somepassword", "HOST": "somehost", "PORT": 444, "OPTIONS": {"charset": "utf8"}, } ), (expected_args, expected_env), ) def test_can_connect_using_sockets(self): expected_args = [ "mysql", "--user=someuser", "--socket=/path/to/mysql.socket.file", "somedbname", ] expected_env = {"MYSQL_PWD": "somepassword"} self.assertEqual( self.settings_to_cmd_args_env( { "NAME": "somedbname", "USER": "someuser", "PASSWORD": "somepassword", "HOST": "/path/to/mysql.socket.file", "PORT": None, "OPTIONS": {}, } ), (expected_args, expected_env), ) def test_ssl_certificate_is_added(self): expected_args = [ "mysql", "--user=someuser", "--host=somehost", "--port=444", "--ssl-ca=sslca", "--ssl-cert=sslcert", "--ssl-key=sslkey", "somedbname", ] expected_env = {"MYSQL_PWD": "somepassword"} self.assertEqual( self.settings_to_cmd_args_env( { "NAME": "somedbname", "USER": "someuser", "PASSWORD": "somepassword", "HOST": "somehost", "PORT": 444, "OPTIONS": { "ssl": { "ca": "sslca", "cert": "sslcert", "key": "sslkey", }, }, } ), (expected_args, expected_env), ) def test_parameters(self): self.assertEqual( self.settings_to_cmd_args_env( { "NAME": "somedbname", "USER": None, "PASSWORD": None, "HOST": None, "PORT": None, "OPTIONS": {}, }, ["--help"], ), (["mysql", "somedbname", "--help"], None), ) def test_crash_password_does_not_leak(self): # The password doesn't leak in an exception that results from a client # crash. args, env = DatabaseClient.settings_to_cmd_args_env( { "NAME": "somedbname", "USER": "someuser", "PASSWORD": "somepassword", "HOST": "somehost", "PORT": 444, "OPTIONS": {}, }, [], ) if env: env = {**os.environ, **env} fake_client = Path(__file__).with_name("fake_client.py") args[0:1] = [sys.executable, str(fake_client)] with self.assertRaises(subprocess.CalledProcessError) as ctx: subprocess.run(args, check=True, env=env) self.assertNotIn("somepassword", str(ctx.exception)) @skipUnless(connection.vendor == "mysql", "Requires a MySQL connection") def test_sigint_handler(self): """SIGINT is ignored in Python and passed to mysql to abort queries.""" def _mock_subprocess_run(*args, **kwargs): handler = signal.getsignal(signal.SIGINT) self.assertEqual(handler, signal.SIG_IGN) sigint_handler = signal.getsignal(signal.SIGINT) # The default handler isn't SIG_IGN. self.assertNotEqual(sigint_handler, signal.SIG_IGN) with mock.patch("subprocess.run", new=_mock_subprocess_run): connection.client.runshell([]) # dbshell restores the original handler. self.assertEqual(sigint_handler, signal.getsignal(signal.SIGINT))
a89cf522f056049ad20b8c29b7c67b87449870c4e3d3bb7d3d467e4deb72faa7
import datetime from collections import Counter from unittest import mock from django.core.exceptions import ValidationError from django.forms import ( BaseForm, CharField, DateField, FileField, Form, IntegerField, SplitDateTimeField, formsets, ) from django.forms.formsets import ( INITIAL_FORM_COUNT, MAX_NUM_FORM_COUNT, MIN_NUM_FORM_COUNT, TOTAL_FORM_COUNT, BaseFormSet, ManagementForm, all_valid, formset_factory, ) from django.forms.renderers import TemplatesSetting, get_default_renderer from django.forms.utils import ErrorList from django.forms.widgets import HiddenInput from django.test import SimpleTestCase from django.test.utils import isolate_lru_cache from django.utils.deprecation import RemovedInDjango50Warning from . import jinja2_tests class Choice(Form): choice = CharField() votes = IntegerField() ChoiceFormSet = formset_factory(Choice) class ChoiceFormsetWithNonFormError(ChoiceFormSet): def clean(self): super().clean() raise ValidationError("non-form error") class FavoriteDrinkForm(Form): name = CharField() class BaseFavoriteDrinksFormSet(BaseFormSet): def clean(self): seen_drinks = [] for drink in self.cleaned_data: if drink["name"] in seen_drinks: raise ValidationError("You may only specify a drink once.") seen_drinks.append(drink["name"]) # A FormSet that takes a list of favorite drinks and raises an error if # there are any duplicates. FavoriteDrinksFormSet = formset_factory( FavoriteDrinkForm, formset=BaseFavoriteDrinksFormSet, extra=3 ) class CustomKwargForm(Form): def __init__(self, *args, custom_kwarg, **kwargs): self.custom_kwarg = custom_kwarg super().__init__(*args, **kwargs) class FormsFormsetTestCase(SimpleTestCase): def make_choiceformset( self, formset_data=None, formset_class=ChoiceFormSet, total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs, ): """ Make a ChoiceFormset from the given formset_data. The data should be given as a list of (choice, votes) tuples. """ kwargs.setdefault("prefix", "choices") kwargs.setdefault("auto_id", False) if formset_data is None: return formset_class(**kwargs) if total_forms is None: total_forms = len(formset_data) def prefixed(*args): args = (kwargs["prefix"],) + args return "-".join(args) data = { prefixed("TOTAL_FORMS"): str(total_forms), prefixed("INITIAL_FORMS"): str(initial_forms), prefixed("MAX_NUM_FORMS"): str(max_num_forms), prefixed("MIN_NUM_FORMS"): str(min_num_forms), } for i, (choice, votes) in enumerate(formset_data): data[prefixed(str(i), "choice")] = choice data[prefixed(str(i), "votes")] = votes return formset_class(data, **kwargs) def test_basic_formset(self): """ A FormSet constructor takes the same arguments as Form. Create a FormSet for adding data. By default, it displays 1 blank form. """ formset = self.make_choiceformset() self.assertHTMLEqual( str(formset), """<input type="hidden" name="choices-TOTAL_FORMS" value="1"> <input type="hidden" name="choices-INITIAL_FORMS" value="0"> <input type="hidden" name="choices-MIN_NUM_FORMS" value="0"> <input type="hidden" name="choices-MAX_NUM_FORMS" value="1000"> <div>Choice:<input type="text" name="choices-0-choice"></div> <div>Votes:<input type="number" name="choices-0-votes"></div>""", ) # FormSet are treated similarly to Forms. FormSet has an is_valid() # method, and a cleaned_data or errors attribute depending on whether # all the forms passed validation. However, unlike a Form, cleaned_data # and errors will be a list of dicts rather than a single dict. formset = self.make_choiceformset([("Calexico", "100")]) self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [{"votes": 100, "choice": "Calexico"}], ) # If a FormSet wasn't passed any data, is_valid() and has_changed() # return False. formset = self.make_choiceformset() self.assertFalse(formset.is_valid()) self.assertFalse(formset.has_changed()) def test_form_kwargs_formset(self): """ Custom kwargs set on the formset instance are passed to the underlying forms. """ FormSet = formset_factory(CustomKwargForm, extra=2) formset = FormSet(form_kwargs={"custom_kwarg": 1}) for form in formset: self.assertTrue(hasattr(form, "custom_kwarg")) self.assertEqual(form.custom_kwarg, 1) def test_form_kwargs_formset_dynamic(self): """Form kwargs can be passed dynamically in a formset.""" class DynamicBaseFormSet(BaseFormSet): def get_form_kwargs(self, index): return {"custom_kwarg": index} DynamicFormSet = formset_factory( CustomKwargForm, formset=DynamicBaseFormSet, extra=2 ) formset = DynamicFormSet(form_kwargs={"custom_kwarg": "ignored"}) for i, form in enumerate(formset): self.assertTrue(hasattr(form, "custom_kwarg")) self.assertEqual(form.custom_kwarg, i) def test_form_kwargs_empty_form(self): FormSet = formset_factory(CustomKwargForm) formset = FormSet(form_kwargs={"custom_kwarg": 1}) self.assertTrue(hasattr(formset.empty_form, "custom_kwarg")) self.assertEqual(formset.empty_form.custom_kwarg, 1) def test_formset_validation(self): # FormSet instances can also have an error attribute if validation failed for # any of the forms. formset = self.make_choiceformset([("Calexico", "")]) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{"votes": ["This field is required."]}]) def test_formset_validation_count(self): """ A formset's ManagementForm is validated once per FormSet.is_valid() call and each form of the formset is cleaned once. """ def make_method_counter(func): """Add a counter to func for the number of times it's called.""" counter = Counter() counter.call_count = 0 def mocked_func(*args, **kwargs): counter.call_count += 1 return func(*args, **kwargs) return mocked_func, counter mocked_is_valid, is_valid_counter = make_method_counter( formsets.ManagementForm.is_valid ) mocked_full_clean, full_clean_counter = make_method_counter(BaseForm.full_clean) formset = self.make_choiceformset( [("Calexico", "100"), ("Any1", "42"), ("Any2", "101")] ) with mock.patch( "django.forms.formsets.ManagementForm.is_valid", mocked_is_valid ), mock.patch("django.forms.forms.BaseForm.full_clean", mocked_full_clean): self.assertTrue(formset.is_valid()) self.assertEqual(is_valid_counter.call_count, 1) self.assertEqual(full_clean_counter.call_count, 4) def test_formset_has_changed(self): """ FormSet.has_changed() is True if any data is passed to its forms, even if the formset didn't validate. """ blank_formset = self.make_choiceformset([("", "")]) self.assertFalse(blank_formset.has_changed()) # invalid formset invalid_formset = self.make_choiceformset([("Calexico", "")]) self.assertFalse(invalid_formset.is_valid()) self.assertTrue(invalid_formset.has_changed()) # valid formset valid_formset = self.make_choiceformset([("Calexico", "100")]) self.assertTrue(valid_formset.is_valid()) self.assertTrue(valid_formset.has_changed()) def test_formset_initial_data(self): """ A FormSet can be prefilled with existing data by providing a list of dicts to the `initial` argument. By default, an extra blank form is included. """ formset = self.make_choiceformset( initial=[{"choice": "Calexico", "votes": 100}] ) self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li> <li>Votes: <input type="number" name="choices-0-votes" value="100"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li>""", ) def test_blank_form_unfilled(self): """A form that's displayed as blank may be submitted as blank.""" formset = self.make_choiceformset( [("Calexico", "100"), ("", "")], initial_forms=1 ) self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [{"votes": 100, "choice": "Calexico"}, {}], ) def test_second_form_partially_filled(self): """ If at least one field is filled out on a blank form, it will be validated. """ formset = self.make_choiceformset( [("Calexico", "100"), ("The Decemberists", "")], initial_forms=1 ) self.assertFalse(formset.is_valid()) self.assertEqual(formset.errors, [{}, {"votes": ["This field is required."]}]) def test_delete_prefilled_data(self): """ Deleting prefilled data is an error. Removing data from form fields isn't the proper way to delete it. """ formset = self.make_choiceformset([("", ""), ("", "")], initial_forms=1) self.assertFalse(formset.is_valid()) self.assertEqual( formset.errors, [ { "votes": ["This field is required."], "choice": ["This field is required."], }, {}, ], ) def test_displaying_more_than_one_blank_form(self): """ More than 1 empty form can be displayed using formset_factory's `extra` argument. """ ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li>""", ) # Since every form was displayed as blank, they are also accepted as # blank. This may seem a little strange, but min_num is used to require # a minimum number of forms to be completed. data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "", "choices-0-votes": "", "choices-1-choice": "", "choices-1-votes": "", "choices-2-choice": "", "choices-2-votes": "", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual([form.cleaned_data for form in formset.forms], [{}, {}, {}]) def test_min_num_displaying_more_than_one_blank_form(self): """ More than 1 empty form can also be displayed using formset_factory's min_num argument. It will (essentially) increment the extra argument. """ ChoiceFormSet = formset_factory(Choice, extra=1, min_num=1) formset = ChoiceFormSet(auto_id=False, prefix="choices") # Min_num forms are required; extra forms can be empty. self.assertFalse(formset.forms[0].empty_permitted) self.assertTrue(formset.forms[1].empty_permitted) self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li>""", ) def test_min_num_displaying_more_than_one_blank_form_with_zero_extra(self): """More than 1 empty form can be displayed using min_num.""" ChoiceFormSet = formset_factory(Choice, extra=0, min_num=3) formset = ChoiceFormSet(auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice"></li> <li>Votes: <input type="number" name="choices-0-votes"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li>""", ) def test_single_form_completed(self): """Just one form may be completed.""" data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-1-choice": "", "choices-1-votes": "", "choices-2-choice": "", "choices-2-votes": "", } ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [{"votes": 100, "choice": "Calexico"}, {}, {}], ) def test_formset_validate_max_flag(self): """ If validate_max is set and max_num is less than TOTAL_FORMS in the data, a ValidationError is raised. MAX_NUM_FORMS in the data is irrelevant here (it's output as a hint for the client but its value in the returned data is not checked). """ data = { "choices-TOTAL_FORMS": "2", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "2", # max number of forms - should be ignored "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ["Please submit at most 1 form."]) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform"><li>Please submit at most 1 form.</li></ul>', ) def test_formset_validate_max_flag_custom_error(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "2", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet( data, auto_id=False, prefix="choices", error_messages={ "too_many_forms": "Number of submitted forms should be at most %(num)d." }, ) self.assertFalse(formset.is_valid()) self.assertEqual( formset.non_form_errors(), ["Number of submitted forms should be at most 1."], ) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform">' "<li>Number of submitted forms should be at most 1.</li></ul>", ) def test_formset_validate_min_flag(self): """ If validate_min is set and min_num is more than TOTAL_FORMS in the data, a ValidationError is raised. MIN_NUM_FORMS in the data is irrelevant here (it's output as a hint for the client but its value in the returned data is not checked). """ data = { "choices-TOTAL_FORMS": "2", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms - should be ignored "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, min_num=3, validate_min=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ["Please submit at least 3 forms."]) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform"><li>' "Please submit at least 3 forms.</li></ul>", ) def test_formset_validate_min_flag_custom_formatted_error(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "0", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, min_num=3, validate_min=True) formset = ChoiceFormSet( data, auto_id=False, prefix="choices", error_messages={ "too_few_forms": "Number of submitted forms should be at least %(num)d." }, ) self.assertFalse(formset.is_valid()) self.assertEqual( formset.non_form_errors(), ["Number of submitted forms should be at least 3."], ) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform">' "<li>Number of submitted forms should be at least 3.</li></ul>", ) def test_formset_validate_min_unchanged_forms(self): """ min_num validation doesn't consider unchanged forms with initial data as "empty". """ initial = [ {"choice": "Zero", "votes": 0}, {"choice": "One", "votes": 0}, ] data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "2", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "2", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", # changed from initial } ChoiceFormSet = formset_factory(Choice, min_num=2, validate_min=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices", initial=initial) self.assertFalse(formset.forms[0].has_changed()) self.assertTrue(formset.forms[1].has_changed()) self.assertTrue(formset.is_valid()) def test_formset_validate_min_excludes_empty_forms(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", } ChoiceFormSet = formset_factory( Choice, extra=2, min_num=1, validate_min=True, can_delete=True ) formset = ChoiceFormSet(data, prefix="choices") self.assertFalse(formset.has_changed()) self.assertFalse(formset.is_valid()) self.assertEqual(formset.non_form_errors(), ["Please submit at least 1 form."]) def test_second_form_partially_filled_2(self): """A partially completed form is invalid.""" data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-1-choice": "The Decemberists", "choices-1-votes": "", # missing value "choices-2-choice": "", "choices-2-votes": "", } ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertFalse(formset.is_valid()) self.assertEqual( formset.errors, [{}, {"votes": ["This field is required."]}, {}] ) def test_more_initial_data(self): """ The extra argument works when the formset is pre-filled with initial data. """ initial = [{"choice": "Calexico", "votes": 100}] ChoiceFormSet = formset_factory(Choice, extra=3) formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li> <li>Votes: <input type="number" name="choices-0-votes" value="100"></li> <li>Choice: <input type="text" name="choices-1-choice"></li> <li>Votes: <input type="number" name="choices-1-votes"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li> <li>Choice: <input type="text" name="choices-3-choice"></li> <li>Votes: <input type="number" name="choices-3-votes"></li>""", ) # Retrieving an empty form works. Tt shows up in the form list. self.assertTrue(formset.empty_form.empty_permitted) self.assertHTMLEqual( formset.empty_form.as_ul(), """<li>Choice: <input type="text" name="choices-__prefix__-choice"></li> <li>Votes: <input type="number" name="choices-__prefix__-votes"></li>""", ) def test_formset_with_deletion(self): """ formset_factory's can_delete argument adds a boolean "delete" field to each form. When that boolean field is True, the form will be in formset.deleted_forms. """ ChoiceFormSet = formset_factory(Choice, can_delete=True) initial = [ {"choice": "Calexico", "votes": 100}, {"choice": "Fergie", "votes": 900}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li> <li>Votes: <input type="number" name="choices-0-votes" value="100"></li> <li>Delete: <input type="checkbox" name="choices-0-DELETE"></li> <li>Choice: <input type="text" name="choices-1-choice" value="Fergie"></li> <li>Votes: <input type="number" name="choices-1-votes" value="900"></li> <li>Delete: <input type="checkbox" name="choices-1-DELETE"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li> <li>Delete: <input type="checkbox" name="choices-2-DELETE"></li>""", ) # To delete something, set that form's special delete field to 'on'. # Let's go ahead and delete Fergie. data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "2", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-DELETE": "", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-DELETE": "on", "choices-2-choice": "", "choices-2-votes": "", "choices-2-DELETE": "", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.forms], [ {"votes": 100, "DELETE": False, "choice": "Calexico"}, {"votes": 900, "DELETE": True, "choice": "Fergie"}, {}, ], ) self.assertEqual( [form.cleaned_data for form in formset.deleted_forms], [{"votes": 900, "DELETE": True, "choice": "Fergie"}], ) def test_formset_with_deletion_remove_deletion_flag(self): """ If a form is filled with something and can_delete is also checked, that form's errors shouldn't make the entire formset invalid since it's going to be deleted. """ class CheckForm(Form): field = IntegerField(min_value=100) data = { "check-TOTAL_FORMS": "3", # the number of forms rendered "check-INITIAL_FORMS": "2", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "check-MAX_NUM_FORMS": "0", # max number of forms "check-0-field": "200", "check-0-DELETE": "", "check-1-field": "50", "check-1-DELETE": "on", "check-2-field": "", "check-2-DELETE": "", } CheckFormSet = formset_factory(CheckForm, can_delete=True) formset = CheckFormSet(data, prefix="check") self.assertTrue(formset.is_valid()) # If the deletion flag is removed, validation is enabled. data["check-1-DELETE"] = "" formset = CheckFormSet(data, prefix="check") self.assertFalse(formset.is_valid()) def test_formset_with_deletion_invalid_deleted_form(self): """ deleted_forms works on a valid formset even if a deleted form would have been invalid. """ FavoriteDrinkFormset = formset_factory(form=FavoriteDrinkForm, can_delete=True) formset = FavoriteDrinkFormset( { "form-0-name": "", "form-0-DELETE": "on", # no name! "form-TOTAL_FORMS": 1, "form-INITIAL_FORMS": 1, "form-MIN_NUM_FORMS": 0, "form-MAX_NUM_FORMS": 1, } ) self.assertTrue(formset.is_valid()) self.assertEqual(formset._errors, []) self.assertEqual(len(formset.deleted_forms), 1) def test_formset_with_deletion_custom_widget(self): class DeletionAttributeFormSet(BaseFormSet): deletion_widget = HiddenInput class DeletionMethodFormSet(BaseFormSet): def get_deletion_widget(self): return HiddenInput(attrs={"class": "deletion"}) tests = [ (DeletionAttributeFormSet, '<input type="hidden" name="form-0-DELETE">'), ( DeletionMethodFormSet, '<input class="deletion" type="hidden" name="form-0-DELETE">', ), ] for formset_class, delete_html in tests: with self.subTest(formset_class=formset_class.__name__): ArticleFormSet = formset_factory( ArticleForm, formset=formset_class, can_delete=True, ) formset = ArticleFormSet(auto_id=False) self.assertHTMLEqual( "\n".join([form.as_ul() for form in formset.forms]), ( f'<li>Title: <input type="text" name="form-0-title"></li>' f'<li>Pub date: <input type="text" name="form-0-pub_date">' f"{delete_html}</li>" ), ) def test_formsets_with_ordering(self): """ formset_factory's can_order argument adds an integer field to each form. When form validation succeeds, [form.cleaned_data for form in formset.forms] will have the data in the correct order specified by the ordering fields. If a number is duplicated in the set of ordering fields, for instance form 0 and form 3 are both marked as 1, then the form index used as a secondary ordering criteria. In order to put something at the front of the list, you'd need to set its order to 0. """ ChoiceFormSet = formset_factory(Choice, can_order=True) initial = [ {"choice": "Calexico", "votes": 100}, {"choice": "Fergie", "votes": 900}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li> <li>Votes: <input type="number" name="choices-0-votes" value="100"></li> <li>Order: <input type="number" name="choices-0-ORDER" value="1"></li> <li>Choice: <input type="text" name="choices-1-choice" value="Fergie"></li> <li>Votes: <input type="number" name="choices-1-votes" value="900"></li> <li>Order: <input type="number" name="choices-1-ORDER" value="2"></li> <li>Choice: <input type="text" name="choices-2-choice"></li> <li>Votes: <input type="number" name="choices-2-votes"></li> <li>Order: <input type="number" name="choices-2-ORDER"></li>""", ) data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "2", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-ORDER": "1", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-ORDER": "2", "choices-2-choice": "The Decemberists", "choices-2-votes": "500", "choices-2-ORDER": "0", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ {"votes": 500, "ORDER": 0, "choice": "The Decemberists"}, {"votes": 100, "ORDER": 1, "choice": "Calexico"}, {"votes": 900, "ORDER": 2, "choice": "Fergie"}, ], ) def test_formsets_with_ordering_custom_widget(self): class OrderingAttributeFormSet(BaseFormSet): ordering_widget = HiddenInput class OrderingMethodFormSet(BaseFormSet): def get_ordering_widget(self): return HiddenInput(attrs={"class": "ordering"}) tests = ( (OrderingAttributeFormSet, '<input type="hidden" name="form-0-ORDER">'), ( OrderingMethodFormSet, '<input class="ordering" type="hidden" name="form-0-ORDER">', ), ) for formset_class, order_html in tests: with self.subTest(formset_class=formset_class.__name__): ArticleFormSet = formset_factory( ArticleForm, formset=formset_class, can_order=True ) formset = ArticleFormSet(auto_id=False) self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), ( '<li>Title: <input type="text" name="form-0-title"></li>' '<li>Pub date: <input type="text" name="form-0-pub_date">' "%s</li>" % order_html ), ) def test_empty_ordered_fields(self): """ Ordering fields are allowed to be left blank. If they are left blank, they'll be sorted below everything else. """ data = { "choices-TOTAL_FORMS": "4", # the number of forms rendered "choices-INITIAL_FORMS": "3", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-ORDER": "1", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-ORDER": "2", "choices-2-choice": "The Decemberists", "choices-2-votes": "500", "choices-2-ORDER": "", "choices-3-choice": "Basia Bulat", "choices-3-votes": "50", "choices-3-ORDER": "", } ChoiceFormSet = formset_factory(Choice, can_order=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ {"votes": 100, "ORDER": 1, "choice": "Calexico"}, {"votes": 900, "ORDER": 2, "choice": "Fergie"}, {"votes": 500, "ORDER": None, "choice": "The Decemberists"}, {"votes": 50, "ORDER": None, "choice": "Basia Bulat"}, ], ) def test_ordering_blank_fieldsets(self): """Ordering works with blank fieldsets.""" data = { "choices-TOTAL_FORMS": "3", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms } ChoiceFormSet = formset_factory(Choice, can_order=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual(formset.ordered_forms, []) def test_formset_with_ordering_and_deletion(self): """FormSets with ordering + deletion.""" ChoiceFormSet = formset_factory(Choice, can_order=True, can_delete=True) initial = [ {"choice": "Calexico", "votes": 100}, {"choice": "Fergie", "votes": 900}, {"choice": "The Decemberists", "votes": 500}, ] formset = ChoiceFormSet(initial=initial, auto_id=False, prefix="choices") self.assertHTMLEqual( "\n".join(form.as_ul() for form in formset.forms), """<li>Choice: <input type="text" name="choices-0-choice" value="Calexico"></li> <li>Votes: <input type="number" name="choices-0-votes" value="100"></li> <li>Order: <input type="number" name="choices-0-ORDER" value="1"></li> <li>Delete: <input type="checkbox" name="choices-0-DELETE"></li> <li>Choice: <input type="text" name="choices-1-choice" value="Fergie"></li> <li>Votes: <input type="number" name="choices-1-votes" value="900"></li> <li>Order: <input type="number" name="choices-1-ORDER" value="2"></li> <li>Delete: <input type="checkbox" name="choices-1-DELETE"></li> <li>Choice: <input type="text" name="choices-2-choice" value="The Decemberists"></li> <li>Votes: <input type="number" name="choices-2-votes" value="500"></li> <li>Order: <input type="number" name="choices-2-ORDER" value="3"></li> <li>Delete: <input type="checkbox" name="choices-2-DELETE"></li> <li>Choice: <input type="text" name="choices-3-choice"></li> <li>Votes: <input type="number" name="choices-3-votes"></li> <li>Order: <input type="number" name="choices-3-ORDER"></li> <li>Delete: <input type="checkbox" name="choices-3-DELETE"></li>""", ) # Let's delete Fergie, and put The Decemberists ahead of Calexico. data = { "choices-TOTAL_FORMS": "4", # the number of forms rendered "choices-INITIAL_FORMS": "3", # the number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", "choices-0-ORDER": "1", "choices-0-DELETE": "", "choices-1-choice": "Fergie", "choices-1-votes": "900", "choices-1-ORDER": "2", "choices-1-DELETE": "on", "choices-2-choice": "The Decemberists", "choices-2-votes": "500", "choices-2-ORDER": "0", "choices-2-DELETE": "", "choices-3-choice": "", "choices-3-votes": "", "choices-3-ORDER": "", "choices-3-DELETE": "", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertEqual( [form.cleaned_data for form in formset.ordered_forms], [ { "votes": 500, "DELETE": False, "ORDER": 0, "choice": "The Decemberists", }, {"votes": 100, "DELETE": False, "ORDER": 1, "choice": "Calexico"}, ], ) self.assertEqual( [form.cleaned_data for form in formset.deleted_forms], [{"votes": 900, "DELETE": True, "ORDER": 2, "choice": "Fergie"}], ) def test_invalid_deleted_form_with_ordering(self): """ Can get ordered_forms from a valid formset even if a deleted form would have been invalid. """ FavoriteDrinkFormset = formset_factory( form=FavoriteDrinkForm, can_delete=True, can_order=True ) formset = FavoriteDrinkFormset( { "form-0-name": "", "form-0-DELETE": "on", # no name! "form-TOTAL_FORMS": 1, "form-INITIAL_FORMS": 1, "form-MIN_NUM_FORMS": 0, "form-MAX_NUM_FORMS": 1, } ) self.assertTrue(formset.is_valid()) self.assertEqual(formset.ordered_forms, []) def test_clean_hook(self): """ FormSets have a clean() hook for doing extra validation that isn't tied to any form. It follows the same pattern as the clean() hook on Forms. """ # Start out with a some duplicate data. data = { "drinks-TOTAL_FORMS": "2", # the number of forms rendered "drinks-INITIAL_FORMS": "0", # the number of forms with initial data "drinks-MIN_NUM_FORMS": "0", # min number of forms "drinks-MAX_NUM_FORMS": "0", # max number of forms "drinks-0-name": "Gin and Tonic", "drinks-1-name": "Gin and Tonic", } formset = FavoriteDrinksFormSet(data, prefix="drinks") self.assertFalse(formset.is_valid()) # Any errors raised by formset.clean() are available via the # formset.non_form_errors() method. for error in formset.non_form_errors(): self.assertEqual(str(error), "You may only specify a drink once.") # The valid case still works. data["drinks-1-name"] = "Bloody Mary" formset = FavoriteDrinksFormSet(data, prefix="drinks") self.assertTrue(formset.is_valid()) self.assertEqual(formset.non_form_errors(), []) def test_limiting_max_forms(self): """Limiting the maximum number of forms with max_num.""" # When not passed, max_num will take a high default value, leaving the # number of forms only controlled by the value of the extra parameter. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=3) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """<div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" id="id_form-0-name"></div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div> <div><label for="id_form-2-name">Name:</label> <input type="text" name="form-2-name" id="id_form-2-name"></div>""", ) # If max_num is 0 then no form is rendered at all. LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=3, max_num=0 ) formset = LimitedFavoriteDrinkFormSet() self.assertEqual(formset.forms, []) def test_limited_max_forms_two(self): LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=5, max_num=2 ) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """<div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" id="id_form-0-name"></div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div>""", ) def test_limiting_extra_lest_than_max_num(self): """max_num has no effect when extra is less than max_num.""" LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=2 ) formset = LimitedFavoriteDrinkFormSet() self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """<div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" id="id_form-0-name"></div>""", ) def test_max_num_with_initial_data(self): # When not passed, max_num will take a high default value, leaving the # number of forms only controlled by the value of the initial and extra # parameters. LimitedFavoriteDrinkFormSet = formset_factory(FavoriteDrinkForm, extra=1) formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Fernet and Coke"}]) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" value="Fernet and Coke" id="id_form-0-name"></div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div> """, ) def test_max_num_zero(self): """ If max_num is 0 then no form is rendered at all, regardless of extra, unless initial data is present. """ LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=0 ) formset = LimitedFavoriteDrinkFormSet() self.assertEqual(formset.forms, []) def test_max_num_zero_with_initial(self): # initial trumps max_num initial = [ {"name": "Fernet and Coke"}, {"name": "Bloody Mary"}, ] LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=0 ) formset = LimitedFavoriteDrinkFormSet(initial=initial) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" name="form-0-name" type="text" value="Fernet and Coke"></div> <div><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></div> """, ) def test_more_initial_than_max_num(self): """ More initial forms than max_num results in all initial forms being displayed (but no extra forms). """ initial = [ {"name": "Gin Tonic"}, {"name": "Bloody Mary"}, {"name": "Jack and Coke"}, ] LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=1, max_num=2 ) formset = LimitedFavoriteDrinkFormSet(initial=initial) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input id="id_form-0-name" name="form-0-name" type="text" value="Gin Tonic"> </div> <div><label for="id_form-1-name">Name:</label> <input id="id_form-1-name" name="form-1-name" type="text" value="Bloody Mary"></div> <div><label for="id_form-2-name">Name:</label> <input id="id_form-2-name" name="form-2-name" type="text" value="Jack and Coke"></div> """, ) def test_default_absolute_max(self): # absolute_max defaults to 2 * DEFAULT_MAX_NUM if max_num is None. data = { "form-TOTAL_FORMS": 2001, "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "0", } formset = FavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), False) self.assertEqual( formset.non_form_errors(), ["Please submit at most 1000 forms."], ) self.assertEqual(formset.absolute_max, 2000) def test_absolute_max(self): data = { "form-TOTAL_FORMS": "2001", "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "0", } AbsoluteMaxFavoriteDrinksFormSet = formset_factory( FavoriteDrinkForm, absolute_max=3000, ) formset = AbsoluteMaxFavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), True) self.assertEqual(len(formset.forms), 2001) # absolute_max provides a hard limit. data["form-TOTAL_FORMS"] = "3001" formset = AbsoluteMaxFavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), False) self.assertEqual(len(formset.forms), 3000) self.assertEqual( formset.non_form_errors(), ["Please submit at most 1000 forms."], ) def test_absolute_max_with_max_num(self): data = { "form-TOTAL_FORMS": "1001", "form-INITIAL_FORMS": "0", "form-MAX_NUM_FORMS": "0", } LimitedFavoriteDrinksFormSet = formset_factory( FavoriteDrinkForm, max_num=30, absolute_max=1000, ) formset = LimitedFavoriteDrinksFormSet(data=data) self.assertIs(formset.is_valid(), False) self.assertEqual(len(formset.forms), 1000) self.assertEqual( formset.non_form_errors(), ["Please submit at most 30 forms."], ) def test_absolute_max_invalid(self): msg = "'absolute_max' must be greater or equal to 'max_num'." for max_num in [None, 31]: with self.subTest(max_num=max_num): with self.assertRaisesMessage(ValueError, msg): formset_factory(FavoriteDrinkForm, max_num=max_num, absolute_max=30) def test_more_initial_form_result_in_one(self): """ One form from initial and extra=3 with max_num=2 results in the one initial form and one extra. """ LimitedFavoriteDrinkFormSet = formset_factory( FavoriteDrinkForm, extra=3, max_num=2 ) formset = LimitedFavoriteDrinkFormSet(initial=[{"name": "Gin Tonic"}]) self.assertHTMLEqual( "\n".join(str(form) for form in formset.forms), """ <div><label for="id_form-0-name">Name:</label> <input type="text" name="form-0-name" value="Gin Tonic" id="id_form-0-name"> </div> <div><label for="id_form-1-name">Name:</label> <input type="text" name="form-1-name" id="id_form-1-name"></div>""", ) def test_management_form_field_names(self): """The management form class has field names matching the constants.""" self.assertCountEqual( ManagementForm.base_fields, [ TOTAL_FORM_COUNT, INITIAL_FORM_COUNT, MIN_NUM_FORM_COUNT, MAX_NUM_FORM_COUNT, ], ) def test_management_form_prefix(self): """The management form has the correct prefix.""" formset = FavoriteDrinksFormSet() self.assertEqual(formset.management_form.prefix, "form") data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "0", "form-MIN_NUM_FORMS": "0", "form-MAX_NUM_FORMS": "0", } formset = FavoriteDrinksFormSet(data=data) self.assertEqual(formset.management_form.prefix, "form") formset = FavoriteDrinksFormSet(initial={}) self.assertEqual(formset.management_form.prefix, "form") def test_non_form_errors(self): data = { "drinks-TOTAL_FORMS": "2", # the number of forms rendered "drinks-INITIAL_FORMS": "0", # the number of forms with initial data "drinks-MIN_NUM_FORMS": "0", # min number of forms "drinks-MAX_NUM_FORMS": "0", # max number of forms "drinks-0-name": "Gin and Tonic", "drinks-1-name": "Gin and Tonic", } formset = FavoriteDrinksFormSet(data, prefix="drinks") self.assertFalse(formset.is_valid()) self.assertEqual( formset.non_form_errors(), ["You may only specify a drink once."] ) self.assertEqual( str(formset.non_form_errors()), '<ul class="errorlist nonform"><li>' "You may only specify a drink once.</li></ul>", ) def test_formset_iteration(self): """Formset instances are iterable.""" ChoiceFormset = formset_factory(Choice, extra=3) formset = ChoiceFormset() # An iterated formset yields formset.forms. forms = list(formset) self.assertEqual(forms, formset.forms) self.assertEqual(len(formset), len(forms)) # A formset may be indexed to retrieve its forms. self.assertEqual(formset[0], forms[0]) with self.assertRaises(IndexError): formset[3] # Formsets can override the default iteration order class BaseReverseFormSet(BaseFormSet): def __iter__(self): return reversed(self.forms) def __getitem__(self, idx): return super().__getitem__(len(self) - idx - 1) ReverseChoiceFormset = formset_factory(Choice, BaseReverseFormSet, extra=3) reverse_formset = ReverseChoiceFormset() # __iter__() modifies the rendering order. # Compare forms from "reverse" formset with forms from original formset self.assertEqual(str(reverse_formset[0]), str(forms[-1])) self.assertEqual(str(reverse_formset[1]), str(forms[-2])) self.assertEqual(len(reverse_formset), len(forms)) def test_formset_nonzero(self): """A formsets without any forms evaluates as True.""" ChoiceFormset = formset_factory(Choice, extra=0) formset = ChoiceFormset() self.assertEqual(len(formset.forms), 0) self.assertTrue(formset) def test_formset_splitdatetimefield(self): """ Formset works with SplitDateTimeField(initial=datetime.datetime.now). """ class SplitDateTimeForm(Form): when = SplitDateTimeField(initial=datetime.datetime.now) SplitDateTimeFormSet = formset_factory(SplitDateTimeForm) data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", "form-0-when_0": "1904-06-16", "form-0-when_1": "15:51:33", } formset = SplitDateTimeFormSet(data) self.assertTrue(formset.is_valid()) def test_formset_error_class(self): """Formset's forms use the formset's error_class.""" class CustomErrorList(ErrorList): pass formset = FavoriteDrinksFormSet(error_class=CustomErrorList) self.assertEqual(formset.forms[0].error_class, CustomErrorList) def test_formset_calls_forms_is_valid(self): """Formsets call is_valid() on each form.""" class AnotherChoice(Choice): def is_valid(self): self.is_valid_called = True return super().is_valid() AnotherChoiceFormSet = formset_factory(AnotherChoice) data = { "choices-TOTAL_FORMS": "1", # number of forms rendered "choices-INITIAL_FORMS": "0", # number of forms with initial data "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "0", # max number of forms "choices-0-choice": "Calexico", "choices-0-votes": "100", } formset = AnotherChoiceFormSet(data, auto_id=False, prefix="choices") self.assertTrue(formset.is_valid()) self.assertTrue(all(form.is_valid_called for form in formset.forms)) def test_hard_limit_on_instantiated_forms(self): """A formset has a hard limit on the number of forms instantiated.""" # reduce the default limit of 1000 temporarily for testing _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 2 ChoiceFormSet = formset_factory(Choice, max_num=1) # someone fiddles with the mgmt form data... formset = ChoiceFormSet( { "choices-TOTAL_FORMS": "4", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "4", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", "choices-2-choice": "Two", "choices-2-votes": "2", "choices-3-choice": "Three", "choices-3-votes": "3", }, prefix="choices", ) # But we still only instantiate 3 forms self.assertEqual(len(formset.forms), 3) # and the formset isn't valid self.assertFalse(formset.is_valid()) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM def test_increase_hard_limit(self): """Can increase the built-in forms limit via a higher max_num.""" # reduce the default limit of 1000 temporarily for testing _old_DEFAULT_MAX_NUM = formsets.DEFAULT_MAX_NUM try: formsets.DEFAULT_MAX_NUM = 3 # for this form, we want a limit of 4 ChoiceFormSet = formset_factory(Choice, max_num=4) formset = ChoiceFormSet( { "choices-TOTAL_FORMS": "4", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", # min number of forms "choices-MAX_NUM_FORMS": "4", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", "choices-2-choice": "Two", "choices-2-votes": "2", "choices-3-choice": "Three", "choices-3-votes": "3", }, prefix="choices", ) # Four forms are instantiated and no exception is raised self.assertEqual(len(formset.forms), 4) finally: formsets.DEFAULT_MAX_NUM = _old_DEFAULT_MAX_NUM def test_non_form_errors_run_full_clean(self): """ If non_form_errors() is called without calling is_valid() first, it should ensure that full_clean() is called. """ class BaseCustomFormSet(BaseFormSet): def clean(self): raise ValidationError("This is a non-form error") ChoiceFormSet = formset_factory(Choice, formset=BaseCustomFormSet) data = { "choices-TOTAL_FORMS": "1", "choices-INITIAL_FORMS": "0", } formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertIsInstance(formset.non_form_errors(), ErrorList) self.assertEqual(list(formset.non_form_errors()), ["This is a non-form error"]) def test_validate_max_ignores_forms_marked_for_deletion(self): class CheckForm(Form): field = IntegerField() data = { "check-TOTAL_FORMS": "2", "check-INITIAL_FORMS": "0", "check-MAX_NUM_FORMS": "1", "check-0-field": "200", "check-0-DELETE": "", "check-1-field": "50", "check-1-DELETE": "on", } CheckFormSet = formset_factory( CheckForm, max_num=1, validate_max=True, can_delete=True ) formset = CheckFormSet(data, prefix="check") self.assertTrue(formset.is_valid()) def test_formset_total_error_count(self): """A valid formset should have 0 total errors.""" data = [ # formset_data, expected error count ([("Calexico", "100")], 0), ([("Calexico", "")], 1), ([("", "invalid")], 2), ([("Calexico", "100"), ("Calexico", "")], 1), ([("Calexico", ""), ("Calexico", "")], 2), ] for formset_data, expected_error_count in data: formset = self.make_choiceformset(formset_data) self.assertEqual(formset.total_error_count(), expected_error_count) def test_formset_total_error_count_with_non_form_errors(self): data = { "choices-TOTAL_FORMS": "2", # the number of forms rendered "choices-INITIAL_FORMS": "0", # the number of forms with initial data "choices-MAX_NUM_FORMS": "2", # max number of forms - should be ignored "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice, extra=1, max_num=1, validate_max=True) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertEqual(formset.total_error_count(), 1) data["choices-1-votes"] = "" formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertEqual(formset.total_error_count(), 2) def test_html_safe(self): formset = self.make_choiceformset() self.assertTrue(hasattr(formset, "__html__")) self.assertEqual(str(formset), formset.__html__()) def test_can_delete_extra_formset_forms(self): ChoiceFormFormset = formset_factory(form=Choice, can_delete=True, extra=2) formset = ChoiceFormFormset() self.assertEqual(len(formset), 2) self.assertIn("DELETE", formset.forms[0].fields) self.assertIn("DELETE", formset.forms[1].fields) def test_disable_delete_extra_formset_forms(self): ChoiceFormFormset = formset_factory( form=Choice, can_delete=True, can_delete_extra=False, extra=2, ) formset = ChoiceFormFormset() self.assertEqual(len(formset), 2) self.assertNotIn("DELETE", formset.forms[0].fields) self.assertNotIn("DELETE", formset.forms[1].fields) formset = ChoiceFormFormset(initial=[{"choice": "Zero", "votes": "1"}]) self.assertEqual(len(formset), 3) self.assertIn("DELETE", formset.forms[0].fields) self.assertNotIn("DELETE", formset.forms[1].fields) self.assertNotIn("DELETE", formset.forms[2].fields) formset = ChoiceFormFormset( data={ "form-0-choice": "Zero", "form-0-votes": "0", "form-0-DELETE": "on", "form-1-choice": "One", "form-1-votes": "1", "form-2-choice": "", "form-2-votes": "", "form-TOTAL_FORMS": "3", "form-INITIAL_FORMS": "1", }, initial=[{"choice": "Zero", "votes": "1"}], ) self.assertEqual( formset.cleaned_data, [ {"choice": "Zero", "votes": 0, "DELETE": True}, {"choice": "One", "votes": 1}, {}, ], ) self.assertIs(formset._should_delete_form(formset.forms[0]), True) self.assertIs(formset._should_delete_form(formset.forms[1]), False) self.assertIs(formset._should_delete_form(formset.forms[2]), False) def test_template_name_uses_renderer_value(self): class CustomRenderer(TemplatesSetting): formset_template_name = "a/custom/formset/template.html" ChoiceFormSet = formset_factory(Choice, renderer=CustomRenderer) self.assertEqual( ChoiceFormSet().template_name, "a/custom/formset/template.html" ) def test_template_name_can_be_overridden(self): class CustomFormSet(BaseFormSet): template_name = "a/custom/formset/template.html" ChoiceFormSet = formset_factory(Choice, formset=CustomFormSet) self.assertEqual( ChoiceFormSet().template_name, "a/custom/formset/template.html" ) def test_custom_renderer(self): """ A custom renderer passed to a formset_factory() is passed to all forms and ErrorList. """ from django.forms.renderers import Jinja2 renderer = Jinja2() data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-0-choice": "Zero", "choices-0-votes": "", "choices-1-choice": "One", "choices-1-votes": "", } ChoiceFormSet = formset_factory(Choice, renderer=renderer) formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertEqual(formset.renderer, renderer) self.assertEqual(formset.forms[0].renderer, renderer) self.assertEqual(formset.management_form.renderer, renderer) self.assertEqual(formset.non_form_errors().renderer, renderer) self.assertEqual(formset.empty_form.renderer, renderer) def test_repr(self): valid_formset = self.make_choiceformset([("test", 1)]) valid_formset.full_clean() invalid_formset = self.make_choiceformset([("test", "")]) invalid_formset.full_clean() partially_invalid_formset = self.make_choiceformset( [("test", "1"), ("test", "")], ) partially_invalid_formset.full_clean() invalid_formset_non_form_errors_only = self.make_choiceformset( [("test", "")], formset_class=ChoiceFormsetWithNonFormError, ) invalid_formset_non_form_errors_only.full_clean() cases = [ ( self.make_choiceformset(), "<ChoiceFormSet: bound=False valid=Unknown total_forms=1>", ), ( self.make_choiceformset( formset_class=formset_factory(Choice, extra=10), ), "<ChoiceFormSet: bound=False valid=Unknown total_forms=10>", ), ( self.make_choiceformset([]), "<ChoiceFormSet: bound=True valid=Unknown total_forms=0>", ), ( self.make_choiceformset([("test", 1)]), "<ChoiceFormSet: bound=True valid=Unknown total_forms=1>", ), (valid_formset, "<ChoiceFormSet: bound=True valid=True total_forms=1>"), (invalid_formset, "<ChoiceFormSet: bound=True valid=False total_forms=1>"), ( partially_invalid_formset, "<ChoiceFormSet: bound=True valid=False total_forms=2>", ), ( invalid_formset_non_form_errors_only, "<ChoiceFormsetWithNonFormError: bound=True valid=False total_forms=1>", ), ] for formset, expected_repr in cases: with self.subTest(expected_repr=expected_repr): self.assertEqual(repr(formset), expected_repr) def test_repr_do_not_trigger_validation(self): formset = self.make_choiceformset([("test", 1)]) with mock.patch.object(formset, "full_clean") as mocked_full_clean: repr(formset) mocked_full_clean.assert_not_called() formset.is_valid() mocked_full_clean.assert_called() @jinja2_tests class Jinja2FormsFormsetTestCase(FormsFormsetTestCase): pass class FormsetAsTagTests(SimpleTestCase): def setUp(self): data = { "choices-TOTAL_FORMS": "1", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-MAX_NUM_FORMS": "0", "choices-0-choice": "Calexico", "choices-0-votes": "100", } self.formset = ChoiceFormSet(data, auto_id=False, prefix="choices") self.management_form_html = ( '<input type="hidden" name="choices-TOTAL_FORMS" value="1">' '<input type="hidden" name="choices-INITIAL_FORMS" value="0">' '<input type="hidden" name="choices-MIN_NUM_FORMS" value="0">' '<input type="hidden" name="choices-MAX_NUM_FORMS" value="0">' ) def test_as_table(self): self.assertHTMLEqual( self.formset.as_table(), self.management_form_html + ( "<tr><th>Choice:</th><td>" '<input type="text" name="choices-0-choice" value="Calexico"></td></tr>' "<tr><th>Votes:</th><td>" '<input type="number" name="choices-0-votes" value="100"></td></tr>' ), ) def test_as_p(self): self.assertHTMLEqual( self.formset.as_p(), self.management_form_html + ( "<p>Choice: " '<input type="text" name="choices-0-choice" value="Calexico"></p>' '<p>Votes: <input type="number" name="choices-0-votes" value="100"></p>' ), ) def test_as_ul(self): self.assertHTMLEqual( self.formset.as_ul(), self.management_form_html + ( "<li>Choice: " '<input type="text" name="choices-0-choice" value="Calexico"></li>' "<li>Votes: " '<input type="number" name="choices-0-votes" value="100"></li>' ), ) def test_as_div(self): self.assertHTMLEqual( self.formset.as_div(), self.management_form_html + ( "<div>Choice: " '<input type="text" name="choices-0-choice" value="Calexico"></div>' '<div>Votes: <input type="number" name="choices-0-votes" value="100">' "</div>" ), ) @jinja2_tests class Jinja2FormsetAsTagTests(FormsetAsTagTests): pass class ArticleForm(Form): title = CharField() pub_date = DateField() ArticleFormSet = formset_factory(ArticleForm) class TestIsBoundBehavior(SimpleTestCase): def test_no_data_error(self): formset = ArticleFormSet({}) self.assertIs(formset.is_valid(), False) self.assertEqual( formset.non_form_errors(), [ "ManagementForm data is missing or has been tampered with. " "Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. " "You may need to file a bug report if the issue persists.", ], ) self.assertEqual(formset.errors, []) # Can still render the formset. self.assertHTMLEqual( str(formset), '<ul class="errorlist nonfield">' "<li>(Hidden field TOTAL_FORMS) This field is required.</li>" "<li>(Hidden field INITIAL_FORMS) This field is required.</li>" "</ul>" "<div>" '<input type="hidden" name="form-TOTAL_FORMS" id="id_form-TOTAL_FORMS">' '<input type="hidden" name="form-INITIAL_FORMS" id="id_form-INITIAL_FORMS">' '<input type="hidden" name="form-MIN_NUM_FORMS" id="id_form-MIN_NUM_FORMS">' '<input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS">' "</div>\n", ) def test_management_form_invalid_data(self): data = { "form-TOTAL_FORMS": "two", "form-INITIAL_FORMS": "one", } formset = ArticleFormSet(data) self.assertIs(formset.is_valid(), False) self.assertEqual( formset.non_form_errors(), [ "ManagementForm data is missing or has been tampered with. " "Missing fields: form-TOTAL_FORMS, form-INITIAL_FORMS. " "You may need to file a bug report if the issue persists.", ], ) self.assertEqual(formset.errors, []) # Can still render the formset. self.assertHTMLEqual( str(formset), '<ul class="errorlist nonfield">' "<li>(Hidden field TOTAL_FORMS) Enter a whole number.</li>" "<li>(Hidden field INITIAL_FORMS) Enter a whole number.</li>" "</ul>" "<div>" '<input type="hidden" name="form-TOTAL_FORMS" value="two" ' 'id="id_form-TOTAL_FORMS">' '<input type="hidden" name="form-INITIAL_FORMS" value="one" ' 'id="id_form-INITIAL_FORMS">' '<input type="hidden" name="form-MIN_NUM_FORMS" id="id_form-MIN_NUM_FORMS">' '<input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS">' "</div>\n", ) def test_customize_management_form_error(self): formset = ArticleFormSet( {}, error_messages={"missing_management_form": "customized"} ) self.assertIs(formset.is_valid(), False) self.assertEqual(formset.non_form_errors(), ["customized"]) self.assertEqual(formset.errors, []) def test_with_management_data_attrs_work_fine(self): data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", } formset = ArticleFormSet(data) self.assertEqual(0, formset.initial_form_count()) self.assertEqual(1, formset.total_form_count()) self.assertTrue(formset.is_bound) self.assertTrue(formset.forms[0].is_bound) self.assertTrue(formset.is_valid()) self.assertTrue(formset.forms[0].is_valid()) self.assertEqual([{}], formset.cleaned_data) def test_form_errors_are_caught_by_formset(self): data = { "form-TOTAL_FORMS": "2", "form-INITIAL_FORMS": "0", "form-0-title": "Test", "form-0-pub_date": "1904-06-16", "form-1-title": "Test", "form-1-pub_date": "", # <-- this date is missing but required } formset = ArticleFormSet(data) self.assertFalse(formset.is_valid()) self.assertEqual( [{}, {"pub_date": ["This field is required."]}], formset.errors ) def test_empty_forms_are_unbound(self): data = { "form-TOTAL_FORMS": "1", "form-INITIAL_FORMS": "0", "form-0-title": "Test", "form-0-pub_date": "1904-06-16", } unbound_formset = ArticleFormSet() bound_formset = ArticleFormSet(data) empty_forms = [unbound_formset.empty_form, bound_formset.empty_form] # Empty forms should be unbound self.assertFalse(empty_forms[0].is_bound) self.assertFalse(empty_forms[1].is_bound) # The empty forms should be equal. self.assertHTMLEqual(empty_forms[0].as_p(), empty_forms[1].as_p()) @jinja2_tests class TestIsBoundBehavior(TestIsBoundBehavior): pass class TestEmptyFormSet(SimpleTestCase): def test_empty_formset_is_valid(self): """An empty formset still calls clean()""" class EmptyFsetWontValidate(BaseFormSet): def clean(self): raise ValidationError("Clean method called") EmptyFsetWontValidateFormset = formset_factory( FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate ) formset = EmptyFsetWontValidateFormset( data={"form-INITIAL_FORMS": "0", "form-TOTAL_FORMS": "0"}, prefix="form", ) formset2 = EmptyFsetWontValidateFormset( data={ "form-INITIAL_FORMS": "0", "form-TOTAL_FORMS": "1", "form-0-name": "bah", }, prefix="form", ) self.assertFalse(formset.is_valid()) self.assertFalse(formset2.is_valid()) def test_empty_formset_media(self): """Media is available on empty formset.""" class MediaForm(Form): class Media: js = ("some-file.js",) self.assertIn("some-file.js", str(formset_factory(MediaForm, extra=0)().media)) def test_empty_formset_is_multipart(self): """is_multipart() works with an empty formset.""" class FileForm(Form): file = FileField() self.assertTrue(formset_factory(FileForm, extra=0)().is_multipart()) class AllValidTests(SimpleTestCase): def test_valid(self): data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-0-choice": "Zero", "choices-0-votes": "0", "choices-1-choice": "One", "choices-1-votes": "1", } ChoiceFormSet = formset_factory(Choice) formset1 = ChoiceFormSet(data, auto_id=False, prefix="choices") formset2 = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertIs(all_valid((formset1, formset2)), True) expected_errors = [{}, {}] self.assertEqual(formset1._errors, expected_errors) self.assertEqual(formset2._errors, expected_errors) def test_invalid(self): """all_valid() validates all forms, even when some are invalid.""" data = { "choices-TOTAL_FORMS": "2", "choices-INITIAL_FORMS": "0", "choices-MIN_NUM_FORMS": "0", "choices-0-choice": "Zero", "choices-0-votes": "", "choices-1-choice": "One", "choices-1-votes": "", } ChoiceFormSet = formset_factory(Choice) formset1 = ChoiceFormSet(data, auto_id=False, prefix="choices") formset2 = ChoiceFormSet(data, auto_id=False, prefix="choices") self.assertIs(all_valid((formset1, formset2)), False) expected_errors = [ {"votes": ["This field is required."]}, {"votes": ["This field is required."]}, ] self.assertEqual(formset1._errors, expected_errors) self.assertEqual(formset2._errors, expected_errors) class DeprecationTests(SimpleTestCase): def test_warning(self): from django.forms.utils import DEFAULT_TEMPLATE_DEPRECATION_MSG with isolate_lru_cache(get_default_renderer), self.settings( FORM_RENDERER="django.forms.renderers.DjangoTemplates" ), self.assertRaisesMessage( RemovedInDjango50Warning, DEFAULT_TEMPLATE_DEPRECATION_MSG ): ChoiceFormSet = formset_factory(Choice) formset = ChoiceFormSet() str(formset)
9f45eb0d4738dc59d56bcd1536f293680a3a14e07a76925f4413d123fab5118a
from unittest import skipIf from django.test.utils import override_settings try: import jinja2 except ImportError: jinja2 = None def jinja2_tests(test_func): test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func) return override_settings( # RemovedInDjango50Warning: When the deprecation ends, revert to # FORM_RENDERER="django.forms.renderers.Jinja2", FORM_RENDERER="django.forms.renderers.Jinja2DivFormRenderer", TEMPLATES={"BACKEND": "django.template.backends.jinja2.Jinja2"}, )(test_func)
e7d2dffa86d7ed49591deb747b7b9735a7b6c0573fad476337b79fbbc808ada7
import copy import datetime import json import uuid from django.core.exceptions import NON_FIELD_ERRORS from django.core.files.uploadedfile import SimpleUploadedFile from django.core.validators import MaxValueValidator, RegexValidator from django.forms import ( BooleanField, CharField, CheckboxSelectMultiple, ChoiceField, DateField, DateTimeField, EmailField, FileField, FileInput, FloatField, Form, HiddenInput, ImageField, IntegerField, MultipleChoiceField, MultipleHiddenInput, MultiValueField, MultiWidget, NullBooleanField, PasswordInput, RadioSelect, Select, SplitDateTimeField, SplitHiddenDateTimeWidget, Textarea, TextInput, TimeField, ValidationError, forms, ) from django.forms.renderers import DjangoTemplates, get_default_renderer from django.forms.utils import ErrorList from django.http import QueryDict from django.template import Context, Template from django.test import SimpleTestCase from django.test.utils import isolate_lru_cache, override_settings from django.utils.datastructures import MultiValueDict from django.utils.deprecation import RemovedInDjango50Warning from django.utils.safestring import mark_safe from . import jinja2_tests class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[("P", "Python"), ("J", "Java")], widget=RadioSelect) class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class PersonNew(Form): first_name = CharField(widget=TextInput(attrs={"id": "first_name_id"})) last_name = CharField() birthday = DateField() class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) class MultiValueDictLike(dict): def getlist(self, key): return [self[key]] class FormsTestCase(SimpleTestCase): # A Form is a collection of Fields. It knows how to validate a set of data and it # knows how to render itself in a couple of default ways (e.g., an HTML table). # You can pass it data in __init__(), as a dictionary. def test_form(self): # Pass a dictionary to a Form's __init__(). p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} ) self.assertTrue(p.is_bound) self.assertEqual(p.errors, {}) self.assertIsInstance(p.errors, dict) self.assertTrue(p.is_valid()) self.assertHTMLEqual(p.errors.as_ul(), "") self.assertEqual(p.errors.as_text(), "") self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) self.assertHTMLEqual( str(p["first_name"]), '<input type="text" name="first_name" value="John" id="id_first_name" ' "required>", ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="last_name" value="Lennon" id="id_last_name" ' "required>", ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required>", ) msg = ( "Key 'nonexistentfield' not found in 'Person'. Choices are: birthday, " "first_name, last_name." ) with self.assertRaisesMessage(KeyError, msg): p["nonexistentfield"] form_output = [] for boundfield in p: form_output.append(str(boundfield)) self.assertHTMLEqual( "\n".join(form_output), """<input type="text" name="first_name" value="John" id="id_first_name" required> <input type="text" name="last_name" value="Lennon" id="id_last_name" required> <input type="text" name="birthday" value="1940-10-9" id="id_birthday" required>""", ) form_output = [] for boundfield in p: form_output.append([boundfield.label, boundfield.data]) self.assertEqual( form_output, [ ["First name", "John"], ["Last name", "Lennon"], ["Birthday", "1940-10-9"], ], ) self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" value="John" required id="id_first_name"></div><div>' '<label for="id_last_name">Last name:</label><input type="text" ' 'name="last_name" value="Lennon" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label><input type="text" ' 'name="birthday" value="1940-10-9" required id="id_birthday"></div>', ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" value="John" required id="id_first_name"></div><div>' '<label for="id_last_name">Last name:</label><input type="text" ' 'name="last_name" value="Lennon" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label><input type="text" ' 'name="birthday" value="1940-10-9" required id="id_birthday"></div>', ) def test_empty_dict(self): # Empty dictionaries are valid, too. p = Person({}) self.assertTrue(p.is_bound) self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {}) self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="first_name" required id="id_first_name"></div>' '<div><label for="id_last_name">Last name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="last_name" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="birthday" required id="id_birthday"></div>', ) self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="birthday" id="id_birthday" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> <label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <ul class="errorlist"><li>This field is required.</li></ul> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="first_name" required id="id_first_name"></div>' '<div><label for="id_last_name">Last name:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="last_name" required id="id_last_name"></div><div>' '<label for="id_birthday">Birthday:</label>' '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="birthday" required id="id_birthday"></div>', ) def test_empty_querydict_args(self): data = QueryDict() files = QueryDict() p = Person(data, files) self.assertIs(p.data, data) self.assertIs(p.files, files) def test_unbound_form(self): # If you don't pass any values to the Form's __init__(), or if you pass None, # the Form will be considered unbound and won't do any validation. Form.errors # will be an empty dictionary *but* Form.is_valid() will return False. p = Person() self.assertFalse(p.is_bound) self.assertEqual(p.errors, {}) self.assertFalse(p.is_valid()) with self.assertRaises(AttributeError): p.cleaned_data self.assertHTMLEqual( str(p), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" id="id_birthday" ' "required></div>", ) self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" id="id_birthday" ' "required></div>", ) def test_unicode_values(self): # Unicode values are handled properly. p = Person( { "first_name": "John", "last_name": "\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111", "birthday": "1940-10-9", } ) self.assertHTMLEqual( p.as_table(), '<tr><th><label for="id_first_name">First name:</label></th><td>' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></td></tr>\n" '<tr><th><label for="id_last_name">Last name:</label>' '</th><td><input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111"' 'id="id_last_name" required></td></tr>\n' '<tr><th><label for="id_birthday">Birthday:</label></th><td>' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></td></tr>", ) self.assertHTMLEqual( p.as_ul(), '<li><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></li>\n" '<li><label for="id_last_name">Last name:</label> ' '<input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></li>\n' '<li><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></li>", ) self.assertHTMLEqual( p.as_p(), '<p><label for="id_first_name">First name:</label> ' '<input type="text" name="first_name" value="John" id="id_first_name" ' "required></p>\n" '<p><label for="id_last_name">Last name:</label> ' '<input type="text" name="last_name" ' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></p>\n' '<p><label for="id_birthday">Birthday:</label> ' '<input type="text" name="birthday" value="1940-10-9" id="id_birthday" ' "required></p>", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label>' '<input type="text" name="first_name" value="John" id="id_first_name" ' 'required></div><div><label for="id_last_name">Last name:</label>' '<input type="text" name="last_name"' 'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" ' 'id="id_last_name" required></div><div><label for="id_birthday">' 'Birthday:</label><input type="text" name="birthday" value="1940-10-9" ' 'id="id_birthday" required></div>', ) p = Person({"last_name": "Lennon"}) self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) self.assertFalse(p.is_valid()) self.assertEqual( p.errors, { "birthday": ["This field is required."], "first_name": ["This field is required."], }, ) self.assertEqual(p.cleaned_data, {"last_name": "Lennon"}) self.assertEqual(p["first_name"].errors, ["This field is required."]) self.assertHTMLEqual( p["first_name"].errors.as_ul(), '<ul class="errorlist"><li>This field is required.</li></ul>', ) self.assertEqual(p["first_name"].errors.as_text(), "* This field is required.") p = Person() self.assertHTMLEqual( str(p["first_name"]), '<input type="text" name="first_name" id="id_first_name" required>', ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="last_name" id="id_last_name" required>', ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="birthday" id="id_birthday" required>', ) def test_cleaned_data_only_fields(self): # cleaned_data will always *only* contain a key for fields defined in the # Form, even if you pass extra data when you define the Form. In this # example, we pass a bunch of extra fields to the form constructor, # but cleaned_data contains only the form's fields. data = { "first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9", "extra1": "hello", "extra2": "hello", } p = Person(data) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) def test_optional_data(self): # cleaned_data will include a key and value for *all* fields defined in # the Form, even if the Form's data didn't include a value for fields # that are not required. In this example, the data dictionary doesn't # include a value for the "nick_name" field, but cleaned_data includes # it. For CharFields, it's set to the empty string. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() nick_name = CharField(required=False) data = {"first_name": "John", "last_name": "Lennon"} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["nick_name"], "") self.assertEqual(f.cleaned_data["first_name"], "John") self.assertEqual(f.cleaned_data["last_name"], "Lennon") # For DateFields, it's set to None. class OptionalPersonForm(Form): first_name = CharField() last_name = CharField() birth_date = DateField(required=False) data = {"first_name": "John", "last_name": "Lennon"} f = OptionalPersonForm(data) self.assertTrue(f.is_valid()) self.assertIsNone(f.cleaned_data["birth_date"]) self.assertEqual(f.cleaned_data["first_name"], "John") self.assertEqual(f.cleaned_data["last_name"], "Lennon") def test_auto_id(self): # "auto_id" tells the Form to add an "id" attribute to each form # element. If it's a string that contains '%s', Django will use that as # a format string into which the field's name will be inserted. It will # also put a <label> around the human-readable labels for a field. p = Person(auto_id="%s_id") self.assertHTMLEqual( p.as_table(), """<tr><th><label for="first_name_id">First name:</label></th><td> <input type="text" name="first_name" id="first_name_id" required></td></tr> <tr><th><label for="last_name_id">Last name:</label></th><td> <input type="text" name="last_name" id="last_name_id" required></td></tr> <tr><th><label for="birthday_id">Birthday:</label></th><td> <input type="text" name="birthday" id="birthday_id" required></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></li> <li><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></li> <li><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="first_name_id">First name:</label> <input type="text" name="first_name" id="first_name_id" required></p> <p><label for="last_name_id">Last name:</label> <input type="text" name="last_name" id="last_name_id" required></p> <p><label for="birthday_id">Birthday:</label> <input type="text" name="birthday" id="birthday_id" required></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="first_name_id">First name:</label><input type="text" ' 'name="first_name" id="first_name_id" required></div><div><label ' 'for="last_name_id">Last name:</label><input type="text" ' 'name="last_name" id="last_name_id" required></div><div><label ' 'for="birthday_id">Birthday:</label><input type="text" name="birthday" ' 'id="birthday_id" required></div>', ) def test_auto_id_true(self): # If auto_id is any True value whose str() does not contain '%s', the "id" # attribute will be the name of the field. p = Person(auto_id=True) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name">First name:</label> <input type="text" name="first_name" id="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></li>""", ) def test_auto_id_false(self): # If auto_id is any False value, an "id" attribute won't be output unless it # was manually entered. p = Person(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) def test_id_on_field(self): # In this example, auto_id is False, but the "id" attribute for the "first_name" # field is given. Also note that field gets a <label>, while the others don't. p = PersonNew(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) def test_auto_id_on_form_and_field(self): # If the "id" attribute is specified in the Form and auto_id is True, the "id" # attribute in the Form gets precedence. p = PersonNew(auto_id=True) self.assertHTMLEqual( p.as_ul(), """<li><label for="first_name_id">First name:</label> <input type="text" id="first_name_id" name="first_name" required></li> <li><label for="last_name">Last name:</label> <input type="text" name="last_name" id="last_name" required></li> <li><label for="birthday">Birthday:</label> <input type="text" name="birthday" id="birthday" required></li>""", ) def test_various_boolean_values(self): class SignupForm(Form): email = EmailField() get_spam = BooleanField() f = SignupForm(auto_id=False) self.assertHTMLEqual( str(f["email"]), '<input type="email" name="email" required>' ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) f = SignupForm({"email": "[email protected]", "get_spam": True}, auto_id=False) self.assertHTMLEqual( str(f["email"]), '<input type="email" name="email" value="[email protected]" required>', ) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) # 'True' or 'true' should be rendered without a value attribute f = SignupForm({"email": "[email protected]", "get_spam": "True"}, auto_id=False) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) f = SignupForm({"email": "[email protected]", "get_spam": "true"}, auto_id=False) self.assertHTMLEqual( str(f["get_spam"]), '<input checked type="checkbox" name="get_spam" required>', ) # A value of 'False' or 'false' should be rendered unchecked f = SignupForm( {"email": "[email protected]", "get_spam": "False"}, auto_id=False ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) f = SignupForm( {"email": "[email protected]", "get_spam": "false"}, auto_id=False ) self.assertHTMLEqual( str(f["get_spam"]), '<input type="checkbox" name="get_spam" required>' ) # A value of '0' should be interpreted as a True value (#16820) f = SignupForm({"email": "[email protected]", "get_spam": "0"}) self.assertTrue(f.is_valid()) self.assertTrue(f.cleaned_data.get("get_spam")) def test_widget_output(self): # Any Field can have a Widget class passed to its constructor: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea) f = ContactForm(auto_id=False) self.assertHTMLEqual( str(f["subject"]), '<input type="text" name="subject" required>' ) self.assertHTMLEqual( str(f["message"]), '<textarea name="message" rows="10" cols="40" required></textarea>', ) # as_textarea(), as_text() and as_hidden() are shortcuts for changing the output # widget type: self.assertHTMLEqual( f["subject"].as_textarea(), '<textarea name="subject" rows="10" cols="40" required></textarea>', ) self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" required>' ) self.assertHTMLEqual( f["message"].as_hidden(), '<input type="hidden" name="message">' ) # The 'widget' parameter to a Field can also be an instance: class ContactForm(Form): subject = CharField() message = CharField(widget=Textarea(attrs={"rows": 80, "cols": 20})) f = ContactForm(auto_id=False) self.assertHTMLEqual( str(f["message"]), '<textarea name="message" rows="80" cols="20" required></textarea>', ) # Instance-level attrs are *not* carried over to as_textarea(), as_text() and # as_hidden(): self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" required>' ) f = ContactForm({"subject": "Hello", "message": "I love you."}, auto_id=False) self.assertHTMLEqual( f["subject"].as_textarea(), '<textarea rows="10" cols="40" name="subject" required>Hello</textarea>', ) self.assertHTMLEqual( f["message"].as_text(), '<input type="text" name="message" value="I love you." required>', ) self.assertHTMLEqual( f["message"].as_hidden(), '<input type="hidden" name="message" value="I love you.">', ) def test_forms_with_choices(self): # For a form with a <select>, use ChoiceField: class FrameworkForm(Form): name = CharField() language = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # A subtlety: If one of the choices' value is the empty string and the form is # unbound, then the <option> for the empty-string choice will get selected. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("", "------"), ("P", "Python"), ("J", "Java")] ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language" required> <option value="" selected>------</option> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) # You can specify widget attributes in the Widget constructor. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("P", "Python"), ("J", "Java")], widget=Select(attrs={"class": "foo"}), ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # When passing a custom widget instance to ChoiceField, note that setting # 'choices' on the widget is meaningless. The widget will use the choices # defined on the Field, not the ones defined on the Widget. class FrameworkForm(Form): name = CharField() language = ChoiceField( choices=[("P", "Python"), ("J", "Java")], widget=Select( choices=[("R", "Ruby"), ("P", "Perl")], attrs={"class": "foo"} ), ) f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) f = FrameworkForm({"name": "Django", "language": "P"}, auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select class="foo" name="language"> <option value="P" selected>Python</option> <option value="J">Java</option> </select>""", ) # You can set a ChoiceField's choices after the fact. class FrameworkForm(Form): name = CharField() language = ChoiceField() f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<select name="language"> </select>""", ) f.fields["language"].choices = [("P", "Python"), ("J", "Java")] self.assertHTMLEqual( str(f["language"]), """<select name="language"> <option value="P">Python</option> <option value="J">Java</option> </select>""", ) def test_forms_with_radio(self): # Add widget=RadioSelect to use that widget with a ChoiceField. f = FrameworkForm(auto_id=False) self.assertHTMLEqual( str(f["language"]), """<div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div>""", ) self.assertHTMLEqual( f.as_table(), """<tr><th>Name:</th><td><input type="text" name="name" required></td></tr> <tr><th>Language:</th><td><div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div></td></tr>""", ) self.assertHTMLEqual( f.as_ul(), """<li>Name: <input type="text" name="name" required></li> <li>Language: <div> <div><label><input type="radio" name="language" value="P" required> Python</label></div> <div><label><input type="radio" name="language" value="J" required> Java</label></div> </div></li>""", ) # Need an auto_id to generate legend. self.assertHTMLEqual( f.render(f.template_name_div), '<div> Name: <input type="text" name="name" required></div><div><fieldset>' 'Language:<div><div><label><input type="radio" name="language" value="P" ' 'required> Python</label></div><div><label><input type="radio" ' 'name="language" value="J" required> Java</label></div></div></fieldset>' "</div>", ) # Regarding auto_id and <label>, RadioSelect is a special case. Each # radio button gets a distinct ID, formed by appending an underscore # plus the button's zero-based index. f = FrameworkForm(auto_id="id_%s") self.assertHTMLEqual( str(f["language"]), """ <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div>""", ) # When RadioSelect is used with auto_id, and the whole form is printed # using either as_table() or as_ul(), the label for the RadioSelect # will **not** point to the ID of the *first* radio button to improve # accessibility for screen reader users. self.assertHTMLEqual( f.as_table(), """ <tr><th><label for="id_name">Name:</label></th><td> <input type="text" name="name" id="id_name" required></td></tr> <tr><th><label>Language:</label></th><td><div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></td></tr>""", ) self.assertHTMLEqual( f.as_ul(), """ <li><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li><label>Language:</label> <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></li> """, ) self.assertHTMLEqual( f.as_p(), """ <p><label for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p><label>Language:</label> <div id="id_language"> <div><label for="id_language_0"> <input type="radio" id="id_language_0" value="P" name="language" required> Python</label></div> <div><label for="id_language_1"> <input type="radio" id="id_language_1" value="J" name="language" required> Java</label></div> </div></p> """, ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><fieldset><legend>Language:</legend>' '<div id="id_language"><div><label for="id_language_0"><input ' 'type="radio" name="language" value="P" required id="id_language_0">' 'Python</label></div><div><label for="id_language_1"><input type="radio" ' 'name="language" value="J" required id="id_language_1">Java</label></div>' "</div></fieldset></div>", ) def test_form_with_iterable_boundfield(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ], widget=RadioSelect, ) f = BeatleForm(auto_id=False) self.assertHTMLEqual( "\n".join(str(bf) for bf in f["name"]), """<label><input type="radio" name="name" value="john" required> John</label> <label><input type="radio" name="name" value="paul" required> Paul</label> <label><input type="radio" name="name" value="george" required> George</label> <label><input type="radio" name="name" value="ringo" required> Ringo</label>""", ) self.assertHTMLEqual( "\n".join("<div>%s</div>" % bf for bf in f["name"]), """ <div><label> <input type="radio" name="name" value="john" required> John</label></div> <div><label> <input type="radio" name="name" value="paul" required> Paul</label></div> <div><label> <input type="radio" name="name" value="george" required> George </label></div> <div><label> <input type="radio" name="name" value="ringo" required> Ringo</label></div> """, ) def test_form_with_iterable_boundfield_id(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ], widget=RadioSelect, ) fields = list(BeatleForm()["name"]) self.assertEqual(len(fields), 4) self.assertEqual(fields[0].id_for_label, "id_name_0") self.assertEqual(fields[0].choice_label, "John") self.assertHTMLEqual( fields[0].tag(), '<input type="radio" name="name" value="john" id="id_name_0" required>', ) self.assertHTMLEqual( str(fields[0]), '<label for="id_name_0"><input type="radio" name="name" ' 'value="john" id="id_name_0" required> John</label>', ) self.assertEqual(fields[1].id_for_label, "id_name_1") self.assertEqual(fields[1].choice_label, "Paul") self.assertHTMLEqual( fields[1].tag(), '<input type="radio" name="name" value="paul" id="id_name_1" required>', ) self.assertHTMLEqual( str(fields[1]), '<label for="id_name_1"><input type="radio" name="name" ' 'value="paul" id="id_name_1" required> Paul</label>', ) def test_iterable_boundfield_select(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ] ) fields = list(BeatleForm(auto_id=False)["name"]) self.assertEqual(len(fields), 4) self.assertIsNone(fields[0].id_for_label) self.assertEqual(fields[0].choice_label, "John") self.assertHTMLEqual(fields[0].tag(), '<option value="john">John</option>') self.assertHTMLEqual(str(fields[0]), '<option value="john">John</option>') def test_form_with_noniterable_boundfield(self): # You can iterate over any BoundField, not just those with widget=RadioSelect. class BeatleForm(Form): name = CharField() f = BeatleForm(auto_id=False) self.assertHTMLEqual( "\n".join(str(bf) for bf in f["name"]), '<input type="text" name="name" required>', ) def test_boundfield_slice(self): class BeatleForm(Form): name = ChoiceField( choices=[ ("john", "John"), ("paul", "Paul"), ("george", "George"), ("ringo", "Ringo"), ], widget=RadioSelect, ) f = BeatleForm() bf = f["name"] self.assertEqual( [str(item) for item in bf[1:]], [str(bf[1]), str(bf[2]), str(bf[3])], ) def test_boundfield_invalid_index(self): class TestForm(Form): name = ChoiceField(choices=[]) field = TestForm()["name"] msg = "BoundField indices must be integers or slices, not str." with self.assertRaisesMessage(TypeError, msg): field["foo"] def test_boundfield_bool(self): """BoundField without any choices (subwidgets) evaluates to True.""" class TestForm(Form): name = ChoiceField(choices=[]) self.assertIs(bool(TestForm()["name"]), True) def test_forms_with_multiple_choice(self): # MultipleChoiceField is a special case, as its data is required to be a list: class SongForm(Form): name = CharField() composers = MultipleChoiceField() f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> </select>""", ) class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")] ) f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P">Paul McCartney</option> </select>""", ) f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False) self.assertHTMLEqual( str(f["name"]), '<input type="text" name="name" value="Yesterday" required>' ) self.assertHTMLEqual( str(f["composers"]), """<select multiple name="composers" required> <option value="J">John Lennon</option> <option value="P" selected>Paul McCartney</option> </select>""", ) f = SongForm() self.assertHTMLEqual( f.as_table(), '<tr><th><label for="id_name">Name:</label></th>' '<td><input type="text" name="name" required id="id_name"></td>' '</tr><tr><th><label for="id_composers">Composers:</label></th>' '<td><select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></td></tr>", ) self.assertHTMLEqual( f.as_ul(), '<li><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></li>' '<li><label for="id_composers">Composers:</label>' '<select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></li>", ) self.assertHTMLEqual( f.as_p(), '<p><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></p>' '<p><label for="id_composers">Composers:</label>' '<select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option>' '<option value="P">Paul McCartney</option>' "</select></p>", ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><label for="id_composers">Composers:' '</label><select name="composers" required id="id_composers" multiple>' '<option value="J">John Lennon</option><option value="P">Paul McCartney' "</option></select></div>", ) def test_multiple_checkbox_render(self): f = SongForm() self.assertHTMLEqual( f.as_table(), '<tr><th><label for="id_name">Name:</label></th><td>' '<input type="text" name="name" required id="id_name"></td></tr>' '<tr><th><label>Composers:</label></th><td><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></td></tr>", ) self.assertHTMLEqual( f.as_ul(), '<li><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></li>' '<li><label>Composers:</label><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></li>", ) self.assertHTMLEqual( f.as_p(), '<p><label for="id_name">Name:</label>' '<input type="text" name="name" required id="id_name"></p>' '<p><label>Composers:</label><div id="id_composers">' '<div><label for="id_composers_0">' '<input type="checkbox" name="composers" value="J" ' 'id="id_composers_0">John Lennon</label></div>' '<div><label for="id_composers_1">' '<input type="checkbox" name="composers" value="P" ' 'id="id_composers_1">Paul McCartney</label></div>' "</div></p>", ) self.assertHTMLEqual( f.render(f.template_name_div), '<div><label for="id_name">Name:</label><input type="text" name="name" ' 'required id="id_name"></div><div><fieldset><legend>Composers:</legend>' '<div id="id_composers"><div><label for="id_composers_0"><input ' 'type="checkbox" name="composers" value="J" id="id_composers_0">' 'John Lennon</label></div><div><label for="id_composers_1"><input ' 'type="checkbox" name="composers" value="P" id="id_composers_1">' "Paul McCartney</label></div></div></fieldset></div>", ) def test_form_with_disabled_fields(self): class PersonForm(Form): name = CharField() birthday = DateField(disabled=True) class PersonFormFieldInitial(Form): name = CharField() birthday = DateField(disabled=True, initial=datetime.date(1974, 8, 16)) # Disabled fields are generally not transmitted by user agents. # The value from the form's initial data is used. f1 = PersonForm( {"name": "John Doe"}, initial={"birthday": datetime.date(1974, 8, 16)} ) f2 = PersonFormFieldInitial({"name": "John Doe"}) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {"birthday": datetime.date(1974, 8, 16), "name": "John Doe"}, ) # Values provided in the form's data are ignored. data = {"name": "John Doe", "birthday": "1984-11-10"} f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertTrue(form.is_valid()) self.assertEqual( form.cleaned_data, {"birthday": datetime.date(1974, 8, 16), "name": "John Doe"}, ) # Initial data remains present on invalid forms. data = {} f1 = PersonForm(data, initial={"birthday": datetime.date(1974, 8, 16)}) f2 = PersonFormFieldInitial(data) for form in (f1, f2): self.assertFalse(form.is_valid()) self.assertEqual(form["birthday"].value(), datetime.date(1974, 8, 16)) def test_hidden_data(self): class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")] ) # MultipleChoiceField rendered as_hidden() is a special case. Because it can # have multiple values, its as_hidden() renders multiple <input type="hidden"> # tags. f = SongForm({"name": "Yesterday", "composers": ["P"]}, auto_id=False) self.assertHTMLEqual( f["composers"].as_hidden(), '<input type="hidden" name="composers" value="P">', ) f = SongForm({"name": "From Me To You", "composers": ["P", "J"]}, auto_id=False) self.assertHTMLEqual( f["composers"].as_hidden(), """<input type="hidden" name="composers" value="P"> <input type="hidden" name="composers" value="J">""", ) # DateTimeField rendered as_hidden() is special too class MessageForm(Form): when = SplitDateTimeField() f = MessageForm({"when_0": "1992-01-01", "when_1": "01:01"}) self.assertTrue(f.is_valid()) self.assertHTMLEqual( str(f["when"]), '<input type="text" name="when_0" value="1992-01-01" id="id_when_0" ' "required>" '<input type="text" name="when_1" value="01:01" id="id_when_1" required>', ) self.assertHTMLEqual( f["when"].as_hidden(), '<input type="hidden" name="when_0" value="1992-01-01" id="id_when_0">' '<input type="hidden" name="when_1" value="01:01" id="id_when_1">', ) def test_multiple_choice_checkbox(self): # MultipleChoiceField can also be used with the CheckboxSelectMultiple widget. f = SongForm(auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) f = SongForm({"composers": ["J"]}, auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) f = SongForm({"composers": ["J", "P"]}, auto_id=False) self.assertHTMLEqual( str(f["composers"]), """ <div> <div><label><input checked type="checkbox" name="composers" value="J"> John Lennon</label></div> <div><label><input checked type="checkbox" name="composers" value="P"> Paul McCartney</label></div> </div> """, ) def test_checkbox_auto_id(self): # Regarding auto_id, CheckboxSelectMultiple is a special case. Each checkbox # gets a distinct ID, formed by appending an underscore plus the checkbox's # zero-based index. class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) f = SongForm(auto_id="%s_id") self.assertHTMLEqual( str(f["composers"]), """ <div id="composers_id"> <div><label for="composers_id_0"> <input type="checkbox" name="composers" value="J" id="composers_id_0"> John Lennon</label></div> <div><label for="composers_id_1"> <input type="checkbox" name="composers" value="P" id="composers_id_1"> Paul McCartney</label></div> </div> """, ) def test_multiple_choice_list_data(self): # Data for a MultipleChoiceField should be a list. QueryDict and # MultiValueDict conveniently work with this. class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) data = {"name": "Yesterday", "composers": ["J", "P"]} f = SongForm(data) self.assertEqual(f.errors, {}) data = QueryDict("name=Yesterday&composers=J&composers=P") f = SongForm(data) self.assertEqual(f.errors, {}) data = MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]}) f = SongForm(data) self.assertEqual(f.errors, {}) # SelectMultiple uses ducktyping so that MultiValueDictLike.getlist() # is called. f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) def test_multiple_hidden(self): class SongForm(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=CheckboxSelectMultiple, ) # The MultipleHiddenInput widget renders multiple values as hidden fields. class SongFormHidden(Form): name = CharField() composers = MultipleChoiceField( choices=[("J", "John Lennon"), ("P", "Paul McCartney")], widget=MultipleHiddenInput, ) f = SongFormHidden( MultiValueDict({"name": ["Yesterday"], "composers": ["J", "P"]}), auto_id=False, ) self.assertHTMLEqual( f.as_ul(), """<li>Name: <input type="text" name="name" value="Yesterday" required> <input type="hidden" name="composers" value="J"> <input type="hidden" name="composers" value="P"></li>""", ) # When using CheckboxSelectMultiple, the framework expects a list of input and # returns a list of input. f = SongForm({"name": "Yesterday"}, auto_id=False) self.assertEqual(f.errors["composers"], ["This field is required."]) f = SongForm({"name": "Yesterday", "composers": ["J"]}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) self.assertEqual(f.cleaned_data["name"], "Yesterday") f = SongForm({"name": "Yesterday", "composers": ["J", "P"]}, auto_id=False) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J", "P"]) self.assertEqual(f.cleaned_data["name"], "Yesterday") # MultipleHiddenInput uses ducktyping so that # MultiValueDictLike.getlist() is called. f = SongForm(MultiValueDictLike({"name": "Yesterday", "composers": "J"})) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["composers"], ["J"]) def test_escaping(self): # Validation errors are HTML-escaped when output as HTML. class EscapingForm(Form): special_name = CharField(label="<em>Special</em> Field") special_safe_name = CharField(label=mark_safe("<em>Special</em> Field")) def clean_special_name(self): raise ValidationError( "Something's wrong with '%s'" % self.cleaned_data["special_name"] ) def clean_special_safe_name(self): raise ValidationError( mark_safe( "'<b>%s</b>' is a safe string" % self.cleaned_data["special_safe_name"] ) ) f = EscapingForm( { "special_name": "Nothing to escape", "special_safe_name": "Nothing to escape", }, auto_id=False, ) self.assertHTMLEqual( f.as_table(), """ <tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td> <ul class="errorlist"> <li>Something&#x27;s wrong with &#x27;Nothing to escape&#x27;</li></ul> <input type="text" name="special_name" value="Nothing to escape" required> </td></tr> <tr><th><em>Special</em> Field:</th><td> <ul class="errorlist"> <li>'<b>Nothing to escape</b>' is a safe string</li></ul> <input type="text" name="special_safe_name" value="Nothing to escape" required></td></tr> """, ) f = EscapingForm( { "special_name": "Should escape < & > and <script>alert('xss')</script>", "special_safe_name": "<i>Do not escape</i>", }, auto_id=False, ) self.assertHTMLEqual( f.as_table(), "<tr><th>&lt;em&gt;Special&lt;/em&gt; Field:</th><td>" '<ul class="errorlist"><li>' "Something&#x27;s wrong with &#x27;Should escape &lt; &amp; &gt; and " "&lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;&#x27;</li></ul>" '<input type="text" name="special_name" value="Should escape &lt; &amp; ' '&gt; and &lt;script&gt;alert(&#x27;xss&#x27;)&lt;/script&gt;" required>' "</td></tr>" "<tr><th><em>Special</em> Field:</th><td>" '<ul class="errorlist">' "<li>'<b><i>Do not escape</i></b>' is a safe string</li></ul>" '<input type="text" name="special_safe_name" ' 'value="&lt;i&gt;Do not escape&lt;/i&gt;" required></td></tr>', ) def test_validating_multiple_fields(self): # There are a couple of ways to do multiple-field validation. If you # want the validation message to be associated with a particular field, # implement the clean_XXX() method on the Form, where XXX is the field # name. As in Field.clean(), the clean_XXX() method should return the # cleaned value. In the clean_XXX() method, you have access to # self.cleaned_data, which is a dictionary of all the data that has # been cleaned *so far*, in order by the fields, including the current # field (e.g., the field XXX if you're in clean_XXX()). class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean_password2(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data["password2"] f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertEqual(f.errors["username"], ["This field is required."]) self.assertEqual(f.errors["password1"], ["This field is required."]) self.assertEqual(f.errors["password2"], ["This field is required."]) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "bar"}, auto_id=False, ) self.assertEqual( f.errors["password2"], ["Please make sure your passwords match."] ) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "foo"}, auto_id=False, ) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["username"], "adrian") self.assertEqual(f.cleaned_data["password1"], "foo") self.assertEqual(f.cleaned_data["password2"], "foo") # Another way of doing multiple-field validation is by implementing the # Form's clean() method. Usually ValidationError raised by that method # will not be associated with a particular field and will have a # special-case association with the field named '__all__'. It's # possible to associate the errors to particular field with the # Form.add_error() method or by passing a dictionary that maps each # field to one or more errors. # # Note that in Form.clean(), you have access to self.cleaned_data, a # dictionary of all the fields/values that have *not* raised a # ValidationError. Also note Form.clean() is required to return a # dictionary of all clean data. class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): # Test raising a ValidationError as NON_FIELD_ERRORS. if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") # Test raising ValidationError that targets multiple fields. errors = {} if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE": errors["password1"] = "Forbidden value." if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE": errors["password2"] = ["Forbidden value."] if errors: raise ValidationError(errors) # Test Form.add_error() if self.cleaned_data.get("password1") == "FORBIDDEN_VALUE2": self.add_error(None, "Non-field error 1.") self.add_error("password1", "Forbidden value 2.") if self.cleaned_data.get("password2") == "FORBIDDEN_VALUE2": self.add_error("password2", "Forbidden value 2.") raise ValidationError("Non-field error 2.") return self.cleaned_data f = UserRegistration(auto_id=False) self.assertEqual(f.errors, {}) f = UserRegistration({}, auto_id=False) self.assertHTMLEqual( f.as_table(), """<tr><th>Username:</th><td> <ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="username" maxlength="10" required></td></tr> <tr><th>Password1:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td><ul class="errorlist"><li>This field is required.</li></ul> <input type="password" name="password2" required></td></tr>""", ) self.assertEqual(f.errors["username"], ["This field is required."]) self.assertEqual(f.errors["password1"], ["This field is required."]) self.assertEqual(f.errors["password2"], ["This field is required."]) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "bar"}, auto_id=False, ) self.assertEqual( f.errors["__all__"], ["Please make sure your passwords match."] ) self.assertHTMLEqual( f.as_table(), """ <tr><td colspan="2"> <ul class="errorlist nonfield"> <li>Please make sure your passwords match.</li></ul></td></tr> <tr><th>Username:</th><td> <input type="text" name="username" value="adrian" maxlength="10" required> </td></tr> <tr><th>Password1:</th><td> <input type="password" name="password1" required></td></tr> <tr><th>Password2:</th><td> <input type="password" name="password2" required></td></tr> """, ) self.assertHTMLEqual( f.as_ul(), """ <li><ul class="errorlist nonfield"> <li>Please make sure your passwords match.</li></ul></li> <li>Username: <input type="text" name="username" value="adrian" maxlength="10" required> </li> <li>Password1: <input type="password" name="password1" required></li> <li>Password2: <input type="password" name="password2" required></li> """, ) self.assertHTMLEqual( f.render(f.template_name_div), '<ul class="errorlist nonfield"><li>Please make sure your passwords match.' '</li></ul><div>Username: <input type="text" name="username" ' 'value="adrian" maxlength="10" required></div><div>Password1: <input ' 'type="password" name="password1" required></div><div>Password2: <input ' 'type="password" name="password2" required></div>', ) f = UserRegistration( {"username": "adrian", "password1": "foo", "password2": "foo"}, auto_id=False, ) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["username"], "adrian") self.assertEqual(f.cleaned_data["password1"], "foo") self.assertEqual(f.cleaned_data["password2"], "foo") f = UserRegistration( { "username": "adrian", "password1": "FORBIDDEN_VALUE", "password2": "FORBIDDEN_VALUE", }, auto_id=False, ) self.assertEqual(f.errors["password1"], ["Forbidden value."]) self.assertEqual(f.errors["password2"], ["Forbidden value."]) f = UserRegistration( { "username": "adrian", "password1": "FORBIDDEN_VALUE2", "password2": "FORBIDDEN_VALUE2", }, auto_id=False, ) self.assertEqual( f.errors["__all__"], ["Non-field error 1.", "Non-field error 2."] ) self.assertEqual(f.errors["password1"], ["Forbidden value 2."]) self.assertEqual(f.errors["password2"], ["Forbidden value 2."]) with self.assertRaisesMessage(ValueError, "has no field named"): f.add_error("missing_field", "Some error.") def test_update_error_dict(self): class CodeForm(Form): code = CharField(max_length=10) def clean(self): try: raise ValidationError({"code": [ValidationError("Code error 1.")]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({"code": [ValidationError("Code error 2.")]}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError({"code": forms.ErrorList(["Code error 3."])}) except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError("Non-field error 1.") except ValidationError as e: self._errors = e.update_error_dict(self._errors) try: raise ValidationError([ValidationError("Non-field error 2.")]) except ValidationError as e: self._errors = e.update_error_dict(self._errors) # The newly added list of errors is an instance of ErrorList. for field, error_list in self._errors.items(): if not isinstance(error_list, self.error_class): self._errors[field] = self.error_class(error_list) form = CodeForm({"code": "hello"}) # Trigger validation. self.assertFalse(form.is_valid()) # update_error_dict didn't lose track of the ErrorDict type. self.assertIsInstance(form._errors, forms.ErrorDict) self.assertEqual( dict(form.errors), { "code": ["Code error 1.", "Code error 2.", "Code error 3."], NON_FIELD_ERRORS: ["Non-field error 1.", "Non-field error 2."], }, ) def test_has_error(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput, min_length=5) password2 = CharField(widget=PasswordInput) def clean(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError( "Please make sure your passwords match.", code="password_mismatch", ) f = UserRegistration(data={}) self.assertTrue(f.has_error("password1")) self.assertTrue(f.has_error("password1", "required")) self.assertFalse(f.has_error("password1", "anything")) f = UserRegistration(data={"password1": "Hi", "password2": "Hi"}) self.assertTrue(f.has_error("password1")) self.assertTrue(f.has_error("password1", "min_length")) self.assertFalse(f.has_error("password1", "anything")) self.assertFalse(f.has_error("password2")) self.assertFalse(f.has_error("password2", "anything")) f = UserRegistration(data={"password1": "Bonjour", "password2": "Hello"}) self.assertFalse(f.has_error("password1")) self.assertFalse(f.has_error("password1", "required")) self.assertTrue(f.has_error(NON_FIELD_ERRORS)) self.assertTrue(f.has_error(NON_FIELD_ERRORS, "password_mismatch")) self.assertFalse(f.has_error(NON_FIELD_ERRORS, "anything")) def test_html_output_with_hidden_input_field_errors(self): class TestForm(Form): hidden_input = CharField(widget=HiddenInput) def clean(self): self.add_error(None, "Form error") f = TestForm(data={}) error_dict = { "hidden_input": ["This field is required."], "__all__": ["Form error"], } self.assertEqual(f.errors, error_dict) f.as_table() self.assertEqual(f.errors, error_dict) self.assertHTMLEqual( f.as_table(), '<tr><td colspan="2"><ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<input type="hidden" name="hidden_input" id="id_hidden_input"></td></tr>', ) self.assertHTMLEqual( f.as_ul(), '<li><ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<input type="hidden" name="hidden_input" id="id_hidden_input"></li>', ) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<p><input type="hidden" name="hidden_input" id="id_hidden_input"></p>', ) self.assertHTMLEqual( f.render(f.template_name_div), '<ul class="errorlist nonfield"><li>Form error</li>' "<li>(Hidden field hidden_input) This field is required.</li></ul>" '<div><input type="hidden" name="hidden_input" id="id_hidden_input"></div>', ) def test_dynamic_construction(self): # It's possible to construct a Form dynamically by adding to the self.fields # dictionary in __init__(). Don't forget to call Form.__init__() within the # subclass' __init__(). class Person(Form): first_name = CharField() last_name = CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["birthday"] = DateField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), """ <tr><th>First name:</th><td> <input type="text" name="first_name" required></td></tr> <tr><th>Last name:</th><td> <input type="text" name="last_name" required></td></tr> <tr><th>Birthday:</th><td> <input type="text" name="birthday" required></td></tr> """, ) # Instances of a dynamic Form do not persist fields from one Form instance to # the next. class MyForm(Form): def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [("field1", CharField()), ("field2", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr> """, ) field_list = [("field3", CharField()), ("field4", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr> """, ) class MyForm(Form): default_field_1 = CharField() default_field_2 = CharField() def __init__(self, data=None, auto_id=False, field_list=[]): Form.__init__(self, data, auto_id=auto_id) for field in field_list: self.fields[field[0]] = field[1] field_list = [("field1", CharField()), ("field2", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Default field 1:</th><td> <input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td> <input type="text" name="default_field_2" required></td></tr> <tr><th>Field1:</th><td><input type="text" name="field1" required></td></tr> <tr><th>Field2:</th><td><input type="text" name="field2" required></td></tr> """, ) field_list = [("field3", CharField()), ("field4", CharField())] my_form = MyForm(field_list=field_list) self.assertHTMLEqual( my_form.as_table(), """ <tr><th>Default field 1:</th><td> <input type="text" name="default_field_1" required></td></tr> <tr><th>Default field 2:</th><td> <input type="text" name="default_field_2" required></td></tr> <tr><th>Field3:</th><td><input type="text" name="field3" required></td></tr> <tr><th>Field4:</th><td><input type="text" name="field4" required></td></tr> """, ) # Similarly, changes to field attributes do not persist from one Form instance # to the next. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) def __init__(self, names_required=False, *args, **kwargs): super().__init__(*args, **kwargs) if names_required: self.fields["first_name"].required = True self.fields["first_name"].widget.attrs["class"] = "required" self.fields["last_name"].required = True self.fields["last_name"].widget.attrs["class"] = "required" f = Person(names_required=False) self.assertEqual( f["first_name"].field.required, f["last_name"].field.required, (False, False), ) self.assertEqual( f["first_name"].field.widget.attrs, f["last_name"].field.widget.attrs, ({}, {}), ) f = Person(names_required=True) self.assertEqual( f["first_name"].field.required, f["last_name"].field.required, (True, True) ) self.assertEqual( f["first_name"].field.widget.attrs, f["last_name"].field.widget.attrs, ({"class": "reuired"}, {"class": "required"}), ) f = Person(names_required=False) self.assertEqual( f["first_name"].field.required, f["last_name"].field.required, (False, False), ) self.assertEqual( f["first_name"].field.widget.attrs, f["last_name"].field.widget.attrs, ({}, {}), ) class Person(Form): first_name = CharField(max_length=30) last_name = CharField(max_length=30) def __init__(self, name_max_length=None, *args, **kwargs): super().__init__(*args, **kwargs) if name_max_length: self.fields["first_name"].max_length = name_max_length self.fields["last_name"].max_length = name_max_length f = Person(name_max_length=None) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30) ) f = Person(name_max_length=20) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (20, 20) ) f = Person(name_max_length=None) self.assertEqual( f["first_name"].field.max_length, f["last_name"].field.max_length, (30, 30) ) # Similarly, choices do not persist from one Form instance to the next. # Refs #15127. class Person(Form): first_name = CharField(required=False) last_name = CharField(required=False) gender = ChoiceField(choices=(("f", "Female"), ("m", "Male"))) def __init__(self, allow_unspec_gender=False, *args, **kwargs): super().__init__(*args, **kwargs) if allow_unspec_gender: self.fields["gender"].choices += (("u", "Unspecified"),) f = Person() self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")]) f = Person(allow_unspec_gender=True) self.assertEqual( f["gender"].field.choices, [("f", "Female"), ("m", "Male"), ("u", "Unspecified")], ) f = Person() self.assertEqual(f["gender"].field.choices, [("f", "Female"), ("m", "Male")]) def test_validators_independence(self): """ The list of form field validators can be modified without polluting other forms. """ class MyForm(Form): myfield = CharField(max_length=25) f1 = MyForm() f2 = MyForm() f1.fields["myfield"].validators[0] = MaxValueValidator(12) self.assertNotEqual( f1.fields["myfield"].validators[0], f2.fields["myfield"].validators[0] ) def test_hidden_widget(self): # HiddenInput widgets are displayed differently in the as_table(), as_ul()) # and as_p() output of a Form -- their verbose names are not displayed, and a # separate row is not displayed. They're displayed in the last row of the # form, directly after that row's form element. class Person(Form): first_name = CharField() last_name = CharField() hidden_text = CharField(widget=HiddenInput) birthday = DateField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_table(), """ <tr><th>First name:</th><td><input type="text" name="first_name" required> </td></tr> <tr><th>Last name:</th><td><input type="text" name="last_name" required> </td></tr> <tr><th>Birthday:</th> <td><input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></td></tr> """, ) self.assertHTMLEqual( p.as_ul(), """ <li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></li> """, ) self.assertHTMLEqual( p.as_p(), """ <p>First name: <input type="text" name="first_name" required></p> <p>Last name: <input type="text" name="last_name" required></p> <p>Birthday: <input type="text" name="birthday" required> <input type="hidden" name="hidden_text"></p> """, ) self.assertHTMLEqual( p.as_div(), '<div>First name: <input type="text" name="first_name" required></div>' '<div>Last name: <input type="text" name="last_name" required></div><div>' 'Birthday: <input type="text" name="birthday" required><input ' 'type="hidden" name="hidden_text"></div>', ) # With auto_id set, a HiddenInput still gets an ID, but it doesn't get a label. p = Person(auto_id="id_%s") self.assertHTMLEqual( p.as_table(), """<tr><th><label for="id_first_name">First name:</label></th><td> <input type="text" name="first_name" id="id_first_name" required></td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input type="text" name="last_name" id="id_last_name" required></td></tr> <tr><th><label for="id_birthday">Birthday:</label></th><td> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></td></tr>""", ) self.assertHTMLEqual( p.as_ul(), """<li><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></li> <li><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></li> <li><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></li>""", ) self.assertHTMLEqual( p.as_p(), """<p><label for="id_first_name">First name:</label> <input type="text" name="first_name" id="id_first_name" required></p> <p><label for="id_last_name">Last name:</label> <input type="text" name="last_name" id="id_last_name" required></p> <p><label for="id_birthday">Birthday:</label> <input type="text" name="birthday" id="id_birthday" required> <input type="hidden" name="hidden_text" id="id_hidden_text"></p>""", ) self.assertHTMLEqual( p.as_div(), '<div><label for="id_first_name">First name:</label><input type="text" ' 'name="first_name" id="id_first_name" required></div><div><label ' 'for="id_last_name">Last name:</label><input type="text" name="last_name" ' 'id="id_last_name" required></div><div><label for="id_birthday">Birthday:' '</label><input type="text" name="birthday" id="id_birthday" required>' '<input type="hidden" name="hidden_text" id="id_hidden_text"></div>', ) # If a field with a HiddenInput has errors, the as_table() and as_ul() output # will include the error message(s) with the text "(Hidden field [fieldname]) " # prepended. This message is displayed at the top of the output, regardless of # its field's order in the form. p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"}, auto_id=False, ) self.assertHTMLEqual( p.as_table(), """ <tr><td colspan="2"> <ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul></td></tr> <tr><th>First name:</th><td> <input type="text" name="first_name" value="John" required></td></tr> <tr><th>Last name:</th><td> <input type="text" name="last_name" value="Lennon" required></td></tr> <tr><th>Birthday:</th><td> <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></td></tr> """, ) self.assertHTMLEqual( p.as_ul(), """ <li><ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul></li> <li>First name: <input type="text" name="first_name" value="John" required> </li> <li>Last name: <input type="text" name="last_name" value="Lennon" required> </li> <li>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></li> """, ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist nonfield"><li> (Hidden field hidden_text) This field is required.</li></ul> <p>First name: <input type="text" name="first_name" value="John" required> </p> <p>Last name: <input type="text" name="last_name" value="Lennon" required> </p> <p>Birthday: <input type="text" name="birthday" value="1940-10-9" required> <input type="hidden" name="hidden_text"></p> """, ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>(Hidden field hidden_text) This field ' 'is required.</li></ul><div>First name: <input type="text" ' 'name="first_name" value="John" required></div><div>Last name: <input ' 'type="text" name="last_name" value="Lennon" required></div><div>' 'Birthday: <input type="text" name="birthday" value="1940-10-9" required>' '<input type="hidden" name="hidden_text"></div>', ) # A corner case: It's possible for a form to have only HiddenInputs. class TestForm(Form): foo = CharField(widget=HiddenInput) bar = CharField(widget=HiddenInput) p = TestForm(auto_id=False) self.assertHTMLEqual( p.as_table(), '<input type="hidden" name="foo"><input type="hidden" name="bar">', ) self.assertHTMLEqual( p.as_ul(), '<input type="hidden" name="foo"><input type="hidden" name="bar">', ) self.assertHTMLEqual( p.as_p(), '<input type="hidden" name="foo"><input type="hidden" name="bar">' ) def test_field_order(self): # A Form's fields are displayed in the same order in which they were defined. class TestForm(Form): field1 = CharField() field2 = CharField() field3 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field7 = CharField() field8 = CharField() field9 = CharField() field10 = CharField() field11 = CharField() field12 = CharField() field13 = CharField() field14 = CharField() p = TestForm(auto_id=False) self.assertHTMLEqual( p.as_table(), "".join( f"<tr><th>Field{i}:</th><td>" f'<input type="text" name="field{i}" required></td></tr>' for i in range(1, 15) ), ) def test_explicit_field_order(self): class TestFormParent(Form): field1 = CharField() field2 = CharField() field4 = CharField() field5 = CharField() field6 = CharField() field_order = ["field6", "field5", "field4", "field2", "field1"] class TestForm(TestFormParent): field3 = CharField() field_order = ["field2", "field4", "field3", "field5", "field6"] class TestFormRemove(TestForm): field1 = None class TestFormMissing(TestForm): field_order = ["field2", "field4", "field3", "field5", "field6", "field1"] field1 = None class TestFormInit(TestFormParent): field3 = CharField() field_order = None def __init__(self, **kwargs): super().__init__(**kwargs) self.order_fields(field_order=TestForm.field_order) p = TestFormParent() self.assertEqual(list(p.fields), TestFormParent.field_order) p = TestFormRemove() self.assertEqual(list(p.fields), TestForm.field_order) p = TestFormMissing() self.assertEqual(list(p.fields), TestForm.field_order) p = TestForm() self.assertEqual(list(p.fields), TestFormMissing.field_order) p = TestFormInit() order = [*TestForm.field_order, "field1"] self.assertEqual(list(p.fields), order) TestForm.field_order = ["unknown"] p = TestForm() self.assertEqual( list(p.fields), ["field1", "field2", "field4", "field5", "field6", "field3"] ) def test_form_html_attributes(self): # Some Field classes have an effect on the HTML attributes of their associated # Widget. If you set max_length in a CharField and its associated widget is # either a TextInput or PasswordInput, then the widget's rendered HTML will # include the "maxlength" attribute. class UserRegistration(Form): username = CharField(max_length=10) # uses TextInput by default password = CharField(max_length=10, widget=PasswordInput) realname = CharField( max_length=10, widget=TextInput ) # redundantly define widget, just to test address = CharField() # no max_length defined here p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" maxlength="10" required> </li> <li>Password: <input type="password" name="password" maxlength="10" required></li> <li>Realname: <input type="text" name="realname" maxlength="10" required> </li> <li>Address: <input type="text" name="address" required></li> """, ) # If you specify a custom "attrs" that includes the "maxlength" # attribute, the Field's max_length attribute will override whatever # "maxlength" you specify in "attrs". class UserRegistration(Form): username = CharField( max_length=10, widget=TextInput(attrs={"maxlength": 20}) ) password = CharField(max_length=10, widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" maxlength="10" required></li>""", ) def test_specifying_labels(self): # You can specify the label for a field by using the 'label' argument to a Field # class. If you don't specify 'label', Django will use the field name with # underscores converted to spaces, and the initial letter capitalized. class UserRegistration(Form): username = CharField(max_length=10, label="Your username") password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput, label="Contraseña (de nuevo)") p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Your username: <input type="text" name="username" maxlength="10" required></li> <li>Password1: <input type="password" name="password1" required></li> <li>Contraseña (de nuevo): <input type="password" name="password2" required></li> """, ) # Labels for as_* methods will only end in a colon if they don't end in other # punctuation already. class Questions(Form): q1 = CharField(label="The first question") q2 = CharField(label="What is your name?") q3 = CharField(label="The answer to life is:") q4 = CharField(label="Answer this question!") q5 = CharField(label="The last question. Period.") self.assertHTMLEqual( Questions(auto_id=False).as_p(), """<p>The first question: <input type="text" name="q1" required></p> <p>What is your name? <input type="text" name="q2" required></p> <p>The answer to life is: <input type="text" name="q3" required></p> <p>Answer this question! <input type="text" name="q4" required></p> <p>The last question. Period. <input type="text" name="q5" required></p>""", ) self.assertHTMLEqual( Questions().as_p(), """ <p><label for="id_q1">The first question:</label> <input type="text" name="q1" id="id_q1" required></p> <p><label for="id_q2">What is your name?</label> <input type="text" name="q2" id="id_q2" required></p> <p><label for="id_q3">The answer to life is:</label> <input type="text" name="q3" id="id_q3" required></p> <p><label for="id_q4">Answer this question!</label> <input type="text" name="q4" id="id_q4" required></p> <p><label for="id_q5">The last question. Period.</label> <input type="text" name="q5" id="id_q5" required></p> """, ) # If a label is set to the empty string for a field, that field won't # get a label. class UserRegistration(Form): username = CharField(max_length=10, label="") password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li> <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""", ) p = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( p.as_ul(), """ <li> <input id="id_username" type="text" name="username" maxlength="10" required> </li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></li> """, ) # If label is None, Django will auto-create the label from the field name. This # is default behavior. class UserRegistration(Form): username = CharField(max_length=10, label=None) password = CharField(widget=PasswordInput) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li>""", ) p = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( p.as_ul(), """<li><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="10" required></li> <li><label for="id_password">Password:</label> <input type="password" name="password" id="id_password" required></li>""", ) def test_label_suffix(self): # You can specify the 'label_suffix' argument to a Form class to modify # the punctuation symbol used at the end of a label. By default, the # colon (:) is used, and is only appended to the label if the label # doesn't already end with a punctuation symbol: ., !, ? or :. If you # specify a different suffix, it will be appended regardless of the # last character of the label. class FavoriteForm(Form): color = CharField(label="Favorite color?") animal = CharField(label="Favorite animal") answer = CharField(label="Secret answer", label_suffix=" =") f = FavoriteForm(auto_id=False) self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal: <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="?") self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal? <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="") self.assertHTMLEqual( f.as_ul(), """<li>Favorite color? <input type="text" name="color" required></li> <li>Favorite animal <input type="text" name="animal" required></li> <li>Secret answer = <input type="text" name="answer" required></li>""", ) f = FavoriteForm(auto_id=False, label_suffix="\u2192") self.assertHTMLEqual( f.as_ul(), '<li>Favorite color? <input type="text" name="color" required></li>\n' "<li>Favorite animal\u2192 " '<input type="text" name="animal" required></li>\n' '<li>Secret answer = <input type="text" name="answer" required></li>', ) def test_initial_data(self): # You can specify initial data for a field by using the 'initial' argument to a # Field class. This initial data is displayed when a Form is rendered with *no* # data. It is not displayed when a Form is rendered with any data (including an # empty dictionary). Also, the initial value is *not* used if data for a # particular required field isn't provided. class UserRegistration(Form): username = CharField(max_length=10, initial="django") password = CharField(widget=PasswordInput) # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) # Here, we're submitting data, so the initial value will *not* be displayed. p = UserRegistration({}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration({"username": ""}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration({"username": "foo"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> """, ) # An 'initial' value is *not* used as a fallback if data is not # provided. In this example, we don't provide a value for 'username', # and the form raises a validation error rather than using the initial # value for 'username'. p = UserRegistration({"password": "secret"}) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) def test_dynamic_initial_data(self): # The previous technique dealt with "hard-coded" initial data, but it's also # possible to specify initial data after you've already created the Form class # (i.e., at runtime). Use the 'initial' parameter to the Form constructor. This # should be a dictionary containing initial values for one or more fields in the # form, keyed by field name. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration(initial={"username": "django"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) p = UserRegistration(initial={"username": "stephane"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration({}, initial={"username": "django"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration( {"username": ""}, initial={"username": "django"}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li>""", ) p = UserRegistration( {"username": "foo"}, initial={"username": "django"}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> """, ) # A dynamic 'initial' value is *not* used as a fallback if data is not provided. # In this example, we don't provide a value for 'username', and the # form raises a validation error rather than using the initial value # for 'username'. p = UserRegistration({"password": "secret"}, initial={"username": "django"}) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter # to Form(), then the latter will get precedence. class UserRegistration(Form): username = CharField(max_length=10, initial="django") password = CharField(widget=PasswordInput) p = UserRegistration(initial={"username": "babik"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="babik" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> """, ) def test_callable_initial_data(self): # The previous technique dealt with raw values as initial data, but it's also # possible to specify callable data. class UserRegistration(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) options = MultipleChoiceField( choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")] ) # We need to define functions that get called later.) def initial_django(): return "django" def initial_stephane(): return "stephane" def initial_options(): return ["f", "b"] def initial_other_options(): return ["b", "w"] # Here, we're not submitting any data, so the initial value will be displayed.) p = UserRegistration( initial={"username": initial_django, "options": initial_options}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) # The 'initial' parameter is meaningless if you pass data. p = UserRegistration( {}, initial={"username": initial_django, "options": initial_options}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""", ) p = UserRegistration( {"username": ""}, initial={"username": initial_django}, auto_id=False ) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist"><li>This field is required.</li></ul> Username: <input type="text" name="username" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b">bar</option> <option value="w">whiz</option> </select></li>""", ) p = UserRegistration( {"username": "foo", "options": ["f", "b"]}, initial={"username": initial_django}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="foo" maxlength="10" required></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) # A callable 'initial' value is *not* used as a fallback if data is not # provided. In this example, we don't provide a value for 'username', # and the form raises a validation error rather than using the initial # value for 'username'. p = UserRegistration( {"password": "secret"}, initial={"username": initial_django, "options": initial_options}, ) self.assertEqual(p.errors["username"], ["This field is required."]) self.assertFalse(p.is_valid()) # If a Form defines 'initial' *and* 'initial' is passed as a parameter # to Form(), then the latter will get precedence. class UserRegistration(Form): username = CharField(max_length=10, initial=initial_django) password = CharField(widget=PasswordInput) options = MultipleChoiceField( choices=[("f", "foo"), ("b", "bar"), ("w", "whiz")], initial=initial_other_options, ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="django" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f">foo</option> <option value="b" selected>bar</option> <option value="w" selected>whiz</option> </select></li> """, ) p = UserRegistration( initial={"username": initial_stephane, "options": initial_options}, auto_id=False, ) self.assertHTMLEqual( p.as_ul(), """ <li>Username: <input type="text" name="username" value="stephane" maxlength="10" required></li> <li>Password: <input type="password" name="password" required></li> <li>Options: <select multiple name="options" required> <option value="f" selected>foo</option> <option value="b" selected>bar</option> <option value="w">whiz</option> </select></li> """, ) def test_get_initial_for_field(self): now = datetime.datetime(2006, 10, 25, 14, 30, 45, 123456) class PersonForm(Form): first_name = CharField(initial="John") last_name = CharField(initial="Doe") age = IntegerField() occupation = CharField(initial=lambda: "Unknown") dt_fixed = DateTimeField(initial=now) dt_callable = DateTimeField(initial=lambda: now) form = PersonForm(initial={"first_name": "Jane"}) cases = [ ("age", None), ("last_name", "Doe"), # Form.initial overrides Field.initial. ("first_name", "Jane"), # Callables are evaluated. ("occupation", "Unknown"), # Microseconds are removed from datetimes. ("dt_fixed", datetime.datetime(2006, 10, 25, 14, 30, 45)), ("dt_callable", datetime.datetime(2006, 10, 25, 14, 30, 45)), ] for field_name, expected in cases: with self.subTest(field_name=field_name): field = form.fields[field_name] actual = form.get_initial_for_field(field, field_name) self.assertEqual(actual, expected) def test_changed_data(self): class Person(Form): first_name = CharField(initial="Hans") last_name = CharField(initial="Greatel") birthday = DateField(initial=datetime.date(1974, 8, 16)) p = Person( data={"first_name": "Hans", "last_name": "Scrmbl", "birthday": "1974-08-16"} ) self.assertTrue(p.is_valid()) self.assertNotIn("first_name", p.changed_data) self.assertIn("last_name", p.changed_data) self.assertNotIn("birthday", p.changed_data) # A field raising ValidationError is always in changed_data class PedanticField(forms.Field): def to_python(self, value): raise ValidationError("Whatever") class Person2(Person): pedantic = PedanticField(initial="whatever", show_hidden_initial=True) p = Person2( data={ "first_name": "Hans", "last_name": "Scrmbl", "birthday": "1974-08-16", "initial-pedantic": "whatever", } ) self.assertFalse(p.is_valid()) self.assertIn("pedantic", p.changed_data) def test_boundfield_values(self): # It's possible to get to the value which would be used for rendering # the widget for a field by using the BoundField's value method. class UserRegistration(Form): username = CharField(max_length=10, initial="djangonaut") password = CharField(widget=PasswordInput) unbound = UserRegistration() bound = UserRegistration({"password": "foo"}) self.assertIsNone(bound["username"].value()) self.assertEqual(unbound["username"].value(), "djangonaut") self.assertEqual(bound["password"].value(), "foo") self.assertIsNone(unbound["password"].value()) def test_boundfield_initial_called_once(self): """ Multiple calls to BoundField().value() in an unbound form should return the same result each time (#24391). """ class MyForm(Form): name = CharField(max_length=10, initial=uuid.uuid4) form = MyForm() name = form["name"] self.assertEqual(name.value(), name.value()) # BoundField is also cached self.assertIs(form["name"], name) def test_boundfield_value_disabled_callable_initial(self): class PersonForm(Form): name = CharField(initial=lambda: "John Doe", disabled=True) # Without form data. form = PersonForm() self.assertEqual(form["name"].value(), "John Doe") # With form data. As the field is disabled, the value should not be # affected by the form data. form = PersonForm({}) self.assertEqual(form["name"].value(), "John Doe") def test_custom_boundfield(self): class CustomField(CharField): def get_bound_field(self, form, name): return (form, name) class SampleForm(Form): name = CustomField() f = SampleForm() self.assertEqual(f["name"], (f, "name")) def test_initial_datetime_values(self): now = datetime.datetime.now() # Nix microseconds (since they should be ignored). #22502 now_no_ms = now.replace(microsecond=0) if now == now_no_ms: now = now.replace(microsecond=1) def delayed_now(): return now def delayed_now_time(): return now.time() class HiddenInputWithoutMicrosec(HiddenInput): supports_microseconds = False class TextInputWithoutMicrosec(TextInput): supports_microseconds = False class DateTimeForm(Form): # Test a non-callable. fixed = DateTimeField(initial=now) auto_timestamp = DateTimeField(initial=delayed_now) auto_time_only = TimeField(initial=delayed_now_time) supports_microseconds = DateTimeField(initial=delayed_now, widget=TextInput) hi_default_microsec = DateTimeField(initial=delayed_now, widget=HiddenInput) hi_without_microsec = DateTimeField( initial=delayed_now, widget=HiddenInputWithoutMicrosec ) ti_without_microsec = DateTimeField( initial=delayed_now, widget=TextInputWithoutMicrosec ) unbound = DateTimeForm() cases = [ ("fixed", now_no_ms), ("auto_timestamp", now_no_ms), ("auto_time_only", now_no_ms.time()), ("supports_microseconds", now), ("hi_default_microsec", now), ("hi_without_microsec", now_no_ms), ("ti_without_microsec", now_no_ms), ] for field_name, expected in cases: with self.subTest(field_name=field_name): actual = unbound[field_name].value() self.assertEqual(actual, expected) # Also check get_initial_for_field(). field = unbound.fields[field_name] actual = unbound.get_initial_for_field(field, field_name) self.assertEqual(actual, expected) def get_datetime_form_with_callable_initial(self, disabled, microseconds=0): class FakeTime: def __init__(self): self.elapsed_seconds = 0 def now(self): self.elapsed_seconds += 1 return datetime.datetime( 2006, 10, 25, 14, 30, 45 + self.elapsed_seconds, microseconds, ) class DateTimeForm(forms.Form): dt = DateTimeField(initial=FakeTime().now, disabled=disabled) return DateTimeForm({}) def test_datetime_clean_disabled_callable_initial_microseconds(self): """ Cleaning a form with a disabled DateTimeField and callable initial removes microseconds. """ form = self.get_datetime_form_with_callable_initial( disabled=True, microseconds=123456, ) self.assertEqual(form.errors, {}) self.assertEqual( form.cleaned_data, { "dt": datetime.datetime(2006, 10, 25, 14, 30, 46), }, ) def test_datetime_clean_disabled_callable_initial_bound_field(self): """ The cleaned value for a form with a disabled DateTimeField and callable initial matches the bound field's cached initial value. """ form = self.get_datetime_form_with_callable_initial(disabled=True) self.assertEqual(form.errors, {}) cleaned = form.cleaned_data["dt"] self.assertEqual(cleaned, datetime.datetime(2006, 10, 25, 14, 30, 46)) bf = form["dt"] self.assertEqual(cleaned, bf.initial) def test_datetime_changed_data_callable_with_microseconds(self): class DateTimeForm(forms.Form): dt = DateTimeField( initial=lambda: datetime.datetime(2006, 10, 25, 14, 30, 45, 123456), disabled=True, ) form = DateTimeForm({"dt": "2006-10-25 14:30:45"}) self.assertEqual(form.changed_data, []) def test_help_text(self): # You can specify descriptive text for a field by using the 'help_text' # argument. class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField( widget=PasswordInput, help_text="Wählen Sie mit Bedacht." ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></li>""", ) self.assertHTMLEqual( p.as_p(), """<p>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></p> <p>Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></p>""", ) self.assertHTMLEqual( p.as_table(), """ <tr><th>Username:</th><td> <input type="text" name="username" maxlength="10" required><br> <span class="helptext">e.g., [email protected]</span></td></tr> <tr><th>Password:</th><td><input type="password" name="password" required> <br> <span class="helptext">Wählen Sie mit Bedacht.</span></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<div>Username: <div class="helptext">e.g., [email protected]</div>' '<input type="text" name="username" maxlength="10" required></div>' '<div>Password: <div class="helptext">Wählen Sie mit Bedacht.</div>' '<input type="password" name="password" required></div>', ) # The help text is displayed whether or not data is provided for the form. p = UserRegistration({"username": "foo"}, auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li><ul class="errorlist"><li>This field is required.</li></ul> Password: <input type="password" name="password" required> <span class="helptext">Wählen Sie mit Bedacht.</span></li>""", ) # help_text is not displayed for hidden fields. It can be used for documentation # purposes, though. class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField(widget=PasswordInput) next = CharField( widget=HiddenInput, initial="/", help_text="Redirect destination" ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>Username: <input type="text" name="username" maxlength="10" required> <span class="helptext">e.g., [email protected]</span></li> <li>Password: <input type="password" name="password" required> <input type="hidden" name="next" value="/"></li>""", ) def test_help_text_html_safe(self): """help_text should not be escaped.""" class UserRegistration(Form): username = CharField(max_length=10, help_text="e.g., [email protected]") password = CharField( widget=PasswordInput, help_text="Help text is <strong>escaped</strong>.", ) p = UserRegistration(auto_id=False) self.assertHTMLEqual( p.as_ul(), '<li>Username: <input type="text" name="username" maxlength="10" required>' '<span class="helptext">e.g., [email protected]</span></li>' '<li>Password: <input type="password" name="password" required>' '<span class="helptext">Help text is <strong>escaped</strong>.</span></li>', ) self.assertHTMLEqual( p.as_p(), '<p>Username: <input type="text" name="username" maxlength="10" required>' '<span class="helptext">e.g., [email protected]</span></p>' '<p>Password: <input type="password" name="password" required>' '<span class="helptext">Help text is <strong>escaped</strong>.</span></p>', ) self.assertHTMLEqual( p.as_table(), "<tr><th>Username:</th><td>" '<input type="text" name="username" maxlength="10" required><br>' '<span class="helptext">e.g., [email protected]</span></td></tr>' "<tr><th>Password:</th><td>" '<input type="password" name="password" required><br>' '<span class="helptext">Help text is <strong>escaped</strong>.</span>' "</td></tr>", ) def test_subclassing_forms(self): # You can subclass a Form to add fields. The resulting form subclass will have # all of the fields of the parent Form, plus whichever fields you define in the # subclass. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Musician(Person): instrument = CharField() p = Person(auto_id=False) self.assertHTMLEqual( p.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li>""", ) m = Musician(auto_id=False) self.assertHTMLEqual( m.as_ul(), """<li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Instrument: <input type="text" name="instrument" required></li>""", ) # Yes, you can subclass multiple forms. The fields are added in the order in # which the parent classes are listed. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() class Instrument(Form): instrument = CharField() class Beatle(Person, Instrument): haircut_type = CharField() b = Beatle(auto_id=False) self.assertHTMLEqual( b.as_ul(), """<li>Instrument: <input type="text" name="instrument" required></li> <li>First name: <input type="text" name="first_name" required></li> <li>Last name: <input type="text" name="last_name" required></li> <li>Birthday: <input type="text" name="birthday" required></li> <li>Haircut type: <input type="text" name="haircut_type" required></li>""", ) def test_forms_with_prefixes(self): # Sometimes it's necessary to have multiple forms display on the same # HTML page, or multiple copies of the same form. We can accomplish # this with form prefixes. Pass the keyword argument 'prefix' to the # Form constructor to use this feature. This value will be prepended to # each HTML form field name. One way to think about this is "namespaces # for HTML forms". Notice that in the data argument, each field's key # has the prefix, in this case 'person1', prepended to the actual field # name. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() data = { "person1-first_name": "John", "person1-last_name": "Lennon", "person1-birthday": "1940-10-9", } p = Person(data, prefix="person1") self.assertHTMLEqual( p.as_ul(), """ <li><label for="id_person1-first_name">First name:</label> <input type="text" name="person1-first_name" value="John" id="id_person1-first_name" required></li> <li><label for="id_person1-last_name">Last name:</label> <input type="text" name="person1-last_name" value="Lennon" id="id_person1-last_name" required></li> <li><label for="id_person1-birthday">Birthday:</label> <input type="text" name="person1-birthday" value="1940-10-9" id="id_person1-birthday" required></li> """, ) self.assertHTMLEqual( str(p["first_name"]), '<input type="text" name="person1-first_name" value="John" ' 'id="id_person1-first_name" required>', ) self.assertHTMLEqual( str(p["last_name"]), '<input type="text" name="person1-last_name" value="Lennon" ' 'id="id_person1-last_name" required>', ) self.assertHTMLEqual( str(p["birthday"]), '<input type="text" name="person1-birthday" value="1940-10-9" ' 'id="id_person1-birthday" required>', ) self.assertEqual(p.errors, {}) self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) # Let's try submitting some bad data to make sure form.errors and field.errors # work as expected. data = { "person1-first_name": "", "person1-last_name": "", "person1-birthday": "", } p = Person(data, prefix="person1") self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) self.assertEqual(p["first_name"].errors, ["This field is required."]) # Accessing a nonexistent field. with self.assertRaises(KeyError): p["person1-first_name"].errors # In this example, the data doesn't have a prefix, but the form requires it, so # the form doesn't "see" the fields. data = {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} p = Person(data, prefix="person1") self.assertEqual(p.errors["first_name"], ["This field is required."]) self.assertEqual(p.errors["last_name"], ["This field is required."]) self.assertEqual(p.errors["birthday"], ["This field is required."]) # With prefixes, a single data dictionary can hold data for multiple instances # of the same form. data = { "person1-first_name": "John", "person1-last_name": "Lennon", "person1-birthday": "1940-10-9", "person2-first_name": "Jim", "person2-last_name": "Morrison", "person2-birthday": "1943-12-8", } p1 = Person(data, prefix="person1") self.assertTrue(p1.is_valid()) self.assertEqual(p1.cleaned_data["first_name"], "John") self.assertEqual(p1.cleaned_data["last_name"], "Lennon") self.assertEqual(p1.cleaned_data["birthday"], datetime.date(1940, 10, 9)) p2 = Person(data, prefix="person2") self.assertTrue(p2.is_valid()) self.assertEqual(p2.cleaned_data["first_name"], "Jim") self.assertEqual(p2.cleaned_data["last_name"], "Morrison") self.assertEqual(p2.cleaned_data["birthday"], datetime.date(1943, 12, 8)) # By default, forms append a hyphen between the prefix and the field name, but a # form can alter that behavior by implementing the add_prefix() method. This # method takes a field name and returns the prefixed field, according to # self.prefix. class Person(Form): first_name = CharField() last_name = CharField() birthday = DateField() def add_prefix(self, field_name): return ( "%s-prefix-%s" % (self.prefix, field_name) if self.prefix else field_name ) p = Person(prefix="foo") self.assertHTMLEqual( p.as_ul(), """ <li><label for="id_foo-prefix-first_name">First name:</label> <input type="text" name="foo-prefix-first_name" id="id_foo-prefix-first_name" required></li> <li><label for="id_foo-prefix-last_name">Last name:</label> <input type="text" name="foo-prefix-last_name" id="id_foo-prefix-last_name" required></li> <li><label for="id_foo-prefix-birthday">Birthday:</label> <input type="text" name="foo-prefix-birthday" id="id_foo-prefix-birthday" required></li> """, ) data = { "foo-prefix-first_name": "John", "foo-prefix-last_name": "Lennon", "foo-prefix-birthday": "1940-10-9", } p = Person(data, prefix="foo") self.assertTrue(p.is_valid()) self.assertEqual(p.cleaned_data["first_name"], "John") self.assertEqual(p.cleaned_data["last_name"], "Lennon") self.assertEqual(p.cleaned_data["birthday"], datetime.date(1940, 10, 9)) def test_class_prefix(self): # Prefix can be also specified at the class level. class Person(Form): first_name = CharField() prefix = "foo" p = Person() self.assertEqual(p.prefix, "foo") p = Person(prefix="bar") self.assertEqual(p.prefix, "bar") def test_forms_with_null_boolean(self): # NullBooleanField is a bit of a special case because its presentation (widget) # is different than its data. This is handled transparently, though. class Person(Form): name = CharField() is_cool = NullBooleanField() p = Person({"name": "Joe"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "1"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "2"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "3"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": True}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": False}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "unknown"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "true"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true" selected>Yes</option> <option value="false">No</option> </select>""", ) p = Person({"name": "Joe", "is_cool": "false"}, auto_id=False) self.assertHTMLEqual( str(p["is_cool"]), """<select name="is_cool"> <option value="unknown">Unknown</option> <option value="true">Yes</option> <option value="false" selected>No</option> </select>""", ) def test_forms_with_file_fields(self): # FileFields are a special case because they take their data from the # request.FILES, not request.POST. class FileForm(Form): file1 = FileField() f = FileForm(auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) f = FileForm(data={}, files={}, auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>This field is required.</li></ul>' '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": SimpleUploadedFile("name", b"")}, auto_id=False ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>The submitted file is empty.</li></ul>' '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": "something that is not a file"}, auto_id=False ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<ul class="errorlist"><li>No file was submitted. Check the ' "encoding type on the form.</li></ul>" '<input type="file" name="file1" required></td></tr>', ) f = FileForm( data={}, files={"file1": SimpleUploadedFile("name", b"some content")}, auto_id=False, ) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) self.assertTrue(f.is_valid()) file1 = SimpleUploadedFile( "我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode() ) f = FileForm(data={}, files={"file1": file1}, auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) # A required file field with initial data should not contain the # required HTML attribute. The file input is left blank by the user to # keep the existing, initial value. f = FileForm(initial={"file1": "resume.txt"}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>', ) def test_filefield_initial_callable(self): class FileForm(forms.Form): file1 = forms.FileField(initial=lambda: "resume.txt") f = FileForm({}) self.assertEqual(f.errors, {}) self.assertEqual(f.cleaned_data["file1"], "resume.txt") def test_filefield_with_fileinput_required(self): class FileForm(Form): file1 = forms.FileField(widget=FileInput) f = FileForm(auto_id=False) self.assertHTMLEqual( f.as_table(), "<tr><th>File1:</th><td>" '<input type="file" name="file1" required></td></tr>', ) # A required file field with initial data doesn't contain the required # HTML attribute. The file input is left blank by the user to keep the # existing, initial value. f = FileForm(initial={"file1": "resume.txt"}, auto_id=False) self.assertHTMLEqual( f.as_table(), '<tr><th>File1:</th><td><input type="file" name="file1"></td></tr>', ) def test_empty_permitted(self): # Sometimes (pretty much in formsets) we want to allow a form to pass validation # if it is completely empty. We can accomplish this by using the empty_permitted # argument to a form constructor. class SongForm(Form): artist = CharField() name = CharField() # First let's show what happens id empty_permitted=False (the default): data = {"artist": "", "song": ""} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "name": ["This field is required."], "artist": ["This field is required."], }, ) self.assertEqual(form.cleaned_data, {}) # Now let's show what happens when empty_permitted=True and the form is empty. form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) self.assertEqual(form.errors, {}) self.assertEqual(form.cleaned_data, {}) # But if we fill in data for one of the fields, the form is no longer empty and # the whole thing must pass validation. data = {"artist": "The Doors", "song": ""} form = SongForm(data, empty_permitted=False) self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {"name": ["This field is required."]}) self.assertEqual(form.cleaned_data, {"artist": "The Doors"}) # If a field is not given in the data then None is returned for its data. Lets # make sure that when checking for empty_permitted that None is treated # accordingly. data = {"artist": None, "song": ""} form = SongForm(data, empty_permitted=True, use_required_attribute=False) self.assertTrue(form.is_valid()) # However, we *really* need to be sure we are checking for None as any data in # initial that returns False on a boolean call needs to be treated literally. class PriceForm(Form): amount = FloatField() qty = IntegerField() data = {"amount": "0.0", "qty": ""} form = PriceForm( data, initial={"amount": 0.0}, empty_permitted=True, use_required_attribute=False, ) self.assertTrue(form.is_valid()) def test_empty_permitted_and_use_required_attribute(self): msg = ( "The empty_permitted and use_required_attribute arguments may not " "both be True." ) with self.assertRaisesMessage(ValueError, msg): Person(empty_permitted=True, use_required_attribute=True) def test_extracting_hidden_and_visible(self): class SongForm(Form): token = CharField(widget=HiddenInput) artist = CharField() name = CharField() form = SongForm() self.assertEqual([f.name for f in form.hidden_fields()], ["token"]) self.assertEqual([f.name for f in form.visible_fields()], ["artist", "name"]) def test_hidden_initial_gets_id(self): class MyForm(Form): field1 = CharField(max_length=50, show_hidden_initial=True) self.assertHTMLEqual( MyForm().as_table(), '<tr><th><label for="id_field1">Field1:</label></th><td>' '<input id="id_field1" type="text" name="field1" maxlength="50" required>' '<input type="hidden" name="initial-field1" id="initial-id_field1">' "</td></tr>", ) def test_error_html_required_html_classes(self): class Person(Form): name = CharField() is_cool = NullBooleanField() email = EmailField(required=False) age = IntegerField() p = Person({}) p.error_css_class = "error" p.required_css_class = "required" self.assertHTMLEqual( p.as_ul(), """ <li class="required error"><ul class="errorlist"> <li>This field is required.</li></ul> <label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></li> <li class="required"> <label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></li> <li><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></li> <li class="required error"><ul class="errorlist"> <li>This field is required.</li></ul> <label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></li>""", ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"> <label class="required" for="id_name">Name:</label> <input type="text" name="name" id="id_name" required></p> <p class="required"> <label class="required" for="id_is_cool">Is cool:</label> <select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></p> <p><label for="id_email">Email:</label> <input type="email" name="email" id="id_email"></p> <ul class="errorlist"><li>This field is required.</li></ul> <p class="required error"><label class="required" for="id_age">Age:</label> <input type="number" name="age" id="id_age" required></p> """, ) self.assertHTMLEqual( p.as_table(), """<tr class="required error"> <th><label class="required" for="id_name">Name:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="text" name="name" id="id_name" required></td></tr> <tr class="required"><th><label class="required" for="id_is_cool">Is cool:</label></th> <td><select name="is_cool" id="id_is_cool"> <option value="unknown" selected>Unknown</option> <option value="true">Yes</option> <option value="false">No</option> </select></td></tr> <tr><th><label for="id_email">Email:</label></th><td> <input type="email" name="email" id="id_email"></td></tr> <tr class="required error"><th><label class="required" for="id_age">Age:</label></th> <td><ul class="errorlist"><li>This field is required.</li></ul> <input type="number" name="age" id="id_age" required></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<div class="required error"><label for="id_name" class="required">Name:' '</label><ul class="errorlist"><li>This field is required.</li></ul>' '<input type="text" name="name" required id="id_name" /></div>' '<div class="required"><label for="id_is_cool" class="required">Is cool:' '</label><select name="is_cool" id="id_is_cool">' '<option value="unknown" selected>Unknown</option>' '<option value="true">Yes</option><option value="false">No</option>' '</select></div><div><label for="id_email">Email:</label>' '<input type="email" name="email" id="id_email" /></div>' '<div class="required error"><label for="id_age" class="required">Age:' '</label><ul class="errorlist"><li>This field is required.</li></ul>' '<input type="number" name="age" required id="id_age" /></div>', ) def test_label_has_required_css_class(self): """ required_css_class is added to label_tag() and legend_tag() of required fields. """ class SomeForm(Form): required_css_class = "required" field = CharField(max_length=10) field2 = IntegerField(required=False) f = SomeForm({"field": "test"}) self.assertHTMLEqual( f["field"].label_tag(), '<label for="id_field" class="required">Field:</label>', ) self.assertHTMLEqual( f["field"].legend_tag(), '<legend for="id_field" class="required">Field:</legend>', ) self.assertHTMLEqual( f["field"].label_tag(attrs={"class": "foo"}), '<label for="id_field" class="foo required">Field:</label>', ) self.assertHTMLEqual( f["field"].legend_tag(attrs={"class": "foo"}), '<legend for="id_field" class="foo required">Field:</legend>', ) self.assertHTMLEqual( f["field2"].label_tag(), '<label for="id_field2">Field2:</label>' ) self.assertHTMLEqual( f["field2"].legend_tag(), '<legend for="id_field2">Field2:</legend>', ) def test_label_split_datetime_not_displayed(self): class EventForm(Form): happened_at = SplitDateTimeField(widget=SplitHiddenDateTimeWidget) form = EventForm() self.assertHTMLEqual( form.as_ul(), '<input type="hidden" name="happened_at_0" id="id_happened_at_0">' '<input type="hidden" name="happened_at_1" id="id_happened_at_1">', ) def test_multivalue_field_validation(self): def bad_names(value): if value == "bad value": raise ValidationError("bad value not allowed") class NameField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = ( CharField(label="First name", max_length=10), CharField(label="Last name", max_length=10), ) super().__init__(fields=fields, *args, **kwargs) def compress(self, data_list): return " ".join(data_list) class NameForm(Form): name = NameField(validators=[bad_names]) form = NameForm(data={"name": ["bad", "value"]}) form.full_clean() self.assertFalse(form.is_valid()) self.assertEqual(form.errors, {"name": ["bad value not allowed"]}) form = NameForm(data={"name": ["should be overly", "long for the field names"]}) self.assertFalse(form.is_valid()) self.assertEqual( form.errors, { "name": [ "Ensure this value has at most 10 characters (it has 16).", "Ensure this value has at most 10 characters (it has 24).", ], }, ) form = NameForm(data={"name": ["fname", "lname"]}) self.assertTrue(form.is_valid()) self.assertEqual(form.cleaned_data, {"name": "fname lname"}) def test_multivalue_deep_copy(self): """ #19298 -- MultiValueField needs to override the default as it needs to deep-copy subfields: """ class ChoicesField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = ( ChoiceField(label="Rank", choices=((1, 1), (2, 2))), CharField(label="Name", max_length=10), ) super().__init__(fields=fields, *args, **kwargs) field = ChoicesField() field2 = copy.deepcopy(field) self.assertIsInstance(field2, ChoicesField) self.assertIsNot(field2.fields, field.fields) self.assertIsNot(field2.fields[0].choices, field.fields[0].choices) def test_multivalue_initial_data(self): """ #23674 -- invalid initial data should not break form.changed_data() """ class DateAgeField(MultiValueField): def __init__(self, fields=(), *args, **kwargs): fields = (DateField(label="Date"), IntegerField(label="Age")) super().__init__(fields=fields, *args, **kwargs) class DateAgeForm(Form): date_age = DateAgeField() data = {"date_age": ["1998-12-06", 16]} form = DateAgeForm(data, initial={"date_age": ["200-10-10", 14]}) self.assertTrue(form.has_changed()) def test_multivalue_optional_subfields(self): class PhoneField(MultiValueField): def __init__(self, *args, **kwargs): fields = ( CharField( label="Country Code", validators=[ RegexValidator( r"^\+[0-9]{1,2}$", message="Enter a valid country code." ) ], ), CharField(label="Phone Number"), CharField( label="Extension", error_messages={"incomplete": "Enter an extension."}, ), CharField( label="Label", required=False, help_text="E.g. home, work." ), ) super().__init__(fields, *args, **kwargs) def compress(self, data_list): if data_list: return "%s.%s ext. %s (label: %s)" % tuple(data_list) return None # An empty value for any field will raise a `required` error on a # required `MultiValueField`. f = PhoneField() with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(["+61"]) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(["+61", "287654321", "123"]) self.assertEqual( "+61.287654321 ext. 123 (label: Home)", f.clean(["+61", "287654321", "123", "Home"]), ) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # Empty values for fields will NOT raise a `required` error on an # optional `MultiValueField` f = PhoneField(required=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) self.assertEqual("+61. ext. (label: )", f.clean(["+61"])) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) self.assertEqual( "+61.287654321 ext. 123 (label: Home)", f.clean(["+61", "287654321", "123", "Home"]), ) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # For a required `MultiValueField` with `require_all_fields=False`, a # `required` error will only be raised if all fields are empty. Fields # can individually be required or optional. An empty value for any # required field will raise an `incomplete` error. f = PhoneField(require_all_fields=False) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean("") with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean(None) with self.assertRaisesMessage(ValidationError, "'This field is required.'"): f.clean([]) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(["+61"]) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) with self.assertRaisesMessage( ValidationError, "'Enter a complete value.', 'Enter an extension.'" ): f.clean(["", "", "", "Home"]) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) # For an optional `MultiValueField` with `require_all_fields=False`, we # don't get any `required` error but we still get `incomplete` errors. f = PhoneField(required=False, require_all_fields=False) self.assertIsNone(f.clean("")) self.assertIsNone(f.clean(None)) self.assertIsNone(f.clean([])) with self.assertRaisesMessage(ValidationError, "'Enter a complete value.'"): f.clean(["+61"]) self.assertEqual( "+61.287654321 ext. 123 (label: )", f.clean(["+61", "287654321", "123"]) ) with self.assertRaisesMessage( ValidationError, "'Enter a complete value.', 'Enter an extension.'" ): f.clean(["", "", "", "Home"]) with self.assertRaisesMessage(ValidationError, "'Enter a valid country code.'"): f.clean(["61", "287654321", "123", "Home"]) def test_multivalue_optional_subfields_rendering(self): class PhoneWidget(MultiWidget): def __init__(self, attrs=None): widgets = [TextInput(), TextInput()] super().__init__(widgets, attrs) def decompress(self, value): return [None, None] class PhoneField(MultiValueField): def __init__(self, *args, **kwargs): fields = [CharField(), CharField(required=False)] super().__init__(fields, *args, **kwargs) class PhoneForm(Form): phone1 = PhoneField(widget=PhoneWidget) phone2 = PhoneField(widget=PhoneWidget, required=False) phone3 = PhoneField(widget=PhoneWidget, require_all_fields=False) phone4 = PhoneField( widget=PhoneWidget, required=False, require_all_fields=False, ) form = PhoneForm(auto_id=False) self.assertHTMLEqual( form.as_p(), """ <p>Phone1:<input type="text" name="phone1_0" required> <input type="text" name="phone1_1" required></p> <p>Phone2:<input type="text" name="phone2_0"> <input type="text" name="phone2_1"></p> <p>Phone3:<input type="text" name="phone3_0" required> <input type="text" name="phone3_1"></p> <p>Phone4:<input type="text" name="phone4_0"> <input type="text" name="phone4_1"></p> """, ) def test_custom_empty_values(self): """ Form fields can customize what is considered as an empty value for themselves (#19997). """ class CustomJSONField(CharField): empty_values = [None, ""] def to_python(self, value): # Fake json.loads if value == "{}": return {} return super().to_python(value) class JSONForm(forms.Form): json = CustomJSONField() form = JSONForm(data={"json": "{}"}) form.full_clean() self.assertEqual(form.cleaned_data, {"json": {}}) def test_boundfield_label_tag(self): class SomeForm(Form): field = CharField() boundfield = SomeForm()["field"] testcases = [ # (args, kwargs, expected) # without anything: just print the <label> ((), {}, '<%(tag)s for="id_field">Field:</%(tag)s>'), # passing just one argument: overrides the field's label (("custom",), {}, '<%(tag)s for="id_field">custom:</%(tag)s>'), # the overridden label is escaped (("custom&",), {}, '<%(tag)s for="id_field">custom&amp;:</%(tag)s>'), ((mark_safe("custom&"),), {}, '<%(tag)s for="id_field">custom&:</%(tag)s>'), # Passing attrs to add extra attributes on the <label> ( (), {"attrs": {"class": "pretty"}}, '<%(tag)s for="id_field" class="pretty">Field:</%(tag)s>', ), ] for args, kwargs, expected in testcases: with self.subTest(args=args, kwargs=kwargs): self.assertHTMLEqual( boundfield.label_tag(*args, **kwargs), expected % {"tag": "label"}, ) self.assertHTMLEqual( boundfield.legend_tag(*args, **kwargs), expected % {"tag": "legend"}, ) def test_boundfield_label_tag_no_id(self): """ If a widget has no id, label_tag() and legend_tag() return the text with no surrounding <label>. """ class SomeForm(Form): field = CharField() boundfield = SomeForm(auto_id="")["field"] self.assertHTMLEqual(boundfield.label_tag(), "Field:") self.assertHTMLEqual(boundfield.legend_tag(), "Field:") self.assertHTMLEqual(boundfield.label_tag("Custom&"), "Custom&amp;:") self.assertHTMLEqual(boundfield.legend_tag("Custom&"), "Custom&amp;:") def test_boundfield_label_tag_custom_widget_id_for_label(self): class CustomIdForLabelTextInput(TextInput): def id_for_label(self, id): return "custom_" + id class EmptyIdForLabelTextInput(TextInput): def id_for_label(self, id): return None class SomeForm(Form): custom = CharField(widget=CustomIdForLabelTextInput) empty = CharField(widget=EmptyIdForLabelTextInput) form = SomeForm() self.assertHTMLEqual( form["custom"].label_tag(), '<label for="custom_id_custom">Custom:</label>' ) self.assertHTMLEqual( form["custom"].legend_tag(), '<legend for="custom_id_custom">Custom:</legend>', ) self.assertHTMLEqual(form["empty"].label_tag(), "<label>Empty:</label>") self.assertHTMLEqual(form["empty"].legend_tag(), "<legend>Empty:</legend>") def test_boundfield_empty_label(self): class SomeForm(Form): field = CharField(label="") boundfield = SomeForm()["field"] self.assertHTMLEqual(boundfield.label_tag(), '<label for="id_field"></label>') self.assertHTMLEqual( boundfield.legend_tag(), '<legend for="id_field"></legend>', ) def test_boundfield_id_for_label(self): class SomeForm(Form): field = CharField(label="") self.assertEqual(SomeForm()["field"].id_for_label, "id_field") def test_boundfield_id_for_label_override_by_attrs(self): """ If an id is provided in `Widget.attrs`, it overrides the generated ID, unless it is `None`. """ class SomeForm(Form): field = CharField(widget=TextInput(attrs={"id": "myCustomID"})) field_none = CharField(widget=TextInput(attrs={"id": None})) form = SomeForm() self.assertEqual(form["field"].id_for_label, "myCustomID") self.assertEqual(form["field_none"].id_for_label, "id_field_none") def test_boundfield_subwidget_id_for_label(self): """ If auto_id is provided when initializing the form, the generated ID in subwidgets must reflect that prefix. """ class SomeForm(Form): field = MultipleChoiceField( choices=[("a", "A"), ("b", "B")], widget=CheckboxSelectMultiple, ) form = SomeForm(auto_id="prefix_%s") subwidgets = form["field"].subwidgets self.assertEqual(subwidgets[0].id_for_label, "prefix_field_0") self.assertEqual(subwidgets[1].id_for_label, "prefix_field_1") def test_boundfield_widget_type(self): class SomeForm(Form): first_name = CharField() birthday = SplitDateTimeField(widget=SplitHiddenDateTimeWidget) f = SomeForm() self.assertEqual(f["first_name"].widget_type, "text") self.assertEqual(f["birthday"].widget_type, "splithiddendatetime") def test_boundfield_css_classes(self): form = Person() field = form["first_name"] self.assertEqual(field.css_classes(), "") self.assertEqual(field.css_classes(extra_classes=""), "") self.assertEqual(field.css_classes(extra_classes="test"), "test") self.assertEqual(field.css_classes(extra_classes="test test"), "test") def test_label_suffix_override(self): """ BoundField label_suffix (if provided) overrides Form label_suffix """ class SomeForm(Form): field = CharField() boundfield = SomeForm(label_suffix="!")["field"] self.assertHTMLEqual( boundfield.label_tag(label_suffix="$"), '<label for="id_field">Field$</label>', ) self.assertHTMLEqual( boundfield.legend_tag(label_suffix="$"), '<legend for="id_field">Field$</legend>', ) def test_error_dict(self): class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError( "Non-field error.", code="secret", params={"a": 1, "b": 2} ) form = MyForm({}) self.assertIs(form.is_valid(), False) errors = form.errors.as_text() control = [ "* foo\n * This field is required.", "* bar\n * This field is required.", "* __all__\n * Non-field error.", ] for error in control: self.assertIn(error, errors) errors = form.errors.as_ul() control = [ '<li>foo<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>bar<ul class="errorlist"><li>This field is required.</li></ul></li>', '<li>__all__<ul class="errorlist nonfield"><li>Non-field error.</li></ul>' "</li>", ] for error in control: self.assertInHTML(error, errors) errors = form.errors.get_json_data() control = { "foo": [{"code": "required", "message": "This field is required."}], "bar": [{"code": "required", "message": "This field is required."}], "__all__": [{"code": "secret", "message": "Non-field error."}], } self.assertEqual(errors, control) self.assertEqual(json.dumps(errors), form.errors.as_json()) def test_error_dict_as_json_escape_html(self): """#21962 - adding html escape flag to ErrorDict""" class MyForm(Form): foo = CharField() bar = CharField() def clean(self): raise ValidationError( "<p>Non-field error.</p>", code="secret", params={"a": 1, "b": 2}, ) control = { "foo": [{"code": "required", "message": "This field is required."}], "bar": [{"code": "required", "message": "This field is required."}], "__all__": [{"code": "secret", "message": "<p>Non-field error.</p>"}], } form = MyForm({}) self.assertFalse(form.is_valid()) errors = json.loads(form.errors.as_json()) self.assertEqual(errors, control) escaped_error = "&lt;p&gt;Non-field error.&lt;/p&gt;" self.assertEqual( form.errors.get_json_data(escape_html=True)["__all__"][0]["message"], escaped_error, ) errors = json.loads(form.errors.as_json(escape_html=True)) control["__all__"][0]["message"] = escaped_error self.assertEqual(errors, control) def test_error_list(self): e = ErrorList() e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertIsInstance(e, list) self.assertIn("Foo", e) self.assertIn("Foo", ValidationError(e)) self.assertEqual(e.as_text(), "* Foo\n* Foobar") self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) errors = e.get_json_data() self.assertEqual( errors, [{"message": "Foo", "code": ""}, {"message": "Foobar", "code": "foobar"}], ) self.assertEqual(json.dumps(errors), e.as_json()) def test_error_list_class_not_specified(self): e = ErrorList() e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertEqual( e.as_ul(), '<ul class="errorlist"><li>Foo</li><li>Foobar</li></ul>' ) def test_error_list_class_has_one_class_specified(self): e = ErrorList(error_class="foobar-error-class") e.append("Foo") e.append(ValidationError("Foo%(bar)s", code="foobar", params={"bar": "bar"})) self.assertEqual( e.as_ul(), '<ul class="errorlist foobar-error-class"><li>Foo</li><li>Foobar</li></ul>', ) def test_error_list_with_hidden_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField(widget=HiddenInput) p = Person({"first_name": "John"}) self.assertHTMLEqual( p.as_ul(), """<li><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></li><li> <label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></li>""", ) self.assertHTMLEqual( p.as_p(), """ <ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></p> """, ) self.assertHTMLEqual( p.as_table(), """<tr><td colspan="2"><ul class="errorlist nonfield"> <li>(Hidden field last_name) This field is required.</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required> <input id="id_last_name" name="last_name" type="hidden"></td></tr>""", ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>(Hidden field last_name) This field ' 'is required.</li></ul><div><label for="id_first_name">First name:</label>' '<input id="id_first_name" name="first_name" type="text" value="John" ' 'required><input id="id_last_name" name="last_name" type="hidden"></div>', ) def test_error_list_with_non_field_errors_has_correct_class(self): class Person(Form): first_name = CharField() last_name = CharField() def clean(self): raise ValidationError("Generic validation error") p = Person({"first_name": "John", "last_name": "Lennon"}) self.assertHTMLEqual( str(p.non_field_errors()), '<ul class="errorlist nonfield"><li>Generic validation error</li></ul>', ) self.assertHTMLEqual( p.as_ul(), """<li> <ul class="errorlist nonfield"><li>Generic validation error</li></ul></li> <li><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></li> <li><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></li>""", ) self.assertHTMLEqual( p.non_field_errors().as_text(), "* Generic validation error" ) self.assertHTMLEqual( p.as_p(), """<ul class="errorlist nonfield"><li>Generic validation error</li></ul> <p><label for="id_first_name">First name:</label> <input id="id_first_name" name="first_name" type="text" value="John" required></p> <p><label for="id_last_name">Last name:</label> <input id="id_last_name" name="last_name" type="text" value="Lennon" required></p>""", ) self.assertHTMLEqual( p.as_table(), """ <tr><td colspan="2"><ul class="errorlist nonfield"> <li>Generic validation error</li></ul></td></tr> <tr><th><label for="id_first_name">First name:</label></th><td> <input id="id_first_name" name="first_name" type="text" value="John" required> </td></tr> <tr><th><label for="id_last_name">Last name:</label></th><td> <input id="id_last_name" name="last_name" type="text" value="Lennon" required> </td></tr> """, ) self.assertHTMLEqual( p.as_div(), '<ul class="errorlist nonfield"><li>Generic validation error</li></ul>' '<div><label for="id_first_name">First name:</label><input ' 'id="id_first_name" name="first_name" type="text" value="John" required>' '</div><div><label for="id_last_name">Last name:</label><input ' 'id="id_last_name" name="last_name" type="text" value="Lennon" required>' "</div>", ) def test_error_escaping(self): class TestForm(Form): hidden = CharField(widget=HiddenInput(), required=False) visible = CharField() def clean_hidden(self): raise ValidationError('Foo & "bar"!') clean_visible = clean_hidden form = TestForm({"hidden": "a", "visible": "b"}) form.is_valid() self.assertHTMLEqual( form.as_ul(), '<li><ul class="errorlist nonfield">' "<li>(Hidden field hidden) Foo &amp; &quot;bar&quot;!</li></ul></li>" '<li><ul class="errorlist"><li>Foo &amp; &quot;bar&quot;!</li></ul>' '<label for="id_visible">Visible:</label> ' '<input type="text" name="visible" value="b" id="id_visible" required>' '<input type="hidden" name="hidden" value="a" id="id_hidden"></li>', ) def test_baseform_repr(self): """ BaseForm.__repr__() should contain some basic information about the form. """ p = Person() self.assertEqual( repr(p), "<Person bound=False, valid=Unknown, " "fields=(first_name;last_name;birthday)>", ) p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "1940-10-9"} ) self.assertEqual( repr(p), "<Person bound=True, valid=Unknown, " "fields=(first_name;last_name;birthday)>", ) p.is_valid() self.assertEqual( repr(p), "<Person bound=True, valid=True, fields=(first_name;last_name;birthday)>", ) p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"} ) p.is_valid() self.assertEqual( repr(p), "<Person bound=True, valid=False, fields=(first_name;last_name;birthday)>", ) def test_baseform_repr_dont_trigger_validation(self): """ BaseForm.__repr__() shouldn't trigger the form validation. """ p = Person( {"first_name": "John", "last_name": "Lennon", "birthday": "fakedate"} ) repr(p) with self.assertRaises(AttributeError): p.cleaned_data self.assertFalse(p.is_valid()) self.assertEqual(p.cleaned_data, {"first_name": "John", "last_name": "Lennon"}) def test_accessing_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data if not self.errors: data["username"] = data["username"].lower() return data f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_changing_cleaned_data_nothing_returned(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): self.cleaned_data["username"] = self.cleaned_data["username"].lower() # don't return anything f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_changing_cleaned_data_in_clean(self): class UserForm(Form): username = CharField(max_length=10) password = CharField(widget=PasswordInput) def clean(self): data = self.cleaned_data # Return a different dict. We have not changed self.cleaned_data. return { "username": data["username"].lower(), "password": "this_is_not_a_secret", } f = UserForm({"username": "SirRobin", "password": "blue"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data["username"], "sirrobin") def test_multipart_encoded_form(self): class FormWithoutFile(Form): username = CharField() class FormWithFile(Form): username = CharField() file = FileField() class FormWithImage(Form): image = ImageField() self.assertFalse(FormWithoutFile().is_multipart()) self.assertTrue(FormWithFile().is_multipart()) self.assertTrue(FormWithImage().is_multipart()) def test_html_safe(self): class SimpleForm(Form): username = CharField() form = SimpleForm() self.assertTrue(hasattr(SimpleForm, "__html__")) self.assertEqual(str(form), form.__html__()) self.assertTrue(hasattr(form["username"], "__html__")) self.assertEqual(str(form["username"]), form["username"].__html__()) def test_use_required_attribute_true(self): class MyForm(Form): use_required_attribute = True f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text" required></p>' '<p><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></p>" '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></p>", ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label> ' '<input id="id_f1" maxlength="30" name="f1" type="text" required></li>' '<li><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></li>" '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></li>", ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text" required>' "</td></tr>" '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th>' '<td><textarea cols="40" id="id_f3" name="f3" rows="10" required>' "</textarea></td></tr>" '<tr><th><label for="id_f4">F4:</label></th><td>' '<select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></td></tr>", ) self.assertHTMLEqual( form.render(form.template_name_div), '<div><label for="id_f1">F1:</label><input id="id_f1" maxlength="30" ' 'name="f1" type="text" required></div><div><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></div><div><label ' 'for="id_f3">F3:</label><textarea cols="40" id="id_f3" name="f3" ' 'rows="10" required></textarea></div><div><label for="id_f4">F4:</label>' '<select id="id_f4" name="f4"><option value="P">Python</option>' '<option value="J">Java</option></select></div>', ) def test_use_required_attribute_false(self): class MyForm(Form): use_required_attribute = False f1 = CharField(max_length=30) f2 = CharField(max_length=30, required=False) f3 = CharField(widget=Textarea) f4 = ChoiceField(choices=[("P", "Python"), ("J", "Java")]) form = MyForm() self.assertHTMLEqual( form.as_p(), '<p><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text"></p>' '<p><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></p>' '<p><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></p>' '<p><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></p>", ) self.assertHTMLEqual( form.as_ul(), '<li><label for="id_f1">F1:</label>' '<input id="id_f1" maxlength="30" name="f1" type="text"></li>' '<li><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></li>' '<li><label for="id_f3">F3:</label>' '<textarea cols="40" id="id_f3" name="f3" rows="10"></textarea></li>' '<li><label for="id_f4">F4:</label> <select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></li>", ) self.assertHTMLEqual( form.as_table(), '<tr><th><label for="id_f1">F1:</label></th>' '<td><input id="id_f1" maxlength="30" name="f1" type="text"></td></tr>' '<tr><th><label for="id_f2">F2:</label></th>' '<td><input id="id_f2" maxlength="30" name="f2" type="text"></td></tr>' '<tr><th><label for="id_f3">F3:</label></th><td>' '<textarea cols="40" id="id_f3" name="f3" rows="10">' "</textarea></td></tr>" '<tr><th><label for="id_f4">F4:</label></th><td>' '<select id="id_f4" name="f4">' '<option value="P">Python</option>' '<option value="J">Java</option>' "</select></td></tr>", ) self.assertHTMLEqual( form.render(form.template_name_div), '<div><label for="id_f1">F1:</label> <input id="id_f1" maxlength="30" ' 'name="f1" type="text"></div><div><label for="id_f2">F2:</label>' '<input id="id_f2" maxlength="30" name="f2" type="text"></div><div>' '<label for="id_f3">F3:</label> <textarea cols="40" id="id_f3" name="f3" ' 'rows="10"></textarea></div><div><label for="id_f4">F4:</label>' '<select id="id_f4" name="f4"><option value="P">Python</option>' '<option value="J">Java</option></select></div>', ) def test_only_hidden_fields(self): # A form with *only* hidden fields that has errors is going to be very unusual. class HiddenForm(Form): data = IntegerField(widget=HiddenInput) f = HiddenForm({}) self.assertHTMLEqual( f.as_p(), '<ul class="errorlist nonfield">' "<li>(Hidden field data) This field is required.</li></ul>\n<p> " '<input type="hidden" name="data" id="id_data"></p>', ) self.assertHTMLEqual( f.as_table(), '<tr><td colspan="2"><ul class="errorlist nonfield">' "<li>(Hidden field data) This field is required.</li></ul>" '<input type="hidden" name="data" id="id_data"></td></tr>', ) def test_field_named_data(self): class DataForm(Form): data = CharField(max_length=10) f = DataForm({"data": "xyzzy"}) self.assertTrue(f.is_valid()) self.assertEqual(f.cleaned_data, {"data": "xyzzy"}) def test_empty_data_files_multi_value_dict(self): p = Person() self.assertIsInstance(p.data, MultiValueDict) self.assertIsInstance(p.files, MultiValueDict) def test_field_deep_copy_error_messages(self): class CustomCharField(CharField): def __init__(self, **kwargs): kwargs["error_messages"] = {"invalid": "Form custom error message."} super().__init__(**kwargs) field = CustomCharField() field_copy = copy.deepcopy(field) self.assertIsInstance(field_copy, CustomCharField) self.assertIsNot(field_copy.error_messages, field.error_messages) def test_label_does_not_include_new_line(self): form = Person() field = form["first_name"] self.assertEqual( field.label_tag(), '<label for="id_first_name">First name:</label>' ) self.assertEqual( field.legend_tag(), '<legend for="id_first_name">First name:</legend>', ) @override_settings(USE_THOUSAND_SEPARATOR=True) def test_label_attrs_not_localized(self): form = Person() field = form["first_name"] self.assertHTMLEqual( field.label_tag(attrs={"number": 9999}), '<label number="9999" for="id_first_name">First name:</label>', ) self.assertHTMLEqual( field.legend_tag(attrs={"number": 9999}), '<legend number="9999" for="id_first_name">First name:</legend>', ) @jinja2_tests class Jinja2FormsTestCase(FormsTestCase): pass class CustomRenderer(DjangoTemplates): form_template_name = "forms_tests/form_snippet.html" class RendererTests(SimpleTestCase): def test_default(self): form = Form() self.assertEqual(form.renderer, get_default_renderer()) def test_kwarg_instance(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_kwarg_class(self): custom = CustomRenderer() form = Form(renderer=custom) self.assertEqual(form.renderer, custom) def test_attribute_instance(self): class CustomForm(Form): default_renderer = DjangoTemplates() form = CustomForm() self.assertEqual(form.renderer, CustomForm.default_renderer) def test_attribute_class(self): class CustomForm(Form): default_renderer = CustomRenderer form = CustomForm() self.assertIsInstance(form.renderer, CustomForm.default_renderer) def test_attribute_override(self): class CustomForm(Form): default_renderer = DjangoTemplates() custom = CustomRenderer() form = CustomForm(renderer=custom) self.assertEqual(form.renderer, custom) class TemplateTests(SimpleTestCase): def test_iterate_radios(self): f = FrameworkForm(auto_id="id_%s") t = Template( "{% for radio in form.language %}" '<div class="myradio">{{ radio }}</div>' "{% endfor %}" ) self.assertHTMLEqual( t.render(Context({"form": f})), '<div class="myradio"><label for="id_language_0">' '<input id="id_language_0" name="language" type="radio" value="P" ' "required> Python</label></div>" '<div class="myradio"><label for="id_language_1">' '<input id="id_language_1" name="language" type="radio" value="J" ' "required> Java</label></div>", ) def test_iterate_checkboxes(self): f = SongForm({"composers": ["J", "P"]}, auto_id=False) t = Template( "{% for checkbox in form.composers %}" '<div class="mycheckbox">{{ checkbox }}</div>' "{% endfor %}" ) self.assertHTMLEqual( t.render(Context({"form": f})), '<div class="mycheckbox"><label>' '<input checked name="composers" type="checkbox" value="J"> ' "John Lennon</label></div>" '<div class="mycheckbox"><label>' '<input checked name="composers" type="checkbox" value="P"> ' "Paul McCartney</label></div>", ) def test_templates_with_forms(self): class UserRegistration(Form): username = CharField( max_length=10, help_text=("Good luck picking a username that doesn't already exist."), ) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data # There is full flexibility in displaying form fields in a template. # Just pass a Form instance to the template, and use "dot" access to # refer to individual fields. However, this flexibility comes with the # responsibility of displaying all the errors, including any that might # not be associated with a particular field. t = Template( "<form>" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" maxlength="10" required></label></p>' "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration({"username": "django"}, auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" '<ul class="errorlist"><li>This field is required.</li></ul><p>' "<label>Password: " '<input type="password" name="password1" required></label></p>' '<ul class="errorlist"><li>This field is required.</li></ul>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].label to output a field's label. 'label' for a field # can by specified by using the 'label' argument to a Field class. If # 'label' is not specified, Django will use the field name with # underscores converted to spaces, and the initial letter capitalized. t = Template( "<form>" "<p><label>{{ form.username.label }}: {{ form.username }}</label></p>" "<p><label>{{ form.password1.label }}: {{ form.password1 }}</label></p>" "<p><label>{{ form.password2.label }}: {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Username: " '<input type="text" name="username" maxlength="10" required></label></p>' "<p><label>Password1: " '<input type="password" name="password1" required></label></p>' "<p><label>Password2: " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].label_tag to output a field's label with a <label> # tag wrapped around it, but *only* if the given field has an "id" # attribute. Recall from above that passing the "auto_id" argument to a # Form gives each field an "id" attribute. t = Template( "<form>" "<p>{{ form.username.label_tag }} {{ form.username }}</p>" "<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required></p>' '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<p><label for="id_username">Username:</label>' '<input id="id_username" type="text" name="username" maxlength="10" ' "required></p>" '<p><label for="id_password1">Password1:</label>' '<input type="password" name="password1" id="id_password1" required></p>' '<p><label for="id_password2">Password2:</label>' '<input type="password" name="password2" id="id_password2" required></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].legend_tag to output a field's label with a <legend> # tag wrapped around it, but *only* if the given field has an "id" # attribute. Recall from above that passing the "auto_id" argument to a # Form gives each field an "id" attribute. t = Template( "<form>" "<p>{{ form.username.legend_tag }} {{ form.username }}</p>" "<p>{{ form.password1.legend_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.legend_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required></p>' '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) f = UserRegistration(auto_id="id_%s") self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<p><legend for="id_username">Username:</legend>' '<input id="id_username" type="text" name="username" maxlength="10" ' "required></p>" '<p><legend for="id_password1">Password1:</legend>' '<input type="password" name="password1" id="id_password1" required></p>' '<p><legend for="id_password2">Password2:</legend>' '<input type="password" name="password2" id="id_password2" required></p>' '<input type="submit" required>' "</form>", ) # Use form.[field].help_text to output a field's help text. If the # given field does not have help text, nothing will be output. t = Template( "<form>" "<p>{{ form.username.label_tag }} {{ form.username }}<br>" "{{ form.username.help_text }}</p>" "<p>{{ form.password1.label_tag }} {{ form.password1 }}</p>" "<p>{{ form.password2.label_tag }} {{ form.password2 }}</p>" '<input type="submit" required>' "</form>" ) f = UserRegistration(auto_id=False) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p>Username: " '<input type="text" name="username" maxlength="10" required><br>' "Good luck picking a username that doesn&#x27;t already exist.</p>" '<p>Password1: <input type="password" name="password1" required></p>' '<p>Password2: <input type="password" name="password2" required></p>' '<input type="submit" required>' "</form>", ) self.assertEqual( Template("{{ form.password1.help_text }}").render(Context({"form": f})), "", ) # To display the errors that aren't associated with a particular field # e.g. the errors caused by Form.clean() -- use # {{ form.non_field_errors }} in the template. If used on its own, it # is displayed as a <ul> (or an empty string, if the list of errors is # empty). t = Template( "<form>" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) f = UserRegistration( {"username": "django", "password1": "foo", "password2": "bar"}, auto_id=False, ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) t = Template( "<form>" "{{ form.non_field_errors }}" "{{ form.username.errors.as_ul }}" "<p><label>Your username: {{ form.username }}</label></p>" "{{ form.password1.errors.as_ul }}" "<p><label>Password: {{ form.password1 }}</label></p>" "{{ form.password2.errors.as_ul }}" "<p><label>Password (again): {{ form.password2 }}</label></p>" '<input type="submit" required>' "</form>" ) self.assertHTMLEqual( t.render(Context({"form": f})), "<form>" '<ul class="errorlist nonfield">' "<li>Please make sure your passwords match.</li></ul>" "<p><label>Your username: " '<input type="text" name="username" value="django" maxlength="10" required>' "</label></p>" "<p><label>Password: " '<input type="password" name="password1" required></label></p>' "<p><label>Password (again): " '<input type="password" name="password2" required></label></p>' '<input type="submit" required>' "</form>", ) def test_basic_processing_in_view(self): class UserRegistration(Form): username = CharField(max_length=10) password1 = CharField(widget=PasswordInput) password2 = CharField(widget=PasswordInput) def clean(self): if ( self.cleaned_data.get("password1") and self.cleaned_data.get("password2") and self.cleaned_data["password1"] != self.cleaned_data["password2"] ): raise ValidationError("Please make sure your passwords match.") return self.cleaned_data def my_function(method, post_data): if method == "POST": form = UserRegistration(post_data, auto_id=False) else: form = UserRegistration(auto_id=False) if form.is_valid(): return "VALID: %r" % sorted(form.cleaned_data.items()) t = Template( '<form method="post">' "{{ form }}" '<input type="submit" required>' "</form>" ) return t.render(Context({"form": form})) # GET with an empty form and no errors. self.assertHTMLEqual( my_function("GET", {}), '<form method="post">' "<div>Username:" '<input type="text" name="username" maxlength="10" required></div>' "<div>Password1:" '<input type="password" name="password1" required></div>' "<div>Password2:" '<input type="password" name="password2" required></div>' '<input type="submit" required>' "</form>", ) # POST with erroneous data, a redisplayed form, with errors. self.assertHTMLEqual( my_function( "POST", { "username": "this-is-a-long-username", "password1": "foo", "password2": "bar", }, ), '<form method="post">' '<ul class="errorlist nonfield">' "<li>Please make sure your passwords match.</li></ul>" '<div>Username:<ul class="errorlist">' "<li>Ensure this value has at most 10 characters (it has 23).</li></ul>" '<input type="text" name="username" ' 'value="this-is-a-long-username" maxlength="10" required></div>' "<div>Password1:" '<input type="password" name="password1" required></div>' "<div>Password2:" '<input type="password" name="password2" required></div>' '<input type="submit" required>' "</form>", ) # POST with valid data (the success message). self.assertEqual( my_function( "POST", { "username": "adrian", "password1": "secret", "password2": "secret", }, ), "VALID: [('password1', 'secret'), ('password2', 'secret'), " "('username', 'adrian')]", ) class OverrideTests(SimpleTestCase): @override_settings(FORM_RENDERER="forms_tests.tests.test_forms.CustomRenderer") def test_custom_renderer_template_name(self): class Person(Form): first_name = CharField() get_default_renderer.cache_clear() t = Template("{{ form }}") html = t.render(Context({"form": Person()})) expected = """ <div class="fieldWrapper"><label for="id_first_name">First name:</label> <input type="text" name="first_name" required id="id_first_name"></div> """ self.assertHTMLEqual(html, expected) get_default_renderer.cache_clear() def test_per_form_template_name(self): class Person(Form): first_name = CharField() template_name = "forms_tests/form_snippet.html" t = Template("{{ form }}") html = t.render(Context({"form": Person()})) expected = """ <div class="fieldWrapper"><label for="id_first_name">First name:</label> <input type="text" name="first_name" required id="id_first_name"></div> """ self.assertHTMLEqual(html, expected) def test_errorlist_override(self): class CustomErrorList(ErrorList): template_name = "forms_tests/error.html" class CommentForm(Form): name = CharField(max_length=50, required=False) email = EmailField() comment = CharField() data = {"email": "invalid"} f = CommentForm(data, auto_id=False, error_class=CustomErrorList) self.assertHTMLEqual( f.as_p(), '<p>Name: <input type="text" name="name" maxlength="50"></p>' '<div class="errorlist">' '<div class="error">Enter a valid email address.</div></div>' '<p>Email: <input type="email" name="email" value="invalid" required></p>' '<div class="errorlist">' '<div class="error">This field is required.</div></div>' '<p>Comment: <input type="text" name="comment" required></p>', ) def test_cyclic_context_boundfield_render(self): class FirstNameForm(Form): first_name = CharField() template_name_label = "forms_tests/cyclic_context_boundfield_render.html" f = FirstNameForm() try: f.render() except RecursionError: self.fail("Cyclic reference in BoundField.render().") def test_legend_tag(self): class CustomFrameworkForm(FrameworkForm): template_name = "forms_tests/legend_test.html" required_css_class = "required" f = CustomFrameworkForm() self.assertHTMLEqual( str(f), '<label for="id_name" class="required">Name:</label>' '<legend class="required">Language:</legend>', ) class DeprecationTests(SimpleTestCase): def test_warning(self): from django.forms.utils import DEFAULT_TEMPLATE_DEPRECATION_MSG with isolate_lru_cache(get_default_renderer), self.settings( FORM_RENDERER="django.forms.renderers.DjangoTemplates" ), self.assertRaisesMessage( RemovedInDjango50Warning, DEFAULT_TEMPLATE_DEPRECATION_MSG ): form = Person() str(form)
205dd9ec1f0e8f8eff77d77c7705f9df52f6b0fac11f740f8d9ac102d6635f58
from datetime import datetime, time from django.template.defaultfilters import date from django.test import SimpleTestCase from django.utils import timezone, translation from ..utils import setup from .timezone_utils import TimezoneTestCase class DateTests(TimezoneTestCase): @setup({"date01": '{{ d|date:"m" }}'}) def test_date01(self): output = self.engine.render_to_string("date01", {"d": datetime(2008, 1, 1)}) self.assertEqual(output, "01") @setup({"date02": "{{ d|date }}"}) def test_date02(self): output = self.engine.render_to_string("date02", {"d": datetime(2008, 1, 1)}) self.assertEqual(output, "Jan. 1, 2008") @setup({"date02_l10n": "{{ d|date }}"}) def test_date02_l10n(self): """Without arg, the active language's DATE_FORMAT is used.""" with translation.override("fr"): output = self.engine.render_to_string( "date02_l10n", {"d": datetime(2008, 1, 1)} ) self.assertEqual(output, "1 janvier 2008") @setup({"date03": '{{ d|date:"m" }}'}) def test_date03(self): """ #9520: Make sure |date doesn't blow up on non-dates """ output = self.engine.render_to_string("date03", {"d": "fail_string"}) self.assertEqual(output, "") # ISO date formats @setup({"date04": '{{ d|date:"o" }}'}) def test_date04(self): output = self.engine.render_to_string("date04", {"d": datetime(2008, 12, 29)}) self.assertEqual(output, "2009") @setup({"date05": '{{ d|date:"o" }}'}) def test_date05(self): output = self.engine.render_to_string("date05", {"d": datetime(2010, 1, 3)}) self.assertEqual(output, "2009") # Timezone name @setup({"date06": '{{ d|date:"e" }}'}) def test_date06(self): output = self.engine.render_to_string( "date06", {"d": datetime(2009, 3, 12, tzinfo=timezone.get_fixed_timezone(30))}, ) self.assertEqual(output, "+0030") @setup({"date07": '{{ d|date:"e" }}'}) def test_date07(self): output = self.engine.render_to_string("date07", {"d": datetime(2009, 3, 12)}) self.assertEqual(output, "") # #19370: Make sure |date doesn't blow up on a midnight time object @setup({"date08": '{{ t|date:"H:i" }}'}) def test_date08(self): output = self.engine.render_to_string("date08", {"t": time(0, 1)}) self.assertEqual(output, "00:01") @setup({"date09": '{{ t|date:"H:i" }}'}) def test_date09(self): output = self.engine.render_to_string("date09", {"t": time(0, 0)}) self.assertEqual(output, "00:00") @setup({"datelazy": '{{ t|date:_("H:i") }}'}) def test_date_lazy(self): output = self.engine.render_to_string("datelazy", {"t": time(0, 0)}) self.assertEqual(output, "00:00") class FunctionTests(SimpleTestCase): def test_date(self): self.assertEqual(date(datetime(2005, 12, 29), "d F Y"), "29 December 2005") def test_no_args(self): self.assertEqual(date(""), "") self.assertEqual(date(None), "") def test_escape_characters(self): self.assertEqual(date(datetime(2005, 12, 29), r"jS \o\f F"), "29th of December")
3adde9a74376fa27a270157369a9b44db5b691c1ec71eb0bb8638151258b6648
import unittest from contextlib import contextmanager from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.db import NotSupportedError, connection from django.test import TestCase, override_settings @contextmanager def get_connection(): new_connection = connection.copy() yield new_connection new_connection.close() @override_settings(DEBUG=True) @unittest.skipUnless(connection.vendor == "mysql", "MySQL tests") class IsolationLevelTests(TestCase): read_committed = "read committed" repeatable_read = "repeatable read" isolation_values = { level: level.upper() for level in (read_committed, repeatable_read) } @classmethod def setUpClass(cls): super().setUpClass() configured_isolation_level = ( connection.isolation_level or cls.isolation_values[cls.repeatable_read] ) cls.configured_isolation_level = configured_isolation_level.upper() cls.other_isolation_level = ( cls.read_committed if configured_isolation_level != cls.isolation_values[cls.read_committed] else cls.repeatable_read ) @staticmethod def get_isolation_level(connection): with connection.cursor() as cursor: cursor.execute( "SHOW VARIABLES " "WHERE variable_name IN ('transaction_isolation', 'tx_isolation')" ) return cursor.fetchone()[1].replace("-", " ") def test_auto_is_null_auto_config(self): query = "set sql_auto_is_null = 0" connection.init_connection_state() last_query = connection.queries[-1]["sql"].lower() if connection.features.is_sql_auto_is_null_enabled: self.assertIn(query, last_query) else: self.assertNotIn(query, last_query) def test_connect_isolation_level(self): self.assertEqual( self.get_isolation_level(connection), self.configured_isolation_level ) def test_setting_isolation_level(self): with get_connection() as new_connection: new_connection.settings_dict["OPTIONS"][ "isolation_level" ] = self.other_isolation_level self.assertEqual( self.get_isolation_level(new_connection), self.isolation_values[self.other_isolation_level], ) def test_uppercase_isolation_level(self): # Upper case values are also accepted in 'isolation_level'. with get_connection() as new_connection: new_connection.settings_dict["OPTIONS"][ "isolation_level" ] = self.other_isolation_level.upper() self.assertEqual( self.get_isolation_level(new_connection), self.isolation_values[self.other_isolation_level], ) def test_default_isolation_level(self): # If not specified in settings, the default is read committed. with get_connection() as new_connection: new_connection.settings_dict["OPTIONS"].pop("isolation_level", None) self.assertEqual( self.get_isolation_level(new_connection), self.isolation_values[self.read_committed], ) def test_isolation_level_validation(self): new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["isolation_level"] = "xxx" msg = ( "Invalid transaction isolation level 'xxx' specified.\n" "Use one of 'read committed', 'read uncommitted', " "'repeatable read', 'serializable', or None." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): new_connection.cursor() @unittest.skipUnless(connection.vendor == "mysql", "MySQL tests") class Tests(TestCase): @mock.patch.object(connection, "get_database_version") def test_check_database_version_supported(self, mocked_get_database_version): if connection.mysql_is_mariadb: mocked_get_database_version.return_value = (10, 3) msg = "MariaDB 10.4 or later is required (found 10.3)." else: mocked_get_database_version.return_value = (5, 6) msg = "MySQL 5.7 or later is required (found 5.6)." with self.assertRaisesMessage(NotSupportedError, msg): connection.check_database_version_supported() self.assertTrue(mocked_get_database_version.called)
abc910feb9235c4d9f7d837525fb7b4fbc3ba756bbadd8c8236fb6adc910d8ab
import copy import unittest from io import StringIO from unittest import mock from django.core.exceptions import ImproperlyConfigured from django.db import ( DEFAULT_DB_ALIAS, DatabaseError, NotSupportedError, connection, connections, ) from django.db.backends.base.base import BaseDatabaseWrapper from django.test import TestCase, override_settings @unittest.skipUnless(connection.vendor == "postgresql", "PostgreSQL tests") class Tests(TestCase): databases = {"default", "other"} def test_nodb_cursor(self): """ The _nodb_cursor() fallbacks to the default connection database when access to the 'postgres' database is not granted. """ orig_connect = BaseDatabaseWrapper.connect def mocked_connect(self): if self.settings_dict["NAME"] is None: raise DatabaseError() return orig_connect(self) with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) self.assertIsNone(cursor.db.settings_dict["NAME"]) self.assertIs(cursor.closed, True) self.assertIsNone(cursor.db.connection) # Now assume the 'postgres' db isn't available msg = ( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' " "database and will use the first PostgreSQL database instead." ) with self.assertWarnsMessage(RuntimeWarning, msg): with mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ): with mock.patch.object( connection, "settings_dict", {**connection.settings_dict, "NAME": "postgres"}, ): with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) self.assertIs(cursor.closed, True) self.assertIsNone(cursor.db.connection) self.assertIsNotNone(cursor.db.settings_dict["NAME"]) self.assertEqual( cursor.db.settings_dict["NAME"], connections["other"].settings_dict["NAME"] ) # Cursor is yielded only for the first PostgreSQL database. with self.assertWarnsMessage(RuntimeWarning, msg): with mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ): with connection._nodb_cursor() as cursor: self.assertIs(cursor.closed, False) self.assertIsNotNone(cursor.db.connection) def test_nodb_cursor_raises_postgres_authentication_failure(self): """ _nodb_cursor() re-raises authentication failure to the 'postgres' db when other connection to the PostgreSQL database isn't available. """ def mocked_connect(self): raise DatabaseError() def mocked_all(self): test_connection = copy.copy(connections[DEFAULT_DB_ALIAS]) test_connection.settings_dict = copy.deepcopy(connection.settings_dict) test_connection.settings_dict["NAME"] = "postgres" return [test_connection] msg = ( "Normally Django will use a connection to the 'postgres' database " "to avoid running initialization queries against the production " "database when it's not needed (for example, when running tests). " "Django was unable to create a connection to the 'postgres' " "database and will use the first PostgreSQL database instead." ) with self.assertWarnsMessage(RuntimeWarning, msg): mocker_connections_all = mock.patch( "django.utils.connection.BaseConnectionHandler.all", side_effect=mocked_all, autospec=True, ) mocker_connect = mock.patch( "django.db.backends.base.base.BaseDatabaseWrapper.connect", side_effect=mocked_connect, autospec=True, ) with mocker_connections_all, mocker_connect: with self.assertRaises(DatabaseError): with connection._nodb_cursor(): pass def test_nodb_cursor_reraise_exceptions(self): with self.assertRaisesMessage(DatabaseError, "exception"): with connection._nodb_cursor(): raise DatabaseError("exception") def test_database_name_too_long(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() max_name_length = connection.ops.max_name_length() settings["NAME"] = "a" + (max_name_length * "a") msg = ( "The database name '%s' (%d characters) is longer than " "PostgreSQL's limit of %s characters. Supply a shorter NAME in " "settings.DATABASES." ) % (settings["NAME"], max_name_length + 1, max_name_length) with self.assertRaisesMessage(ImproperlyConfigured, msg): DatabaseWrapper(settings).get_connection_params() def test_database_name_empty(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["NAME"] = "" msg = ( "settings.DATABASES is improperly configured. Please supply the " "NAME or OPTIONS['service'] value." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): DatabaseWrapper(settings).get_connection_params() def test_service_name(self): from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["OPTIONS"] = {"service": "my_service"} settings["NAME"] = "" params = DatabaseWrapper(settings).get_connection_params() self.assertEqual(params["service"], "my_service") self.assertNotIn("database", params) def test_service_name_default_db(self): # None is used to connect to the default 'postgres' db. from django.db.backends.postgresql.base import DatabaseWrapper settings = connection.settings_dict.copy() settings["NAME"] = None settings["OPTIONS"] = {"service": "django_test"} params = DatabaseWrapper(settings).get_connection_params() self.assertEqual(params["database"], "postgres") self.assertNotIn("service", params) def test_connect_and_rollback(self): """ PostgreSQL shouldn't roll back SET TIME ZONE, even if the first transaction is rolled back (#17062). """ new_connection = connection.copy() try: # Ensure the database default time zone is different than # the time zone in new_connection.settings_dict. We can # get the default time zone by reset & show. with new_connection.cursor() as cursor: cursor.execute("RESET TIMEZONE") cursor.execute("SHOW TIMEZONE") db_default_tz = cursor.fetchone()[0] new_tz = "Europe/Paris" if db_default_tz == "UTC" else "UTC" new_connection.close() # Invalidate timezone name cache, because the setting_changed # handler cannot know about new_connection. del new_connection.timezone_name # Fetch a new connection with the new_tz as default # time zone, run a query and rollback. with self.settings(TIME_ZONE=new_tz): new_connection.set_autocommit(False) new_connection.rollback() # Now let's see if the rollback rolled back the SET TIME ZONE. with new_connection.cursor() as cursor: cursor.execute("SHOW TIMEZONE") tz = cursor.fetchone()[0] self.assertEqual(new_tz, tz) finally: new_connection.close() def test_connect_non_autocommit(self): """ The connection wrapper shouldn't believe that autocommit is enabled after setting the time zone when AUTOCOMMIT is False (#21452). """ new_connection = connection.copy() new_connection.settings_dict["AUTOCOMMIT"] = False try: # Open a database connection. with new_connection.cursor(): self.assertFalse(new_connection.get_autocommit()) finally: new_connection.close() def test_connect_isolation_level(self): """ The transaction level can be configured with DATABASES ['OPTIONS']['isolation_level']. """ from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE as serializable # Since this is a django.test.TestCase, a transaction is in progress # and the isolation level isn't reported as 0. This test assumes that # PostgreSQL is configured with the default isolation level. # Check the level on the psycopg2 connection, not the Django wrapper. self.assertIsNone(connection.connection.isolation_level) new_connection = connection.copy() new_connection.settings_dict["OPTIONS"]["isolation_level"] = serializable try: # Start a transaction so the isolation level isn't reported as 0. new_connection.set_autocommit(False) # Check the level on the psycopg2 connection, not the Django wrapper. self.assertEqual(new_connection.connection.isolation_level, serializable) finally: new_connection.close() def test_connect_no_is_usable_checks(self): new_connection = connection.copy() try: with mock.patch.object(new_connection, "is_usable") as is_usable: new_connection.connect() is_usable.assert_not_called() finally: new_connection.close() def _select(self, val): with connection.cursor() as cursor: cursor.execute("SELECT %s", (val,)) return cursor.fetchone()[0] def test_select_ascii_array(self): a = ["awef"] b = self._select(a) self.assertEqual(a[0], b[0]) def test_select_unicode_array(self): a = ["ᄲawef"] b = self._select(a) self.assertEqual(a[0], b[0]) def test_lookup_cast(self): from django.db.backends.postgresql.operations import DatabaseOperations do = DatabaseOperations(connection=None) lookups = ( "iexact", "contains", "icontains", "startswith", "istartswith", "endswith", "iendswith", "regex", "iregex", ) for lookup in lookups: with self.subTest(lookup=lookup): self.assertIn("::text", do.lookup_cast(lookup)) for lookup in lookups: for field_type in ("CICharField", "CIEmailField", "CITextField"): with self.subTest(lookup=lookup, field_type=field_type): self.assertIn( "::citext", do.lookup_cast(lookup, internal_type=field_type) ) def test_correct_extraction_psycopg2_version(self): from django.db.backends.postgresql.base import psycopg2_version with mock.patch("psycopg2.__version__", "4.2.1 (dt dec pq3 ext lo64)"): self.assertEqual(psycopg2_version(), (4, 2, 1)) with mock.patch("psycopg2.__version__", "4.2b0.dev1 (dt dec pq3 ext lo64)"): self.assertEqual(psycopg2_version(), (4, 2)) @override_settings(DEBUG=True) def test_copy_cursors(self): out = StringIO() copy_expert_sql = "COPY django_session TO STDOUT (FORMAT CSV, HEADER)" with connection.cursor() as cursor: cursor.copy_expert(copy_expert_sql, out) cursor.copy_to(out, "django_session") self.assertEqual( [q["sql"] for q in connection.queries], [copy_expert_sql, "COPY django_session TO STDOUT"], ) def test_get_database_version(self): new_connection = connection.copy() new_connection.pg_version = 110009 self.assertEqual(new_connection.get_database_version(), (11, 9)) @mock.patch.object(connection, "get_database_version", return_value=(11,)) def test_check_database_version_supported(self, mocked_get_database_version): msg = "PostgreSQL 12 or later is required (found 11)." with self.assertRaisesMessage(NotSupportedError, msg): connection.check_database_version_supported() self.assertTrue(mocked_get_database_version.called)
d11d34292b0acebe632da5169cb3426fdfab5df33aa7c762568552b237ac7d24
# Django documentation build configuration file, created by # sphinx-quickstart on Thu Mar 27 09:06:53 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't picklable (module imports are okay, they're removed automatically). # # All configuration values have a default; values that are commented out # serve to show the default. import sys from os.path import abspath, dirname, join # Workaround for sphinx-build recursion limit overflow: # pickle.dump(doctree, f, pickle.HIGHEST_PROTOCOL) # RuntimeError: maximum recursion depth exceeded while pickling an object # # Python's default allowed recursion depth is 1000 but this isn't enough for # building docs/ref/settings.txt sometimes. # https://groups.google.com/g/sphinx-dev/c/MtRf64eGtv4/discussion sys.setrecursionlimit(2000) # Make sure we get the version of this copy of Django sys.path.insert(1, dirname(dirname(abspath(__file__)))) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(abspath(join(dirname(__file__), "_ext"))) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. needs_sphinx = "1.6.0" # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "djangodocs", "sphinx.ext.extlinks", "sphinx.ext.intersphinx", "sphinx.ext.viewcode", "sphinx.ext.autosectionlabel", ] # AutosectionLabel settings. # Uses a <page>:<label> schema which doesn't work for duplicate sub-section # labels, so set max depth. autosectionlabel_prefix_document = True autosectionlabel_maxdepth = 2 # Linkcheck settings. linkcheck_ignore = [ # Special-use addresses and domain names. (RFC 6761/6890) r"^https?://(?:127\.0\.0\.1|\[::1\])(?::\d+)?/", r"^https?://(?:[^/\.]+\.)*example\.(?:com|net|org)(?::\d+)?/", r"^https?://(?:[^/\.]+\.)*(?:example|invalid|localhost|test)(?::\d+)?/", # Pages that are inaccessible because they require authentication. r"^https://github\.com/[^/]+/[^/]+/fork", r"^https://code\.djangoproject\.com/github/login", r"^https://code\.djangoproject\.com/newticket", r"^https://(?:code|www)\.djangoproject\.com/admin/", r"^https://www\.djangoproject\.com/community/add/blogs/", r"^https://www\.google\.com/webmasters/tools/ping", r"^https://search\.google\.com/search-console/welcome", # Fragments used to dynamically switch content or populate fields. r"^https://web\.libera\.chat/#", r"^https://github\.com/[^#]+#L\d+-L\d+$", r"^https://help\.apple\.com/itc/podcasts_connect/#/itc", # Anchors on certain pages with missing a[name] attributes. r"^https://tools\.ietf\.org/html/rfc1123\.html#section-", ] # Spelling check needs an additional module that is not installed by default. # Add it only if spelling check is requested so docs can be generated without it. if "spelling" in sys.argv: extensions.append("sphinxcontrib.spelling") # Spelling language. spelling_lang = "en_US" # Location of word list. spelling_word_list_filename = "spelling_wordlist" spelling_warning = True # Add any paths that contain templates here, relative to this directory. # templates_path = [] # The suffix of source filenames. source_suffix = ".txt" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "contents" # General substitutions. project = "Django" copyright = "Django Software Foundation and contributors" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = "4.2" # The full version, including alpha/beta/rc tags. try: from django import VERSION, get_version except ImportError: release = version else: def django_release(): pep440ver = get_version() if VERSION[3:5] == ("alpha", 0) and "dev" not in pep440ver: return pep440ver + ".dev" return pep440ver release = django_release() # The "development version" of Django django_next_version = "4.2" extlinks = { "bpo": ("https://bugs.python.org/issue?@action=redirect&bpo=%s", "bpo-"), "commit": ("https://github.com/django/django/commit/%s", ""), "cve": ("https://nvd.nist.gov/vuln/detail/CVE-%s", "CVE-"), # A file or directory. GitHub redirects from blob to tree if needed. "source": ("https://github.com/django/django/blob/main/%s", ""), "ticket": ("https://code.djangoproject.com/ticket/%s", "#"), } # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # language = None # Location for .po/.mo translation files used when language is set locale_dirs = ["locale/"] # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = "%B %d, %Y" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build", "_theme", "requirements.txt"] # The reST default role (used for this markup: `text`) to use for all documents. default_role = "default-role-error" # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "trac" # Links to Python's docs should reference the most recent version of the 3.x # branch, which is located at this URL. intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), "sphinx": ("https://www.sphinx-doc.org/en/master/", None), "psycopg2": ("https://www.psycopg.org/docs/", None), } # Python's docs don't change every week. intersphinx_cache_limit = 90 # days # The 'versionadded' and 'versionchanged' directives are overridden. suppress_warnings = ["app.add_directive"] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "djangodocs" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ["_theme"] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ["_static"] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = "%b %d, %Y" # Content template for the index page. # html_index = '' # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = "Djangodoc" modindex_common_prefix = ["django."] # Appended to every page rst_epilog = """ .. |django-users| replace:: :ref:`django-users <django-users-mailing-list>` .. |django-developers| replace:: :ref:`django-developers <django-developers-mailing-list>` .. |django-announce| replace:: :ref:`django-announce <django-announce-mailing-list>` .. |django-updates| replace:: :ref:`django-updates <django-updates-mailing-list>` """ # NOQA # -- Options for LaTeX output -------------------------------------------------- # Use XeLaTeX for Unicode support. latex_engine = "xelatex" latex_use_xindy = False # Set font for CJK and fallbacks for unicode characters. latex_elements = { "fontpkg": r""" \setmainfont{Symbola} """, "preamble": r""" \usepackage{newunicodechar} \usepackage[UTF8]{ctex} \newunicodechar{π}{\ensuremath{\pi}} \newunicodechar{≤}{\ensuremath{\le}} \newunicodechar{≥}{\ensuremath{\ge}} \newunicodechar{♥}{\ensuremath{\heartsuit}} \newunicodechar{…}{\ensuremath{\ldots}} """, } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). # latex_documents = [] latex_documents = [ ( "contents", "django.tex", "Django Documentation", "Django Software Foundation", "manual", ), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ( "ref/django-admin", "django-admin", "Utility script for the Django web framework", ["Django Software Foundation"], 1, ) ] # -- Options for Texinfo output ------------------------------------------------ # List of tuples (startdocname, targetname, title, author, dir_entry, # description, category, toctree_only) texinfo_documents = [ ( master_doc, "django", "", "", "Django", "Documentation of the Django framework", "Web development", False, ) ] # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project epub_author = "Django Software Foundation" epub_publisher = "Django Software Foundation" epub_copyright = copyright # The basename for the epub file. It defaults to the project name. # epub_basename = 'Django' # The HTML theme for the epub output. Since the default themes are not optimized # for small screen space, using the same theme for HTML and epub output is # usually not wise. This defaults to 'epub', a theme designed to save visual # space. epub_theme = "djangodocs-epub" # The language of the text. It defaults to the language option # or en if the language is not set. # epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. # epub_scheme = '' # The unique identifier of the text. This can be an ISBN number # or the project homepage. # epub_identifier = '' # A unique identification for the text. # epub_uid = '' # A tuple containing the cover image and cover page html template filenames. epub_cover = ("", "epub-cover.html") # A sequence of (type, uri, title) tuples for the guide element of content.opf. # epub_guide = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. # epub_post_files = [] # A list of files that should not be packed into the epub file. # epub_exclude_files = [] # The depth of the table of contents in toc.ncx. # epub_tocdepth = 3 # Allow duplicate toc entries. # epub_tocdup = True # Choose between 'default' and 'includehidden'. # epub_tocscope = 'default' # Fix unsupported image types using the PIL. # epub_fix_images = False # Scale large images. # epub_max_image_width = 0 # How to display URL addresses: 'footnote', 'no', or 'inline'. # epub_show_urls = 'inline' # If false, no index is generated. # epub_use_index = True
acc8e10e807f3091d83ccd038fbe770bb542a1225ecb586db3c02948973c2d51
import operator from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): empty_fetchmany_value = () allows_group_by_pk = True related_fields_match_type = True # MySQL doesn't support sliced subqueries with IN/ALL/ANY/SOME. allow_sliced_subqueries_with_in = False has_select_for_update = True supports_forward_references = False supports_regex_backreferencing = False supports_date_lookup_using_string = False supports_timezones = False requires_explicit_null_ordering_when_grouping = True can_release_savepoints = True atomic_transactions = False can_clone_databases = True supports_temporal_subtraction = True supports_select_intersection = False supports_select_difference = False supports_slicing_ordering_in_compound = True supports_index_on_text_field = False supports_update_conflicts = True create_test_procedure_without_params_sql = """ CREATE PROCEDURE test_procedure () BEGIN DECLARE V_I INTEGER; SET V_I = 1; END; """ create_test_procedure_with_int_param_sql = """ CREATE PROCEDURE test_procedure (P_I INTEGER) BEGIN DECLARE V_I INTEGER; SET V_I = P_I; END; """ # Neither MySQL nor MariaDB support partial indexes. supports_partial_indexes = False # COLLATE must be wrapped in parentheses because MySQL treats COLLATE as an # indexed expression. collate_as_index_expression = True supports_order_by_nulls_modifier = False order_by_nulls_first = True supports_logical_xor = True @cached_property def minimum_database_version(self): if self.connection.mysql_is_mariadb: return (10, 4) else: return (5, 7) @cached_property def bare_select_suffix(self): if not self.connection.mysql_is_mariadb and self.connection.mysql_version < ( 8, ): return " FROM DUAL" return "" @cached_property def test_collations(self): charset = "utf8" if self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 6, ): # utf8 is an alias for utf8mb3 in MariaDB 10.6+. charset = "utf8mb3" return { "ci": f"{charset}_general_ci", "non_default": f"{charset}_esperanto_ci", "swedish_ci": f"{charset}_swedish_ci", } test_now_utc_template = "UTC_TIMESTAMP" @cached_property def django_test_skips(self): skips = { "This doesn't work on MySQL.": { "db_functions.comparison.test_greatest.GreatestTests." "test_coalesce_workaround", "db_functions.comparison.test_least.LeastTests." "test_coalesce_workaround", }, "Running on MySQL requires utf8mb4 encoding (#18392).": { "model_fields.test_textfield.TextFieldTests.test_emoji", "model_fields.test_charfield.TestCharField.test_emoji", }, "MySQL doesn't support functional indexes on a function that " "returns JSON": { "schema.tests.SchemaTests.test_func_index_json_key_transform", }, "MySQL supports multiplying and dividing DurationFields by a " "scalar value but it's not implemented (#25287).": { "expressions.tests.FTimeDeltaTests.test_durationfield_multiply_divide", }, } if "ONLY_FULL_GROUP_BY" in self.connection.sql_mode: skips.update( { "GROUP BY optimization does not work properly when " "ONLY_FULL_GROUP_BY mode is enabled on MySQL, see #31331.": { "aggregation.tests.AggregateTestCase." "test_aggregation_subquery_annotation_multivalued", "annotations.tests.NonAggregateAnnotationTestCase." "test_annotation_aggregate_with_m2o", }, } ) if not self.connection.mysql_is_mariadb and self.connection.mysql_version < ( 8, ): skips.update( { "Casting to datetime/time is not supported by MySQL < 8.0. " "(#30224)": { "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_time_from_python", "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_datetime_from_python", }, "MySQL < 8.0 returns string type instead of datetime/time. " "(#30224)": { "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_time_from_database", "aggregation.tests.AggregateTestCase." "test_aggregation_default_using_datetime_from_database", }, } ) if self.connection.mysql_is_mariadb and ( 10, 4, 3, ) < self.connection.mysql_version < (10, 5, 2): skips.update( { "https://jira.mariadb.org/browse/MDEV-19598": { "schema.tests.SchemaTests." "test_alter_not_unique_field_to_primary_key", }, } ) if self.connection.mysql_is_mariadb and ( 10, 4, 12, ) < self.connection.mysql_version < (10, 5): skips.update( { "https://jira.mariadb.org/browse/MDEV-22775": { "schema.tests.SchemaTests." "test_alter_pk_with_self_referential_field", }, } ) if not self.supports_explain_analyze: skips.update( { "MariaDB and MySQL >= 8.0.18 specific.": { "queries.test_explain.ExplainTests.test_mysql_analyze", }, } ) return skips @cached_property def _mysql_storage_engine(self): "Internal method used in Django tests. Don't rely on this from your code" return self.connection.mysql_server_data["default_storage_engine"] @cached_property def allows_auto_pk_0(self): """ Autoincrement primary key can be set to 0 if it doesn't generate new autoincrement values. """ return "NO_AUTO_VALUE_ON_ZERO" in self.connection.sql_mode @cached_property def update_can_self_select(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 3, 2, ) @cached_property def can_introspect_foreign_keys(self): "Confirm support for introspected foreign keys" return self._mysql_storage_engine != "MyISAM" @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "BinaryField": "TextField", "BooleanField": "IntegerField", "DurationField": "BigIntegerField", "GenericIPAddressField": "CharField", } @cached_property def can_return_columns_from_insert(self): return self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 10, 5, 0, ) can_return_rows_from_bulk_insert = property( operator.attrgetter("can_return_columns_from_insert") ) @cached_property def has_zoneinfo_database(self): return self.connection.mysql_server_data["has_zoneinfo_database"] @cached_property def is_sql_auto_is_null_enabled(self): return self.connection.mysql_server_data["sql_auto_is_null"] @cached_property def supports_over_clause(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 2) supports_frame_range_fixed_distance = property( operator.attrgetter("supports_over_clause") ) @cached_property def supports_column_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) supports_table_check_constraints = property( operator.attrgetter("supports_column_check_constraints") ) @cached_property def can_introspect_check_constraints(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 16) @cached_property def has_select_for_update_skip_locked(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 6) return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_nowait(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (8, 0, 1) @cached_property def has_select_for_update_of(self): return ( not self.connection.mysql_is_mariadb and self.connection.mysql_version >= (8, 0, 1) ) @cached_property def supports_explain_analyze(self): return self.connection.mysql_is_mariadb or self.connection.mysql_version >= ( 8, 0, 18, ) @cached_property def supported_explain_formats(self): # Alias MySQL's TRADITIONAL to TEXT for consistency with other # backends. formats = {"JSON", "TEXT", "TRADITIONAL"} if not self.connection.mysql_is_mariadb and self.connection.mysql_version >= ( 8, 0, 16, ): formats.add("TREE") return formats @cached_property def supports_transactions(self): """ All storage engines except MyISAM support transactions. """ return self._mysql_storage_engine != "MyISAM" uses_savepoints = property(operator.attrgetter("supports_transactions")) can_release_savepoints = property(operator.attrgetter("supports_transactions")) @cached_property def ignores_table_name_case(self): return self.connection.mysql_server_data["lower_case_table_names"] @cached_property def supports_default_in_lead_lag(self): # To be added in https://jira.mariadb.org/browse/MDEV-12981. return not self.connection.mysql_is_mariadb @cached_property def supports_json_field(self): if self.connection.mysql_is_mariadb: return True return self.connection.mysql_version >= (5, 7, 8) @cached_property def can_introspect_json_field(self): if self.connection.mysql_is_mariadb: return self.supports_json_field and self.can_introspect_check_constraints return self.supports_json_field @cached_property def supports_index_column_ordering(self): if self._mysql_storage_engine != "InnoDB": return False if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 8) return self.connection.mysql_version >= (8, 0, 1) @cached_property def supports_expression_indexes(self): return ( not self.connection.mysql_is_mariadb and self._mysql_storage_engine != "MyISAM" and self.connection.mysql_version >= (8, 0, 13) ) @cached_property def can_rename_index(self): if self.connection.mysql_is_mariadb: return self.connection.mysql_version >= (10, 5, 2) return True
7bcbce0b4c0681feff8d29fe220621c2517afc414361cadf239c7fa590371332
import operator from django.db import InterfaceError from django.db.backends.base.features import BaseDatabaseFeatures from django.utils.functional import cached_property class DatabaseFeatures(BaseDatabaseFeatures): minimum_database_version = (12,) allows_group_by_selected_pks = True can_return_columns_from_insert = True can_return_rows_from_bulk_insert = True has_real_datatype = True has_native_uuid_field = True has_native_duration_field = True has_native_json_field = True can_defer_constraint_checks = True has_select_for_update = True has_select_for_update_nowait = True has_select_for_update_of = True has_select_for_update_skip_locked = True has_select_for_no_key_update = True can_release_savepoints = True supports_tablespaces = True supports_transactions = True can_introspect_materialized_views = True can_distinct_on_fields = True can_rollback_ddl = True supports_combined_alters = True nulls_order_largest = True closed_cursor_error_class = InterfaceError greatest_least_ignores_nulls = True can_clone_databases = True supports_temporal_subtraction = True supports_slicing_ordering_in_compound = True create_test_procedure_without_params_sql = """ CREATE FUNCTION test_procedure () RETURNS void AS $$ DECLARE V_I INTEGER; BEGIN V_I := 1; END; $$ LANGUAGE plpgsql;""" create_test_procedure_with_int_param_sql = """ CREATE FUNCTION test_procedure (P_I INTEGER) RETURNS void AS $$ DECLARE V_I INTEGER; BEGIN V_I := P_I; END; $$ LANGUAGE plpgsql;""" requires_casted_case_in_updates = True supports_over_clause = True only_supports_unbounded_with_preceding_and_following = True supports_aggregate_filter_clause = True supported_explain_formats = {"JSON", "TEXT", "XML", "YAML"} supports_deferrable_unique_constraints = True has_json_operators = True json_key_contains_list_matching_requires_list = True supports_update_conflicts = True supports_update_conflicts_with_target = True supports_covering_indexes = True can_rename_index = True test_collations = { "non_default": "sv-x-icu", "swedish_ci": "sv-x-icu", } test_now_utc_template = "STATEMENT_TIMESTAMP() AT TIME ZONE 'UTC'" django_test_skips = { "opclasses are PostgreSQL only.": { "indexes.tests.SchemaIndexesNotPostgreSQLTests." "test_create_index_ignores_opclasses", }, } @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "PositiveBigIntegerField": "BigIntegerField", "PositiveIntegerField": "IntegerField", "PositiveSmallIntegerField": "SmallIntegerField", } @cached_property def is_postgresql_13(self): return self.connection.pg_version >= 130000 @cached_property def is_postgresql_14(self): return self.connection.pg_version >= 140000 has_bit_xor = property(operator.attrgetter("is_postgresql_14")) supports_covering_spgist_indexes = property(operator.attrgetter("is_postgresql_14"))
54413bf8463dd49faca75700af848d69de19d522c000f656ed1a3ad00e8a3c67
from django.core.exceptions import FieldDoesNotExist from django.db import IntegrityError, connection, migrations, models, transaction from django.db.migrations.migration import Migration from django.db.migrations.operations.fields import FieldOperation from django.db.migrations.state import ModelState, ProjectState from django.db.models.functions import Abs from django.db.transaction import atomic from django.test import SimpleTestCase, override_settings, skipUnlessDBFeature from django.test.utils import CaptureQueriesContext from .models import FoodManager, FoodQuerySet, UnicodeModel from .test_base import OperationTestBase class Mixin: pass class OperationTests(OperationTestBase): """ Tests running the operations and making sure they do what they say they do. Each test looks at their state changing, and then their database operation - both forwards and backwards. """ def test_create_model(self): """ Tests the CreateModel operation. Most other tests use this operation as part of setup, so check failures here first. """ operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], ) self.assertEqual(operation.describe(), "Create model Pony") self.assertEqual(operation.migration_name_fragment, "pony") # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual(new_state.models["test_crmo", "pony"].name, "Pony") self.assertEqual(len(new_state.models["test_crmo", "pony"].fields), 2) # Test the database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["fields", "name"]) # And default manager not in set operation = migrations.CreateModel( "Foo", fields=[], managers=[("objects", models.Manager())] ) definition = operation.deconstruct() self.assertNotIn("managers", definition[2]) def test_create_model_with_duplicate_field_name(self): with self.assertRaisesMessage( ValueError, "Found duplicate value pink in CreateModel fields argument." ): migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.TextField()), ("pink", models.IntegerField(default=1)), ], ) def test_create_model_with_duplicate_base(self): message = "Found duplicate value test_crmo.pony in CreateModel bases argument." with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( "test_crmo.Pony", "test_crmo.Pony", ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( "test_crmo.Pony", "test_crmo.pony", ), ) message = ( "Found duplicate value migrations.unicodemodel in CreateModel bases " "argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, UnicodeModel, ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, "migrations.unicodemodel", ), ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( UnicodeModel, "migrations.UnicodeModel", ), ) message = ( "Found duplicate value <class 'django.db.models.base.Model'> in " "CreateModel bases argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( models.Model, models.Model, ), ) message = ( "Found duplicate value <class 'migrations.test_operations.Mixin'> in " "CreateModel bases argument." ) with self.assertRaisesMessage(ValueError, message): migrations.CreateModel( "Pony", fields=[], bases=( Mixin, Mixin, ), ) def test_create_model_with_duplicate_manager_name(self): with self.assertRaisesMessage( ValueError, "Found duplicate value objects in CreateModel managers argument.", ): migrations.CreateModel( "Pony", fields=[], managers=[ ("objects", models.Manager()), ("objects", models.Manager()), ], ) def test_create_model_with_unique_after(self): """ Tests the CreateModel operation directly followed by an AlterUniqueTogether (bug #22844 - sqlite remake issues) """ operation1 = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], ) operation2 = migrations.CreateModel( "Rider", [ ("id", models.AutoField(primary_key=True)), ("number", models.IntegerField(default=1)), ("pony", models.ForeignKey("test_crmoua.Pony", models.CASCADE)), ], ) operation3 = migrations.AlterUniqueTogether( "Rider", [ ("number", "pony"), ], ) # Test the database alteration project_state = ProjectState() self.assertTableNotExists("test_crmoua_pony") self.assertTableNotExists("test_crmoua_rider") with connection.schema_editor() as editor: new_state = project_state.clone() operation1.state_forwards("test_crmoua", new_state) operation1.database_forwards( "test_crmoua", editor, project_state, new_state ) project_state, new_state = new_state, new_state.clone() operation2.state_forwards("test_crmoua", new_state) operation2.database_forwards( "test_crmoua", editor, project_state, new_state ) project_state, new_state = new_state, new_state.clone() operation3.state_forwards("test_crmoua", new_state) operation3.database_forwards( "test_crmoua", editor, project_state, new_state ) self.assertTableExists("test_crmoua_pony") self.assertTableExists("test_crmoua_rider") def test_create_model_m2m(self): """ Test the creation of a model with a ManyToMany field and the auto-created "through" model. """ project_state = self.set_up_test_model("test_crmomm") operation = migrations.CreateModel( "Stable", [ ("id", models.AutoField(primary_key=True)), ("ponies", models.ManyToManyField("Pony", related_name="stables")), ], ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_crmomm", new_state) # Test the database alteration self.assertTableNotExists("test_crmomm_stable_ponies") with connection.schema_editor() as editor: operation.database_forwards("test_crmomm", editor, project_state, new_state) self.assertTableExists("test_crmomm_stable") self.assertTableExists("test_crmomm_stable_ponies") self.assertColumnNotExists("test_crmomm_stable", "ponies") # Make sure the M2M field actually works with atomic(): Pony = new_state.apps.get_model("test_crmomm", "Pony") Stable = new_state.apps.get_model("test_crmomm", "Stable") stable = Stable.objects.create() p1 = Pony.objects.create(pink=False, weight=4.55) p2 = Pony.objects.create(pink=True, weight=5.43) stable.ponies.add(p1, p2) self.assertEqual(stable.ponies.count(), 2) stable.ponies.all().delete() # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crmomm", editor, new_state, project_state ) self.assertTableNotExists("test_crmomm_stable") self.assertTableNotExists("test_crmomm_stable_ponies") @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys") def test_create_fk_models_to_pk_field_db_collation(self): """Creation of models with a FK to a PK with db_collation.""" collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") app_label = "test_cfkmtopkfdbc" operations = [ migrations.CreateModel( "Pony", [ ( "id", models.CharField( primary_key=True, max_length=10, db_collation=collation, ), ), ], ) ] project_state = self.apply_operations(app_label, ProjectState(), operations) # ForeignKey. new_state = project_state.clone() operation = migrations.CreateModel( "Rider", [ ("id", models.AutoField(primary_key=True)), ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # OneToOneField. new_state = project_state.clone() operation = migrations.CreateModel( "ShetlandPony", [ ( "pony", models.OneToOneField("Pony", models.CASCADE, primary_key=True), ), ("cuteness", models.IntegerField(default=1)), ], ) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_shetlandpony", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) def test_create_model_inheritance(self): """ Tests the CreateModel operation on a multi-table inheritance setup. """ project_state = self.set_up_test_model("test_crmoih") # Test the state alteration operation = migrations.CreateModel( "ShetlandPony", [ ( "pony_ptr", models.OneToOneField( "test_crmoih.Pony", models.CASCADE, auto_created=True, primary_key=True, to_field="id", serialize=False, ), ), ("cuteness", models.IntegerField(default=1)), ], ) new_state = project_state.clone() operation.state_forwards("test_crmoih", new_state) self.assertIn(("test_crmoih", "shetlandpony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crmoih_shetlandpony") with connection.schema_editor() as editor: operation.database_forwards("test_crmoih", editor, project_state, new_state) self.assertTableExists("test_crmoih_shetlandpony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crmoih", editor, new_state, project_state ) self.assertTableNotExists("test_crmoih_shetlandpony") def test_create_proxy_model(self): """ CreateModel ignores proxy models. """ project_state = self.set_up_test_model("test_crprmo") # Test the state alteration operation = migrations.CreateModel( "ProxyPony", [], options={"proxy": True}, bases=("test_crprmo.Pony",), ) self.assertEqual(operation.describe(), "Create proxy model ProxyPony") new_state = project_state.clone() operation.state_forwards("test_crprmo", new_state) self.assertIn(("test_crprmo", "proxypony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crprmo", editor, project_state, new_state) self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crprmo", editor, new_state, project_state ) self.assertTableNotExists("test_crprmo_proxypony") self.assertTableExists("test_crprmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["bases", "fields", "name", "options"]) def test_create_unmanaged_model(self): """ CreateModel ignores unmanaged models. """ project_state = self.set_up_test_model("test_crummo") # Test the state alteration operation = migrations.CreateModel( "UnmanagedPony", [], options={"proxy": True}, bases=("test_crummo.Pony",), ) self.assertEqual(operation.describe(), "Create proxy model UnmanagedPony") new_state = project_state.clone() operation.state_forwards("test_crummo", new_state) self.assertIn(("test_crummo", "unmanagedpony"), new_state.models) # Test the database alteration self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crummo", editor, project_state, new_state) self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crummo", editor, new_state, project_state ) self.assertTableNotExists("test_crummo_unmanagedpony") self.assertTableExists("test_crummo_pony") @skipUnlessDBFeature("supports_table_check_constraints") def test_create_model_with_constraint(self): where = models.Q(pink__gt=2) check_constraint = models.CheckConstraint( check=where, name="test_constraint_pony_pink_gt_2" ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ], options={"constraints": [check_constraint]}, ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) # Test database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") with connection.cursor() as cursor: with self.assertRaises(IntegrityError): cursor.execute("INSERT INTO test_crmo_pony (id, pink) VALUES (1, 1)") # Test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual(definition[2]["options"]["constraints"], [check_constraint]) @skipUnlessDBFeature("supports_table_check_constraints") def test_create_model_with_boolean_expression_in_check_constraint(self): app_label = "test_crmobechc" rawsql_constraint = models.CheckConstraint( check=models.expressions.RawSQL( "price < %s", (1000,), output_field=models.BooleanField() ), name=f"{app_label}_price_lt_1000_raw", ) wrapper_constraint = models.CheckConstraint( check=models.expressions.ExpressionWrapper( models.Q(price__gt=500) | models.Q(price__lt=500), output_field=models.BooleanField(), ), name=f"{app_label}_price_neq_500_wrap", ) operation = migrations.CreateModel( "Product", [ ("id", models.AutoField(primary_key=True)), ("price", models.IntegerField(null=True)), ], options={"constraints": [rawsql_constraint, wrapper_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Add table. self.assertTableNotExists(app_label) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertTableExists(f"{app_label}_product") insert_sql = f"INSERT INTO {app_label}_product (id, price) VALUES (%d, %d)" with connection.cursor() as cursor: with self.assertRaises(IntegrityError): cursor.execute(insert_sql % (1, 1000)) cursor.execute(insert_sql % (1, 999)) with self.assertRaises(IntegrityError): cursor.execute(insert_sql % (2, 500)) cursor.execute(insert_sql % (2, 499)) def test_create_model_with_partial_unique_constraint(self): partial_unique_constraint = models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ("weight", models.FloatField()), ], options={"constraints": [partial_unique_constraint]}, ) # Test the state alteration project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) # Test database alteration self.assertTableNotExists("test_crmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") # Test constraint works Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test reversal with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [partial_unique_constraint] ) def test_create_model_with_deferred_unique_constraint(self): deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferrable_pink_constraint", deferrable=models.Deferrable.DEFERRED, ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ], options={"constraints": [deferred_unique_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) self.assertTableNotExists("test_crmo_pony") # Create table. with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1) obj.pink = 3 obj.save() else: Pony.objects.create(pink=1) # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [deferred_unique_constraint], ) @skipUnlessDBFeature("supports_covering_indexes") def test_create_model_with_covering_unique_constraint(self): covering_unique_constraint = models.UniqueConstraint( fields=["pink"], include=["weight"], name="test_constraint_pony_pink_covering_weight", ) operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=3)), ("weight", models.FloatField()), ], options={"constraints": [covering_unique_constraint]}, ) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crmo", new_state) self.assertEqual( len(new_state.models["test_crmo", "pony"].options["constraints"]), 1 ) self.assertTableNotExists("test_crmo_pony") # Create table. with connection.schema_editor() as editor: operation.database_forwards("test_crmo", editor, project_state, new_state) self.assertTableExists("test_crmo_pony") Pony = new_state.apps.get_model("test_crmo", "Pony") Pony.objects.create(pink=1, weight=4.0) with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=7.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards("test_crmo", editor, new_state, project_state) self.assertTableNotExists("test_crmo_pony") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "CreateModel") self.assertEqual(definition[1], []) self.assertEqual( definition[2]["options"]["constraints"], [covering_unique_constraint], ) def test_create_model_managers(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_cmoma") # Test the state alteration operation = migrations.CreateModel( "Food", fields=[ ("id", models.AutoField(primary_key=True)), ], managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) self.assertEqual(operation.describe(), "Create model Food") new_state = project_state.clone() operation.state_forwards("test_cmoma", new_state) self.assertIn(("test_cmoma", "food"), new_state.models) managers = new_state.models["test_cmoma", "food"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) def test_delete_model(self): """ Tests the DeleteModel operation. """ project_state = self.set_up_test_model("test_dlmo") # Test the state alteration operation = migrations.DeleteModel("Pony") self.assertEqual(operation.describe(), "Delete model Pony") self.assertEqual(operation.migration_name_fragment, "delete_pony") new_state = project_state.clone() operation.state_forwards("test_dlmo", new_state) self.assertNotIn(("test_dlmo", "pony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlmo_pony") with connection.schema_editor() as editor: operation.database_forwards("test_dlmo", editor, project_state, new_state) self.assertTableNotExists("test_dlmo_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_dlmo", editor, new_state, project_state) self.assertTableExists("test_dlmo_pony") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "DeleteModel") self.assertEqual(definition[1], []) self.assertEqual(list(definition[2]), ["name"]) def test_delete_proxy_model(self): """ Tests the DeleteModel operation ignores proxy models. """ project_state = self.set_up_test_model("test_dlprmo", proxy_model=True) # Test the state alteration operation = migrations.DeleteModel("ProxyPony") new_state = project_state.clone() operation.state_forwards("test_dlprmo", new_state) self.assertIn(("test_dlprmo", "proxypony"), project_state.models) self.assertNotIn(("test_dlprmo", "proxypony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") with connection.schema_editor() as editor: operation.database_forwards("test_dlprmo", editor, project_state, new_state) self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dlprmo", editor, new_state, project_state ) self.assertTableExists("test_dlprmo_pony") self.assertTableNotExists("test_dlprmo_proxypony") def test_delete_mti_model(self): project_state = self.set_up_test_model("test_dlmtimo", mti_model=True) # Test the state alteration operation = migrations.DeleteModel("ShetlandPony") new_state = project_state.clone() operation.state_forwards("test_dlmtimo", new_state) self.assertIn(("test_dlmtimo", "shetlandpony"), project_state.models) self.assertNotIn(("test_dlmtimo", "shetlandpony"), new_state.models) # Test the database alteration self.assertTableExists("test_dlmtimo_pony") self.assertTableExists("test_dlmtimo_shetlandpony") self.assertColumnExists("test_dlmtimo_shetlandpony", "pony_ptr_id") with connection.schema_editor() as editor: operation.database_forwards( "test_dlmtimo", editor, project_state, new_state ) self.assertTableExists("test_dlmtimo_pony") self.assertTableNotExists("test_dlmtimo_shetlandpony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dlmtimo", editor, new_state, project_state ) self.assertTableExists("test_dlmtimo_pony") self.assertTableExists("test_dlmtimo_shetlandpony") self.assertColumnExists("test_dlmtimo_shetlandpony", "pony_ptr_id") def test_rename_model(self): """ Tests the RenameModel operation. """ project_state = self.set_up_test_model("test_rnmo", related_model=True) # Test the state alteration operation = migrations.RenameModel("Pony", "Horse") self.assertEqual(operation.describe(), "Rename model Pony to Horse") self.assertEqual(operation.migration_name_fragment, "rename_pony_horse") # Test initial state and database self.assertIn(("test_rnmo", "pony"), project_state.models) self.assertNotIn(("test_rnmo", "horse"), project_state.models) self.assertTableExists("test_rnmo_pony") self.assertTableNotExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # Migrate forwards new_state = project_state.clone() atomic_rename = connection.features.supports_atomic_references_rename new_state = self.apply_operations( "test_rnmo", new_state, [operation], atomic=atomic_rename ) # Test new state and database self.assertNotIn(("test_rnmo", "pony"), new_state.models) self.assertIn(("test_rnmo", "horse"), new_state.models) # RenameModel also repoints all incoming FKs and M2Ms self.assertEqual( new_state.models["test_rnmo", "rider"].fields["pony"].remote_field.model, "test_rnmo.Horse", ) self.assertTableNotExists("test_rnmo_pony") self.assertTableExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # Migrate backwards original_state = self.unapply_operations( "test_rnmo", project_state, [operation], atomic=atomic_rename ) # Test original state and database self.assertIn(("test_rnmo", "pony"), original_state.models) self.assertNotIn(("test_rnmo", "horse"), original_state.models) self.assertEqual( original_state.models["test_rnmo", "rider"] .fields["pony"] .remote_field.model, "Pony", ) self.assertTableExists("test_rnmo_pony") self.assertTableNotExists("test_rnmo_horse") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_pony", "id") ) self.assertFKNotExists( "test_rnmo_rider", ["pony_id"], ("test_rnmo_horse", "id") ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RenameModel") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"old_name": "Pony", "new_name": "Horse"}) def test_rename_model_state_forwards(self): """ RenameModel operations shouldn't trigger the caching of rendered apps on state without prior apps. """ state = ProjectState() state.add_model(ModelState("migrations", "Foo", [])) operation = migrations.RenameModel("Foo", "Bar") operation.state_forwards("migrations", state) self.assertNotIn("apps", state.__dict__) self.assertNotIn(("migrations", "foo"), state.models) self.assertIn(("migrations", "bar"), state.models) # Now with apps cached. apps = state.apps operation = migrations.RenameModel("Bar", "Foo") operation.state_forwards("migrations", state) self.assertIs(state.apps, apps) self.assertNotIn(("migrations", "bar"), state.models) self.assertIn(("migrations", "foo"), state.models) def test_rename_model_with_self_referential_fk(self): """ Tests the RenameModel operation on model with self referential FK. """ project_state = self.set_up_test_model("test_rmwsrf", related_model=True) # Test the state alteration operation = migrations.RenameModel("Rider", "HorseRider") self.assertEqual(operation.describe(), "Rename model Rider to HorseRider") new_state = project_state.clone() operation.state_forwards("test_rmwsrf", new_state) self.assertNotIn(("test_rmwsrf", "rider"), new_state.models) self.assertIn(("test_rmwsrf", "horserider"), new_state.models) # Remember, RenameModel also repoints all incoming FKs and M2Ms self.assertEqual( "self", new_state.models["test_rmwsrf", "horserider"] .fields["friend"] .remote_field.model, ) HorseRider = new_state.apps.get_model("test_rmwsrf", "horserider") self.assertIs( HorseRider._meta.get_field("horserider").remote_field.model, HorseRider ) # Test the database alteration self.assertTableExists("test_rmwsrf_rider") self.assertTableNotExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKNotExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id") ) atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_forwards("test_rmwsrf", editor, project_state, new_state) self.assertTableNotExists("test_rmwsrf_rider") self.assertTableExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKNotExists( "test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKExists( "test_rmwsrf_horserider", ["friend_id"], ("test_rmwsrf_horserider", "id"), ) # And test reversal with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_backwards( "test_rmwsrf", editor, new_state, project_state ) self.assertTableExists("test_rmwsrf_rider") self.assertTableNotExists("test_rmwsrf_horserider") if connection.features.supports_foreign_keys: self.assertFKExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_rider", "id") ) self.assertFKNotExists( "test_rmwsrf_rider", ["friend_id"], ("test_rmwsrf_horserider", "id") ) def test_rename_model_with_superclass_fk(self): """ Tests the RenameModel operation on a model which has a superclass that has a foreign key. """ project_state = self.set_up_test_model( "test_rmwsc", related_model=True, mti_model=True ) # Test the state alteration operation = migrations.RenameModel("ShetlandPony", "LittleHorse") self.assertEqual( operation.describe(), "Rename model ShetlandPony to LittleHorse" ) new_state = project_state.clone() operation.state_forwards("test_rmwsc", new_state) self.assertNotIn(("test_rmwsc", "shetlandpony"), new_state.models) self.assertIn(("test_rmwsc", "littlehorse"), new_state.models) # RenameModel shouldn't repoint the superclass's relations, only local ones self.assertEqual( project_state.models["test_rmwsc", "rider"] .fields["pony"] .remote_field.model, new_state.models["test_rmwsc", "rider"].fields["pony"].remote_field.model, ) # Before running the migration we have a table for Shetland Pony, not # Little Horse. self.assertTableExists("test_rmwsc_shetlandpony") self.assertTableNotExists("test_rmwsc_littlehorse") if connection.features.supports_foreign_keys: # and the foreign key on rider points to pony, not shetland pony self.assertFKExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id") ) self.assertFKNotExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_shetlandpony", "id") ) with connection.schema_editor( atomic=connection.features.supports_atomic_references_rename ) as editor: operation.database_forwards("test_rmwsc", editor, project_state, new_state) # Now we have a little horse table, not shetland pony self.assertTableNotExists("test_rmwsc_shetlandpony") self.assertTableExists("test_rmwsc_littlehorse") if connection.features.supports_foreign_keys: # but the Foreign keys still point at pony, not little horse self.assertFKExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_pony", "id") ) self.assertFKNotExists( "test_rmwsc_rider", ["pony_id"], ("test_rmwsc_littlehorse", "id") ) def test_rename_model_with_self_referential_m2m(self): app_label = "test_rename_model_with_self_referential_m2m" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "ReflexivePony", fields=[ ("id", models.AutoField(primary_key=True)), ("ponies", models.ManyToManyField("self")), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("ReflexivePony", "ReflexivePony2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "ReflexivePony2") pony = Pony.objects.create() pony.ponies.add(pony) def test_rename_model_with_m2m(self): app_label = "test_rename_model_with_m2m" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("Pony", "Pony2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony2") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) self.assertEqual(Pony.objects.count(), 2) self.assertEqual(Rider.objects.count(), 2) self.assertEqual( Pony._meta.get_field("riders").remote_field.through.objects.count(), 2 ) def test_rename_model_with_db_table_noop(self): app_label = "test_rmwdbtn" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], options={"db_table": "rider"}, ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey("%s.Rider" % app_label, models.CASCADE), ), ], ), ], ) new_state = project_state.clone() operation = migrations.RenameModel("Rider", "Runner") operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( app_label, editor, new_state, project_state ) def test_rename_m2m_target_model(self): app_label = "test_rename_m2m_target_model" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("Rider", "Rider2"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider2") pony = Pony.objects.create() rider = Rider.objects.create() pony.riders.add(rider) self.assertEqual(Pony.objects.count(), 2) self.assertEqual(Rider.objects.count(), 2) self.assertEqual( Pony._meta.get_field("riders").remote_field.through.objects.count(), 2 ) def test_rename_m2m_through_model(self): app_label = "test_rename_through" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "test_rename_through.Rider", models.CASCADE ), ), ( "pony", models.ForeignKey( "test_rename_through.Pony", models.CASCADE ), ), ], ), migrations.AddField( "Pony", "riders", models.ManyToManyField( "test_rename_through.Rider", through="test_rename_through.PonyRider", ), ), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") PonyRider = project_state.apps.get_model(app_label, "PonyRider") pony = Pony.objects.create() rider = Rider.objects.create() PonyRider.objects.create(pony=pony, rider=rider) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameModel("PonyRider", "PonyRider2"), ], ) Pony = project_state.apps.get_model(app_label, "Pony") Rider = project_state.apps.get_model(app_label, "Rider") PonyRider = project_state.apps.get_model(app_label, "PonyRider2") pony = Pony.objects.first() rider = Rider.objects.create() PonyRider.objects.create(pony=pony, rider=rider) self.assertEqual(Pony.objects.count(), 1) self.assertEqual(Rider.objects.count(), 2) self.assertEqual(PonyRider.objects.count(), 2) self.assertEqual(pony.riders.count(), 2) def test_rename_m2m_model_after_rename_field(self): """RenameModel renames a many-to-many column after a RenameField.""" app_label = "test_rename_multiple" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=20)), ], ), migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey( "test_rename_multiple.Pony", models.CASCADE ), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ("riders", models.ManyToManyField("Rider")), ], ), migrations.RenameField( model_name="pony", old_name="name", new_name="fancy_name" ), migrations.RenameModel(old_name="Rider", new_name="Jockey"), ], atomic=connection.features.supports_atomic_references_rename, ) Pony = project_state.apps.get_model(app_label, "Pony") Jockey = project_state.apps.get_model(app_label, "Jockey") PonyRider = project_state.apps.get_model(app_label, "PonyRider") # No "no such column" error means the column was renamed correctly. pony = Pony.objects.create(fancy_name="a good name") jockey = Jockey.objects.create(pony=pony) ponyrider = PonyRider.objects.create() ponyrider.riders.add(jockey) def test_add_field(self): """ Tests the AddField operation. """ # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=5), ) self.assertEqual(operation.describe(), "Add field height to Pony") self.assertEqual(operation.migration_name_fragment, "pony_height") project_state, new_state = self.make_test_state("test_adfl", operation) self.assertEqual(len(new_state.models["test_adfl", "pony"].fields), 4) field = new_state.models["test_adfl", "pony"].fields["height"] self.assertEqual(field.default, 5) # Test the database alteration self.assertColumnNotExists("test_adfl_pony", "height") with connection.schema_editor() as editor: operation.database_forwards("test_adfl", editor, project_state, new_state) self.assertColumnExists("test_adfl_pony", "height") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_adfl", editor, new_state, project_state) self.assertColumnNotExists("test_adfl_pony", "height") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddField") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"]) def test_add_charfield(self): """ Tests the AddField operation on TextField. """ project_state = self.set_up_test_model("test_adchfl") Pony = project_state.apps.get_model("test_adchfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adchfl", project_state, [ migrations.AddField( "Pony", "text", models.CharField(max_length=10, default="some text"), ), migrations.AddField( "Pony", "empty", models.CharField(max_length=10, default=""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.CharField(max_length=10, default="42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.CharField(max_length=10, default='"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adchfl", "Pony") pony = Pony.objects.get(pk=pony.pk) self.assertEqual(pony.text, "some text") self.assertEqual(pony.empty, "") self.assertEqual(pony.digits, "42") self.assertEqual(pony.quotes, '"\'"') def test_add_textfield(self): """ Tests the AddField operation on TextField. """ project_state = self.set_up_test_model("test_adtxtfl") Pony = project_state.apps.get_model("test_adtxtfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adtxtfl", project_state, [ migrations.AddField( "Pony", "text", models.TextField(default="some text"), ), migrations.AddField( "Pony", "empty", models.TextField(default=""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.TextField(default="42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.TextField(default='"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adtxtfl", "Pony") pony = Pony.objects.get(pk=pony.pk) self.assertEqual(pony.text, "some text") self.assertEqual(pony.empty, "") self.assertEqual(pony.digits, "42") self.assertEqual(pony.quotes, '"\'"') def test_add_binaryfield(self): """ Tests the AddField operation on TextField/BinaryField. """ project_state = self.set_up_test_model("test_adbinfl") Pony = project_state.apps.get_model("test_adbinfl", "Pony") pony = Pony.objects.create(weight=42) new_state = self.apply_operations( "test_adbinfl", project_state, [ migrations.AddField( "Pony", "blob", models.BinaryField(default=b"some text"), ), migrations.AddField( "Pony", "empty", models.BinaryField(default=b""), ), # If not properly quoted digits would be interpreted as an int. migrations.AddField( "Pony", "digits", models.BinaryField(default=b"42"), ), # Manual quoting is fragile and could trip on quotes. Refs #xyz. migrations.AddField( "Pony", "quotes", models.BinaryField(default=b'"\'"'), ), ], ) Pony = new_state.apps.get_model("test_adbinfl", "Pony") pony = Pony.objects.get(pk=pony.pk) # SQLite returns buffer/memoryview, cast to bytes for checking. self.assertEqual(bytes(pony.blob), b"some text") self.assertEqual(bytes(pony.empty), b"") self.assertEqual(bytes(pony.digits), b"42") self.assertEqual(bytes(pony.quotes), b'"\'"') def test_column_name_quoting(self): """ Column names that are SQL keywords shouldn't cause problems when used in migrations (#22168). """ project_state = self.set_up_test_model("test_regr22168") operation = migrations.AddField( "Pony", "order", models.IntegerField(default=0), ) new_state = project_state.clone() operation.state_forwards("test_regr22168", new_state) with connection.schema_editor() as editor: operation.database_forwards( "test_regr22168", editor, project_state, new_state ) self.assertColumnExists("test_regr22168_pony", "order") def test_add_field_preserve_default(self): """ Tests the AddField operation's state alteration when preserve_default = False. """ project_state = self.set_up_test_model("test_adflpd") # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=4), preserve_default=False, ) new_state = project_state.clone() operation.state_forwards("test_adflpd", new_state) self.assertEqual(len(new_state.models["test_adflpd", "pony"].fields), 4) field = new_state.models["test_adflpd", "pony"].fields["height"] self.assertEqual(field.default, models.NOT_PROVIDED) # Test the database alteration project_state.apps.get_model("test_adflpd", "pony").objects.create( weight=4, ) self.assertColumnNotExists("test_adflpd_pony", "height") with connection.schema_editor() as editor: operation.database_forwards("test_adflpd", editor, project_state, new_state) self.assertColumnExists("test_adflpd_pony", "height") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddField") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["field", "model_name", "name", "preserve_default"] ) def test_add_field_m2m(self): """ Tests the AddField operation with a ManyToManyField. """ project_state = self.set_up_test_model("test_adflmm", second_model=True) # Test the state alteration operation = migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies") ) new_state = project_state.clone() operation.state_forwards("test_adflmm", new_state) self.assertEqual(len(new_state.models["test_adflmm", "pony"].fields), 4) # Test the database alteration self.assertTableNotExists("test_adflmm_pony_stables") with connection.schema_editor() as editor: operation.database_forwards("test_adflmm", editor, project_state, new_state) self.assertTableExists("test_adflmm_pony_stables") self.assertColumnNotExists("test_adflmm_pony", "stables") # Make sure the M2M field actually works with atomic(): Pony = new_state.apps.get_model("test_adflmm", "Pony") p = Pony.objects.create(pink=False, weight=4.55) p.stables.create() self.assertEqual(p.stables.count(), 1) p.stables.all().delete() # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_adflmm", editor, new_state, project_state ) self.assertTableNotExists("test_adflmm_pony_stables") def test_alter_field_m2m(self): project_state = self.set_up_test_model("test_alflmm", second_model=True) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") self.assertFalse(Pony._meta.get_field("stables").blank) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AlterField( "Pony", "stables", models.ManyToManyField( to="Stable", related_name="ponies", blank=True ), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") self.assertTrue(Pony._meta.get_field("stables").blank) def test_repoint_field_m2m(self): project_state = self.set_up_test_model( "test_alflmm", second_model=True, third_model=True ) project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AddField( "Pony", "places", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) Pony = project_state.apps.get_model("test_alflmm", "Pony") project_state = self.apply_operations( "test_alflmm", project_state, operations=[ migrations.AlterField( "Pony", "places", models.ManyToManyField(to="Van", related_name="ponies"), ) ], ) # Ensure the new field actually works Pony = project_state.apps.get_model("test_alflmm", "Pony") p = Pony.objects.create(pink=False, weight=4.55) p.places.create() self.assertEqual(p.places.count(), 1) p.places.all().delete() def test_remove_field_m2m(self): project_state = self.set_up_test_model("test_rmflmm", second_model=True) project_state = self.apply_operations( "test_rmflmm", project_state, operations=[ migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable", related_name="ponies"), ) ], ) self.assertTableExists("test_rmflmm_pony_stables") with_field_state = project_state.clone() operations = [migrations.RemoveField("Pony", "stables")] project_state = self.apply_operations( "test_rmflmm", project_state, operations=operations ) self.assertTableNotExists("test_rmflmm_pony_stables") # And test reversal self.unapply_operations("test_rmflmm", with_field_state, operations=operations) self.assertTableExists("test_rmflmm_pony_stables") def test_remove_field_m2m_with_through(self): project_state = self.set_up_test_model("test_rmflmmwt", second_model=True) self.assertTableNotExists("test_rmflmmwt_ponystables") project_state = self.apply_operations( "test_rmflmmwt", project_state, operations=[ migrations.CreateModel( "PonyStables", fields=[ ( "pony", models.ForeignKey("test_rmflmmwt.Pony", models.CASCADE), ), ( "stable", models.ForeignKey("test_rmflmmwt.Stable", models.CASCADE), ), ], ), migrations.AddField( "Pony", "stables", models.ManyToManyField( "Stable", related_name="ponies", through="test_rmflmmwt.PonyStables", ), ), ], ) self.assertTableExists("test_rmflmmwt_ponystables") operations = [ migrations.RemoveField("Pony", "stables"), migrations.DeleteModel("PonyStables"), ] self.apply_operations("test_rmflmmwt", project_state, operations=operations) def test_remove_field(self): """ Tests the RemoveField operation. """ project_state = self.set_up_test_model("test_rmfl") # Test the state alteration operation = migrations.RemoveField("Pony", "pink") self.assertEqual(operation.describe(), "Remove field pink from Pony") self.assertEqual(operation.migration_name_fragment, "remove_pony_pink") new_state = project_state.clone() operation.state_forwards("test_rmfl", new_state) self.assertEqual(len(new_state.models["test_rmfl", "pony"].fields), 2) # Test the database alteration self.assertColumnExists("test_rmfl_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_rmfl", editor, project_state, new_state) self.assertColumnNotExists("test_rmfl_pony", "pink") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_rmfl", editor, new_state, project_state) self.assertColumnExists("test_rmfl_pony", "pink") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveField") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": "pink"}) def test_remove_fk(self): """ Tests the RemoveField operation on a foreign key. """ project_state = self.set_up_test_model("test_rfk", related_model=True) self.assertColumnExists("test_rfk_rider", "pony_id") operation = migrations.RemoveField("Rider", "pony") new_state = project_state.clone() operation.state_forwards("test_rfk", new_state) with connection.schema_editor() as editor: operation.database_forwards("test_rfk", editor, project_state, new_state) self.assertColumnNotExists("test_rfk_rider", "pony_id") with connection.schema_editor() as editor: operation.database_backwards("test_rfk", editor, new_state, project_state) self.assertColumnExists("test_rfk_rider", "pony_id") def test_alter_model_table(self): """ Tests the AlterModelTable operation. """ project_state = self.set_up_test_model("test_almota") # Test the state alteration operation = migrations.AlterModelTable("Pony", "test_almota_pony_2") self.assertEqual( operation.describe(), "Rename table for Pony to test_almota_pony_2" ) self.assertEqual(operation.migration_name_fragment, "alter_pony_table") new_state = project_state.clone() operation.state_forwards("test_almota", new_state) self.assertEqual( new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony_2", ) # Test the database alteration self.assertTableExists("test_almota_pony") self.assertTableNotExists("test_almota_pony_2") with connection.schema_editor() as editor: operation.database_forwards("test_almota", editor, project_state, new_state) self.assertTableNotExists("test_almota_pony") self.assertTableExists("test_almota_pony_2") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_almota", editor, new_state, project_state ) self.assertTableExists("test_almota_pony") self.assertTableNotExists("test_almota_pony_2") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelTable") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"name": "Pony", "table": "test_almota_pony_2"}) def test_alter_model_table_none(self): """ Tests the AlterModelTable operation if the table name is set to None. """ operation = migrations.AlterModelTable("Pony", None) self.assertEqual(operation.describe(), "Rename table for Pony to (default)") def test_alter_model_table_noop(self): """ Tests the AlterModelTable operation if the table name is not changed. """ project_state = self.set_up_test_model("test_almota") # Test the state alteration operation = migrations.AlterModelTable("Pony", "test_almota_pony") new_state = project_state.clone() operation.state_forwards("test_almota", new_state) self.assertEqual( new_state.models["test_almota", "pony"].options["db_table"], "test_almota_pony", ) # Test the database alteration self.assertTableExists("test_almota_pony") with connection.schema_editor() as editor: operation.database_forwards("test_almota", editor, project_state, new_state) self.assertTableExists("test_almota_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_almota", editor, new_state, project_state ) self.assertTableExists("test_almota_pony") def test_alter_model_table_m2m(self): """ AlterModelTable should rename auto-generated M2M tables. """ app_label = "test_talflmltlm2m" pony_db_table = "pony_foo" project_state = self.set_up_test_model( app_label, second_model=True, db_table=pony_db_table ) # Add the M2M field first_state = project_state.clone() operation = migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable") ) operation.state_forwards(app_label, first_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, first_state) original_m2m_table = "%s_%s" % (pony_db_table, "stables") new_m2m_table = "%s_%s" % (app_label, "pony_stables") self.assertTableExists(original_m2m_table) self.assertTableNotExists(new_m2m_table) # Rename the Pony db_table which should also rename the m2m table. second_state = first_state.clone() operation = migrations.AlterModelTable(name="pony", table=None) operation.state_forwards(app_label, second_state) atomic_rename = connection.features.supports_atomic_references_rename with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_forwards(app_label, editor, first_state, second_state) self.assertTableExists(new_m2m_table) self.assertTableNotExists(original_m2m_table) # And test reversal with connection.schema_editor(atomic=atomic_rename) as editor: operation.database_backwards(app_label, editor, second_state, first_state) self.assertTableExists(original_m2m_table) self.assertTableNotExists(new_m2m_table) def test_alter_field(self): """ Tests the AlterField operation. """ project_state = self.set_up_test_model("test_alfl") # Test the state alteration operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) self.assertEqual(operation.describe(), "Alter field pink on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_pink") new_state = project_state.clone() operation.state_forwards("test_alfl", new_state) self.assertIs( project_state.models["test_alfl", "pony"].fields["pink"].null, False ) self.assertIs(new_state.models["test_alfl", "pony"].fields["pink"].null, True) # Test the database alteration self.assertColumnNotNull("test_alfl_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_alfl", editor, project_state, new_state) self.assertColumnNull("test_alfl_pony", "pink") # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_alfl", editor, new_state, project_state) self.assertColumnNotNull("test_alfl_pony", "pink") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterField") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["field", "model_name", "name"]) def test_alter_field_add_db_column_noop(self): """ AlterField operation is a noop when adding only a db_column and the column name is not changed. """ app_label = "test_afadbn" project_state = self.set_up_test_model(app_label, related_model=True) pony_table = "%s_pony" % app_label new_state = project_state.clone() operation = migrations.AlterField( "Pony", "weight", models.FloatField(db_column="weight") ) operation.state_forwards(app_label, new_state) self.assertIsNone( project_state.models[app_label, "pony"].fields["weight"].db_column, ) self.assertEqual( new_state.models[app_label, "pony"].fields["weight"].db_column, "weight", ) self.assertColumnExists(pony_table, "weight") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnExists(pony_table, "weight") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( app_label, editor, new_state, project_state ) self.assertColumnExists(pony_table, "weight") rider_table = "%s_rider" % app_label new_state = project_state.clone() operation = migrations.AlterField( "Rider", "pony", models.ForeignKey("Pony", models.CASCADE, db_column="pony_id"), ) operation.state_forwards(app_label, new_state) self.assertIsNone( project_state.models[app_label, "rider"].fields["pony"].db_column, ) self.assertIs( new_state.models[app_label, "rider"].fields["pony"].db_column, "pony_id", ) self.assertColumnExists(rider_table, "pony_id") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnExists(rider_table, "pony_id") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards(app_label, editor, new_state, project_state) self.assertColumnExists(rider_table, "pony_id") def test_alter_field_pk(self): """ The AlterField operation on primary keys (things like PostgreSQL's SERIAL weirdness). """ project_state = self.set_up_test_model("test_alflpk") # Test the state alteration operation = migrations.AlterField( "Pony", "id", models.IntegerField(primary_key=True) ) new_state = project_state.clone() operation.state_forwards("test_alflpk", new_state) self.assertIsInstance( project_state.models["test_alflpk", "pony"].fields["id"], models.AutoField, ) self.assertIsInstance( new_state.models["test_alflpk", "pony"].fields["id"], models.IntegerField, ) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_alflpk", editor, project_state, new_state) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflpk", editor, new_state, project_state ) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_pk_fk(self): """ Tests the AlterField operation on primary keys changes any FKs pointing to it. """ project_state = self.set_up_test_model("test_alflpkfk", related_model=True) project_state = self.apply_operations( "test_alflpkfk", project_state, [ migrations.CreateModel( "Stable", fields=[ ("ponies", models.ManyToManyField("Pony")), ], ), migrations.AddField( "Pony", "stables", models.ManyToManyField("Stable"), ), ], ) # Test the state alteration operation = migrations.AlterField( "Pony", "id", models.FloatField(primary_key=True) ) new_state = project_state.clone() operation.state_forwards("test_alflpkfk", new_state) self.assertIsInstance( project_state.models["test_alflpkfk", "pony"].fields["id"], models.AutoField, ) self.assertIsInstance( new_state.models["test_alflpkfk", "pony"].fields["id"], models.FloatField, ) def assertIdTypeEqualsFkType(): with connection.cursor() as cursor: id_type, id_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_pony" ) if c.name == "id" ][0] fk_type, fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_rider" ) if c.name == "pony_id" ][0] m2m_fk_type, m2m_fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_pony_stables", ) if c.name == "pony_id" ][0] remote_m2m_fk_type, remote_m2m_fk_null = [ (c.type_code, c.null_ok) for c in connection.introspection.get_table_description( cursor, "test_alflpkfk_stable_ponies", ) if c.name == "pony_id" ][0] self.assertEqual(id_type, fk_type) self.assertEqual(id_type, m2m_fk_type) self.assertEqual(id_type, remote_m2m_fk_type) self.assertEqual(id_null, fk_null) self.assertEqual(id_null, m2m_fk_null) self.assertEqual(id_null, remote_m2m_fk_null) assertIdTypeEqualsFkType() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alflpkfk", editor, project_state, new_state ) assertIdTypeEqualsFkType() if connection.features.supports_foreign_keys: self.assertFKExists( "test_alflpkfk_pony_stables", ["pony_id"], ("test_alflpkfk_pony", "id"), ) self.assertFKExists( "test_alflpkfk_stable_ponies", ["pony_id"], ("test_alflpkfk_pony", "id"), ) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflpkfk", editor, new_state, project_state ) assertIdTypeEqualsFkType() if connection.features.supports_foreign_keys: self.assertFKExists( "test_alflpkfk_pony_stables", ["pony_id"], ("test_alflpkfk_pony", "id"), ) self.assertFKExists( "test_alflpkfk_stable_ponies", ["pony_id"], ("test_alflpkfk_pony", "id"), ) @skipUnlessDBFeature("supports_collation_on_charfield", "supports_foreign_keys") def test_alter_field_pk_fk_db_collation(self): """ AlterField operation of db_collation on primary keys changes any FKs pointing to it. """ collation = connection.features.test_collations.get("non_default") if not collation: self.skipTest("Language collations are not supported.") app_label = "test_alflpkfkdbc" project_state = self.apply_operations( app_label, ProjectState(), [ migrations.CreateModel( "Pony", [ ("id", models.CharField(primary_key=True, max_length=10)), ], ), migrations.CreateModel( "Rider", [ ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ), migrations.CreateModel( "Stable", [ ("ponies", models.ManyToManyField("Pony")), ], ), ], ) # State alteration. operation = migrations.AlterField( "Pony", "id", models.CharField( primary_key=True, max_length=10, db_collation=collation, ), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Database alteration. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertColumnCollation(f"{app_label}_pony", "id", collation) self.assertColumnCollation(f"{app_label}_rider", "pony_id", collation) self.assertColumnCollation(f"{app_label}_stable_ponies", "pony_id", collation) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) def test_alter_field_pk_mti_fk(self): app_label = "test_alflpkmtifk" project_state = self.set_up_test_model(app_label, mti_model=True) project_state = self.apply_operations( app_label, project_state, [ migrations.CreateModel( "ShetlandRider", fields=[ ( "pony", models.ForeignKey( f"{app_label}.ShetlandPony", models.CASCADE ), ), ], ), ], ) operation = migrations.AlterField( "Pony", "id", models.BigAutoField(primary_key=True), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertIsInstance( new_state.models[app_label, "pony"].fields["id"], models.BigAutoField, ) def _get_column_id_type(cursor, table, column): return [ c.type_code for c in connection.introspection.get_table_description( cursor, f"{app_label}_{table}", ) if c.name == column ][0] def assertIdTypeEqualsMTIFkType(): with connection.cursor() as cursor: parent_id_type = _get_column_id_type(cursor, "pony", "id") child_id_type = _get_column_id_type( cursor, "shetlandpony", "pony_ptr_id" ) mti_id_type = _get_column_id_type(cursor, "shetlandrider", "pony_id") self.assertEqual(parent_id_type, child_id_type) self.assertEqual(parent_id_type, mti_id_type) assertIdTypeEqualsMTIFkType() # Alter primary key. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_shetlandrider", ["pony_id"], (f"{app_label}_shetlandpony", "pony_ptr_id"), ) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_shetlandrider", ["pony_id"], (f"{app_label}_shetlandpony", "pony_ptr_id"), ) def test_alter_field_pk_mti_and_fk_to_base(self): app_label = "test_alflpkmtiftb" project_state = self.set_up_test_model( app_label, mti_model=True, related_model=True, ) operation = migrations.AlterField( "Pony", "id", models.BigAutoField(primary_key=True), ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertIsInstance( new_state.models[app_label, "pony"].fields["id"], models.BigAutoField, ) def _get_column_id_type(cursor, table, column): return [ c.type_code for c in connection.introspection.get_table_description( cursor, f"{app_label}_{table}", ) if c.name == column ][0] def assertIdTypeEqualsMTIFkType(): with connection.cursor() as cursor: parent_id_type = _get_column_id_type(cursor, "pony", "id") fk_id_type = _get_column_id_type(cursor, "rider", "pony_id") child_id_type = _get_column_id_type( cursor, "shetlandpony", "pony_ptr_id" ) self.assertEqual(parent_id_type, child_id_type) self.assertEqual(parent_id_type, fk_id_type) assertIdTypeEqualsMTIFkType() # Alter primary key. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_rider", ["pony_id"], (f"{app_label}_pony", "id"), ) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertIdTypeEqualsMTIFkType() if connection.features.supports_foreign_keys: self.assertFKExists( f"{app_label}_shetlandpony", ["pony_ptr_id"], (f"{app_label}_pony", "id"), ) self.assertFKExists( f"{app_label}_rider", ["pony_id"], (f"{app_label}_pony", "id"), ) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_reloads_state_on_fk_with_to_field_target_type_change(self): app_label = "test_alflrsfkwtflttc" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("code", models.IntegerField(unique=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="code" ), ), ], ), ], ) operation = migrations.AlterField( "Rider", "code", models.CharField(max_length=100, unique=True), ) self.apply_operations(app_label, project_state, operations=[operation]) id_type, id_null = [ (c.type_code, c.null_ok) for c in self.get_table_description("%s_rider" % app_label) if c.name == "code" ][0] fk_type, fk_null = [ (c.type_code, c.null_ok) for c in self.get_table_description("%s_pony" % app_label) if c.name == "rider_id" ][0] self.assertEqual(id_type, fk_type) self.assertEqual(id_null, fk_null) @skipUnlessDBFeature("supports_foreign_keys") def test_alter_field_reloads_state_fk_with_to_field_related_name_target_type_change( self, ): app_label = "test_alflrsfkwtflrnttc" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("code", models.PositiveIntegerField(unique=True)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="code", related_name="+", ), ), ], ), ], ) operation = migrations.AlterField( "Rider", "code", models.CharField(max_length=100, unique=True), ) self.apply_operations(app_label, project_state, operations=[operation]) def test_alter_field_reloads_state_on_fk_target_changes(self): """ If AlterField doesn't reload state appropriately, the second AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_alter_field_reloads_state_on_fk_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey("%s.Rider" % app_label, models.CASCADE), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey("%s.Pony" % app_label, models.CASCADE), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.AlterField( "Rider", "id", models.CharField(primary_key=True, max_length=99) ), migrations.AlterField( "Pony", "id", models.CharField(primary_key=True, max_length=99) ), ], ) def test_alter_field_reloads_state_on_fk_with_to_field_target_changes(self): """ If AlterField doesn't reload state appropriately, the second AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_alter_field_reloads_state_on_fk_with_to_field_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ("slug", models.CharField(unique=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey( "%s.Rider" % app_label, models.CASCADE, to_field="slug" ), ), ("slug", models.CharField(unique=True, max_length=100)), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey( "%s.Pony" % app_label, models.CASCADE, to_field="slug" ), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.AlterField( "Rider", "slug", models.CharField(unique=True, max_length=99) ), migrations.AlterField( "Pony", "slug", models.CharField(unique=True, max_length=99) ), ], ) def test_rename_field_reloads_state_on_fk_target_changes(self): """ If RenameField doesn't reload state appropriately, the AlterField crashes on MySQL due to not dropping the PonyRider.pony foreign key constraint before modifying the column. """ app_label = "alter_rename_field_reloads_state_on_fk_target_changes" project_state = self.apply_operations( app_label, ProjectState(), operations=[ migrations.CreateModel( "Rider", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ], ), migrations.CreateModel( "Pony", fields=[ ("id", models.CharField(primary_key=True, max_length=100)), ( "rider", models.ForeignKey("%s.Rider" % app_label, models.CASCADE), ), ], ), migrations.CreateModel( "PonyRider", fields=[ ("id", models.AutoField(primary_key=True)), ( "pony", models.ForeignKey("%s.Pony" % app_label, models.CASCADE), ), ], ), ], ) project_state = self.apply_operations( app_label, project_state, operations=[ migrations.RenameField("Rider", "id", "id2"), migrations.AlterField( "Pony", "id", models.CharField(primary_key=True, max_length=99) ), ], atomic=connection.features.supports_atomic_references_rename, ) def test_rename_field(self): """ Tests the RenameField operation. """ project_state = self.set_up_test_model( "test_rnfl", unique_together=True, index_together=True ) # Test the state alteration operation = migrations.RenameField("Pony", "pink", "blue") self.assertEqual(operation.describe(), "Rename field pink on Pony to blue") self.assertEqual(operation.migration_name_fragment, "rename_pink_pony_blue") new_state = project_state.clone() operation.state_forwards("test_rnfl", new_state) self.assertIn("blue", new_state.models["test_rnfl", "pony"].fields) self.assertNotIn("pink", new_state.models["test_rnfl", "pony"].fields) # Make sure the unique_together has the renamed column too self.assertIn( "blue", new_state.models["test_rnfl", "pony"].options["unique_together"][0] ) self.assertNotIn( "pink", new_state.models["test_rnfl", "pony"].options["unique_together"][0] ) # Make sure the index_together has the renamed column too self.assertIn( "blue", new_state.models["test_rnfl", "pony"].options["index_together"][0] ) self.assertNotIn( "pink", new_state.models["test_rnfl", "pony"].options["index_together"][0] ) # Test the database alteration self.assertColumnExists("test_rnfl_pony", "pink") self.assertColumnNotExists("test_rnfl_pony", "blue") with connection.schema_editor() as editor: operation.database_forwards("test_rnfl", editor, project_state, new_state) self.assertColumnExists("test_rnfl_pony", "blue") self.assertColumnNotExists("test_rnfl_pony", "pink") # Ensure the unique constraint has been ported over with connection.cursor() as cursor: cursor.execute("INSERT INTO test_rnfl_pony (blue, weight) VALUES (1, 1)") with self.assertRaises(IntegrityError): with atomic(): cursor.execute( "INSERT INTO test_rnfl_pony (blue, weight) VALUES (1, 1)" ) cursor.execute("DELETE FROM test_rnfl_pony") # Ensure the index constraint has been ported over self.assertIndexExists("test_rnfl_pony", ["weight", "blue"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_rnfl", editor, new_state, project_state) self.assertColumnExists("test_rnfl_pony", "pink") self.assertColumnNotExists("test_rnfl_pony", "blue") # Ensure the index constraint has been reset self.assertIndexExists("test_rnfl_pony", ["weight", "pink"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RenameField") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "old_name": "pink", "new_name": "blue"}, ) def test_rename_field_with_db_column(self): project_state = self.apply_operations( "test_rfwdbc", ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField(db_column="db_field")), ( "fk_field", models.ForeignKey( "Pony", models.CASCADE, db_column="db_fk_field", ), ), ], ), ], ) new_state = project_state.clone() operation = migrations.RenameField("Pony", "field", "renamed_field") operation.state_forwards("test_rfwdbc", new_state) self.assertIn("renamed_field", new_state.models["test_rfwdbc", "pony"].fields) self.assertNotIn("field", new_state.models["test_rfwdbc", "pony"].fields) self.assertColumnExists("test_rfwdbc_pony", "db_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards( "test_rfwdbc", editor, project_state, new_state ) self.assertColumnExists("test_rfwdbc_pony", "db_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( "test_rfwdbc", editor, new_state, project_state ) self.assertColumnExists("test_rfwdbc_pony", "db_field") new_state = project_state.clone() operation = migrations.RenameField("Pony", "fk_field", "renamed_fk_field") operation.state_forwards("test_rfwdbc", new_state) self.assertIn( "renamed_fk_field", new_state.models["test_rfwdbc", "pony"].fields ) self.assertNotIn("fk_field", new_state.models["test_rfwdbc", "pony"].fields) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_forwards( "test_rfwdbc", editor, project_state, new_state ) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") with connection.schema_editor() as editor: with self.assertNumQueries(0): operation.database_backwards( "test_rfwdbc", editor, new_state, project_state ) self.assertColumnExists("test_rfwdbc_pony", "db_fk_field") def test_rename_field_case(self): project_state = self.apply_operations( "test_rfmx", ProjectState(), operations=[ migrations.CreateModel( "Pony", fields=[ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField()), ], ), ], ) new_state = project_state.clone() operation = migrations.RenameField("Pony", "field", "FiElD") operation.state_forwards("test_rfmx", new_state) self.assertIn("FiElD", new_state.models["test_rfmx", "pony"].fields) self.assertColumnExists("test_rfmx_pony", "field") with connection.schema_editor() as editor: operation.database_forwards("test_rfmx", editor, project_state, new_state) self.assertColumnExists( "test_rfmx_pony", connection.introspection.identifier_converter("FiElD"), ) with connection.schema_editor() as editor: operation.database_backwards("test_rfmx", editor, new_state, project_state) self.assertColumnExists("test_rfmx_pony", "field") def test_rename_missing_field(self): state = ProjectState() state.add_model(ModelState("app", "model", [])) with self.assertRaisesMessage( FieldDoesNotExist, "app.model has no field named 'field'" ): migrations.RenameField("model", "field", "new_field").state_forwards( "app", state ) def test_rename_referenced_field_state_forward(self): state = ProjectState() state.add_model( ModelState( "app", "Model", [ ("id", models.AutoField(primary_key=True)), ("field", models.IntegerField(unique=True)), ], ) ) state.add_model( ModelState( "app", "OtherModel", [ ("id", models.AutoField(primary_key=True)), ( "fk", models.ForeignKey("Model", models.CASCADE, to_field="field"), ), ( "fo", models.ForeignObject( "Model", models.CASCADE, from_fields=("fk",), to_fields=("field",), ), ), ], ) ) operation = migrations.RenameField("Model", "field", "renamed") new_state = state.clone() operation.state_forwards("app", new_state) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].remote_field.field_name, "renamed", ) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].from_fields, ["self"] ) self.assertEqual( new_state.models["app", "othermodel"].fields["fk"].to_fields, ("renamed",) ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].from_fields, ("fk",) ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",) ) operation = migrations.RenameField("OtherModel", "fk", "renamed_fk") new_state = state.clone() operation.state_forwards("app", new_state) self.assertEqual( new_state.models["app", "othermodel"] .fields["renamed_fk"] .remote_field.field_name, "renamed", ) self.assertEqual( new_state.models["app", "othermodel"].fields["renamed_fk"].from_fields, ("self",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["renamed_fk"].to_fields, ("renamed",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].from_fields, ("renamed_fk",), ) self.assertEqual( new_state.models["app", "othermodel"].fields["fo"].to_fields, ("renamed",) ) def test_alter_unique_together(self): """ Tests the AlterUniqueTogether operation. """ project_state = self.set_up_test_model("test_alunto") # Test the state alteration operation = migrations.AlterUniqueTogether("Pony", [("pink", "weight")]) self.assertEqual( operation.describe(), "Alter unique_together for Pony (1 constraint(s))" ) self.assertEqual( operation.migration_name_fragment, "alter_pony_unique_together", ) new_state = project_state.clone() operation.state_forwards("test_alunto", new_state) self.assertEqual( len( project_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 0, ) self.assertEqual( len( new_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 1, ) # Make sure we can insert duplicate rows with connection.cursor() as cursor: cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("DELETE FROM test_alunto_pony") # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alunto", editor, project_state, new_state ) cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") with self.assertRaises(IntegrityError): with atomic(): cursor.execute( "INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)" ) cursor.execute("DELETE FROM test_alunto_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alunto", editor, new_state, project_state ) cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)") cursor.execute("DELETE FROM test_alunto_pony") # Test flat unique_together operation = migrations.AlterUniqueTogether("Pony", ("pink", "weight")) operation.state_forwards("test_alunto", new_state) self.assertEqual( len( new_state.models["test_alunto", "pony"].options.get( "unique_together", set() ) ), 1, ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterUniqueTogether") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "unique_together": {("pink", "weight")}} ) def test_alter_unique_together_remove(self): operation = migrations.AlterUniqueTogether("Pony", None) self.assertEqual( operation.describe(), "Alter unique_together for Pony (0 constraint(s))" ) def test_add_index(self): """ Test the AddIndex operation. """ project_state = self.set_up_test_model("test_adin") msg = ( "Indexes passed to AddIndex operations require a name argument. " "<Index: fields=['pink']> doesn't have one." ) with self.assertRaisesMessage(ValueError, msg): migrations.AddIndex("Pony", models.Index(fields=["pink"])) index = models.Index(fields=["pink"], name="test_adin_pony_pink_idx") operation = migrations.AddIndex("Pony", index) self.assertEqual( operation.describe(), "Create index test_adin_pony_pink_idx on field(s) pink of model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_adin_pony_pink_idx", ) new_state = project_state.clone() operation.state_forwards("test_adin", new_state) # Test the database alteration self.assertEqual( len(new_state.models["test_adin", "pony"].options["indexes"]), 1 ) self.assertIndexNotExists("test_adin_pony", ["pink"]) with connection.schema_editor() as editor: operation.database_forwards("test_adin", editor, project_state, new_state) self.assertIndexExists("test_adin_pony", ["pink"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_adin", editor, new_state, project_state) self.assertIndexNotExists("test_adin_pony", ["pink"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "index": index}) def test_remove_index(self): """ Test the RemoveIndex operation. """ project_state = self.set_up_test_model("test_rmin", multicol_index=True) self.assertTableExists("test_rmin_pony") self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) operation = migrations.RemoveIndex("Pony", "pony_test_idx") self.assertEqual(operation.describe(), "Remove index pony_test_idx from Pony") self.assertEqual( operation.migration_name_fragment, "remove_pony_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards("test_rmin", new_state) # Test the state alteration self.assertEqual( len(new_state.models["test_rmin", "pony"].options["indexes"]), 0 ) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_rmin", editor, project_state, new_state) self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards("test_rmin", editor, new_state, project_state) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": "pony_test_idx"}) # Also test a field dropped with index - sqlite remake issue operations = [ migrations.RemoveIndex("Pony", "pony_test_idx"), migrations.RemoveField("Pony", "pink"), ] self.assertColumnExists("test_rmin_pony", "pink") self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) # Test database alteration new_state = project_state.clone() self.apply_operations("test_rmin", new_state, operations=operations) self.assertColumnNotExists("test_rmin_pony", "pink") self.assertIndexNotExists("test_rmin_pony", ["pink", "weight"]) # And test reversal self.unapply_operations("test_rmin", project_state, operations=operations) self.assertIndexExists("test_rmin_pony", ["pink", "weight"]) def test_rename_index(self): app_label = "test_rnin" project_state = self.set_up_test_model(app_label, index=True) table_name = app_label + "_pony" self.assertIndexNameExists(table_name, "pony_pink_idx") self.assertIndexNameNotExists(table_name, "new_pony_test_idx") operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_name="pony_pink_idx" ) self.assertEqual( operation.describe(), "Rename index pony_pink_idx on Pony to new_pony_test_idx", ) self.assertEqual( operation.migration_name_fragment, "rename_pony_pink_idx_new_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Rename index. expected_queries = 1 if connection.features.can_rename_index else 2 with connection.schema_editor() as editor, self.assertNumQueries( expected_queries ): operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, "pony_pink_idx") self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reversal. with connection.schema_editor() as editor, self.assertNumQueries( expected_queries ): operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "pony_pink_idx") self.assertIndexNameNotExists(table_name, "new_pony_test_idx") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RenameIndex") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "old_name": "pony_pink_idx", "new_name": "new_pony_test_idx", }, ) def test_rename_index_arguments(self): msg = "RenameIndex.old_name and old_fields are mutually exclusive." with self.assertRaisesMessage(ValueError, msg): migrations.RenameIndex( "Pony", new_name="new_idx_name", old_name="old_idx_name", old_fields=("weight", "pink"), ) msg = "RenameIndex requires one of old_name and old_fields arguments to be set." with self.assertRaisesMessage(ValueError, msg): migrations.RenameIndex("Pony", new_name="new_idx_name") def test_rename_index_unnamed_index(self): app_label = "test_rninui" project_state = self.set_up_test_model(app_label, index_together=True) table_name = app_label + "_pony" self.assertIndexNameNotExists(table_name, "new_pony_test_idx") operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink") ) self.assertEqual( operation.describe(), "Rename unnamed index for ('weight', 'pink') on Pony to new_pony_test_idx", ) self.assertEqual( operation.migration_name_fragment, "rename_pony_weight_pink_new_pony_test_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) # Rename index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reverse is a no-op. with connection.schema_editor() as editor, self.assertNumQueries(0): operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reapply, RenameIndex operation is a noop when the old and new name # match. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "new_pony_test_idx") # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RenameIndex") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "new_name": "new_pony_test_idx", "old_fields": ("weight", "pink"), }, ) def test_rename_index_unknown_unnamed_index(self): app_label = "test_rninuui" project_state = self.set_up_test_model(app_label) operation = migrations.RenameIndex( "Pony", new_name="new_pony_test_idx", old_fields=("weight", "pink") ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) msg = "Found wrong number (0) of indexes for test_rninuui_pony(weight, pink)." with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, msg): operation.database_forwards(app_label, editor, project_state, new_state) def test_add_index_state_forwards(self): project_state = self.set_up_test_model("test_adinsf") index = models.Index(fields=["pink"], name="test_adinsf_pony_pink_idx") old_model = project_state.apps.get_model("test_adinsf", "Pony") new_state = project_state.clone() operation = migrations.AddIndex("Pony", index) operation.state_forwards("test_adinsf", new_state) new_model = new_state.apps.get_model("test_adinsf", "Pony") self.assertIsNot(old_model, new_model) def test_remove_index_state_forwards(self): project_state = self.set_up_test_model("test_rminsf") index = models.Index(fields=["pink"], name="test_rminsf_pony_pink_idx") migrations.AddIndex("Pony", index).state_forwards("test_rminsf", project_state) old_model = project_state.apps.get_model("test_rminsf", "Pony") new_state = project_state.clone() operation = migrations.RemoveIndex("Pony", "test_rminsf_pony_pink_idx") operation.state_forwards("test_rminsf", new_state) new_model = new_state.apps.get_model("test_rminsf", "Pony") self.assertIsNot(old_model, new_model) def test_rename_index_state_forwards(self): app_label = "test_rnidsf" project_state = self.set_up_test_model(app_label, index=True) old_model = project_state.apps.get_model(app_label, "Pony") new_state = project_state.clone() operation = migrations.RenameIndex( "Pony", new_name="new_pony_pink_idx", old_name="pony_pink_idx" ) operation.state_forwards(app_label, new_state) new_model = new_state.apps.get_model(app_label, "Pony") self.assertIsNot(old_model, new_model) self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx") def test_rename_index_state_forwards_unnamed_index(self): app_label = "test_rnidsfui" project_state = self.set_up_test_model(app_label, index_together=True) old_model = project_state.apps.get_model(app_label, "Pony") new_state = project_state.clone() operation = migrations.RenameIndex( "Pony", new_name="new_pony_pink_idx", old_fields=("weight", "pink") ) operation.state_forwards(app_label, new_state) new_model = new_state.apps.get_model(app_label, "Pony") self.assertIsNot(old_model, new_model) self.assertEqual(new_model._meta.index_together, tuple()) self.assertEqual(new_model._meta.indexes[0].name, "new_pony_pink_idx") @skipUnlessDBFeature("supports_expression_indexes") def test_add_func_index(self): app_label = "test_addfuncin" index_name = f"{app_label}_pony_abs_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) index = models.Index(Abs("weight"), name=index_name) operation = migrations.AddIndex("Pony", index) self.assertEqual( operation.describe(), "Create index test_addfuncin_pony_abs_idx on Abs(F(weight)) on model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_addfuncin_pony_abs_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 1) self.assertIndexNameNotExists(table_name, index_name) # Add index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, index_name) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameNotExists(table_name, index_name) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "index": index}) @skipUnlessDBFeature("supports_expression_indexes") def test_remove_func_index(self): app_label = "test_rmfuncin" index_name = f"{app_label}_pony_abs_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, indexes=[ models.Index(Abs("weight"), name=index_name), ], ) self.assertTableExists(table_name) self.assertIndexNameExists(table_name, index_name) operation = migrations.RemoveIndex("Pony", index_name) self.assertEqual( operation.describe(), "Remove index test_rmfuncin_pony_abs_idx from Pony", ) self.assertEqual( operation.migration_name_fragment, "remove_pony_test_rmfuncin_pony_abs_idx", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual(len(new_state.models[app_label, "pony"].options["indexes"]), 0) # Remove index. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, index_name) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, index_name) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveIndex") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": index_name}) @skipUnlessDBFeature("supports_expression_indexes") def test_alter_field_with_func_index(self): app_label = "test_alfuncin" index_name = f"{app_label}_pony_idx" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, indexes=[models.Index(Abs("pink"), name=index_name)], ) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameExists(table_name, index_name) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, index_name) def test_alter_field_with_index(self): """ Test AlterField operation with an index to ensure indexes created via Meta.indexes don't get dropped with sqlite3 remake. """ project_state = self.set_up_test_model("test_alflin", index=True) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards("test_alflin", new_state) # Test the database alteration self.assertColumnNotNull("test_alflin_pony", "pink") with connection.schema_editor() as editor: operation.database_forwards("test_alflin", editor, project_state, new_state) # Index hasn't been dropped self.assertIndexExists("test_alflin_pony", ["pink"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alflin", editor, new_state, project_state ) # Ensure the index is still there self.assertIndexExists("test_alflin_pony", ["pink"]) def test_alter_index_together(self): """ Tests the AlterIndexTogether operation. """ project_state = self.set_up_test_model("test_alinto") # Test the state alteration operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")]) self.assertEqual( operation.describe(), "Alter index_together for Pony (1 constraint(s))" ) self.assertEqual( operation.migration_name_fragment, "alter_pony_index_together", ) new_state = project_state.clone() operation.state_forwards("test_alinto", new_state) self.assertEqual( len( project_state.models["test_alinto", "pony"].options.get( "index_together", set() ) ), 0, ) self.assertEqual( len( new_state.models["test_alinto", "pony"].options.get( "index_together", set() ) ), 1, ) # Make sure there's no matching index self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"]) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_alinto", editor, project_state, new_state) self.assertIndexExists("test_alinto_pony", ["pink", "weight"]) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alinto", editor, new_state, project_state ) self.assertIndexNotExists("test_alinto_pony", ["pink", "weight"]) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterIndexTogether") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "index_together": {("pink", "weight")}} ) def test_alter_index_together_remove(self): operation = migrations.AlterIndexTogether("Pony", None) self.assertEqual( operation.describe(), "Alter index_together for Pony (0 constraint(s))" ) @skipUnlessDBFeature("allows_multiple_constraints_on_same_fields") def test_alter_index_together_remove_with_unique_together(self): app_label = "test_alintoremove_wunto" table_name = "%s_pony" % app_label project_state = self.set_up_test_model(app_label, unique_together=True) self.assertUniqueConstraintExists(table_name, ["pink", "weight"]) # Add index together. new_state = project_state.clone() operation = migrations.AlterIndexTogether("Pony", [("pink", "weight")]) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexExists(table_name, ["pink", "weight"]) # Remove index together. project_state = new_state new_state = project_state.clone() operation = migrations.AlterIndexTogether("Pony", set()) operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNotExists(table_name, ["pink", "weight"]) self.assertUniqueConstraintExists(table_name, ["pink", "weight"]) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_constraint(self): project_state = self.set_up_test_model("test_addconstraint") gt_check = models.Q(pink__gt=2) gt_constraint = models.CheckConstraint( check=gt_check, name="test_add_constraint_pony_pink_gt_2" ) gt_operation = migrations.AddConstraint("Pony", gt_constraint) self.assertEqual( gt_operation.describe(), "Create constraint test_add_constraint_pony_pink_gt_2 on model Pony", ) self.assertEqual( gt_operation.migration_name_fragment, "pony_test_add_constraint_pony_pink_gt_2", ) # Test the state alteration new_state = project_state.clone() gt_operation.state_forwards("test_addconstraint", new_state) self.assertEqual( len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 1, ) Pony = new_state.apps.get_model("test_addconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test the database alteration with connection.schema_editor() as editor: gt_operation.database_forwards( "test_addconstraint", editor, project_state, new_state ) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=1.0) # Add another one. lt_check = models.Q(pink__lt=100) lt_constraint = models.CheckConstraint( check=lt_check, name="test_add_constraint_pony_pink_lt_100" ) lt_operation = migrations.AddConstraint("Pony", lt_constraint) lt_operation.state_forwards("test_addconstraint", new_state) self.assertEqual( len(new_state.models["test_addconstraint", "pony"].options["constraints"]), 2, ) Pony = new_state.apps.get_model("test_addconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 2) with connection.schema_editor() as editor: lt_operation.database_forwards( "test_addconstraint", editor, project_state, new_state ) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=100, weight=1.0) # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_addconstraint", editor, new_state, project_state ) Pony.objects.create(pink=1, weight=1.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": gt_constraint} ) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_constraint_percent_escaping(self): app_label = "add_constraint_string_quoting" operations = [ migrations.CreateModel( "Author", fields=[ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ("surname", models.CharField(max_length=100, default="")), ("rebate", models.CharField(max_length=100)), ], ), ] from_state = self.apply_operations(app_label, ProjectState(), operations) # "%" generated in startswith lookup should be escaped in a way that is # considered a leading wildcard. check = models.Q(name__startswith="Albert") constraint = models.CheckConstraint(check=check, name="name_constraint") operation = migrations.AddConstraint("Author", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Author = to_state.apps.get_model(app_label, "Author") with self.assertRaises(IntegrityError), transaction.atomic(): Author.objects.create(name="Artur") # Literal "%" should be escaped in a way that is not a considered a # wildcard. check = models.Q(rebate__endswith="%") constraint = models.CheckConstraint(check=check, name="rebate_constraint") operation = migrations.AddConstraint("Author", constraint) from_state = to_state to_state = from_state.clone() operation.state_forwards(app_label, to_state) Author = to_state.apps.get_model(app_label, "Author") with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Author = to_state.apps.get_model(app_label, "Author") with self.assertRaises(IntegrityError), transaction.atomic(): Author.objects.create(name="Albert", rebate="10$") author = Author.objects.create(name="Albert", rebate="10%") self.assertEqual(Author.objects.get(), author) # Right-hand-side baked "%" literals should not be used for parameters # interpolation. check = ~models.Q(surname__startswith=models.F("name")) constraint = models.CheckConstraint(check=check, name="name_constraint_rhs") operation = migrations.AddConstraint("Author", constraint) from_state = to_state to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Author = to_state.apps.get_model(app_label, "Author") with self.assertRaises(IntegrityError), transaction.atomic(): Author.objects.create(name="Albert", surname="Alberto") @skipUnlessDBFeature("supports_table_check_constraints") def test_add_or_constraint(self): app_label = "test_addorconstraint" constraint_name = "add_constraint_or" from_state = self.set_up_test_model(app_label) check = models.Q(pink__gt=2, weight__gt=2) | models.Q(weight__lt=0) constraint = models.CheckConstraint(check=check, name=constraint_name) operation = migrations.AddConstraint("Pony", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Pony = to_state.apps.get_model(app_label, "Pony") with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=2, weight=3.0) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=3, weight=1.0) Pony.objects.bulk_create( [ Pony(pink=3, weight=-1.0), Pony(pink=1, weight=-1.0), Pony(pink=3, weight=3.0), ] ) @skipUnlessDBFeature("supports_table_check_constraints") def test_add_constraint_combinable(self): app_label = "test_addconstraint_combinable" operations = [ migrations.CreateModel( "Book", fields=[ ("id", models.AutoField(primary_key=True)), ("read", models.PositiveIntegerField()), ("unread", models.PositiveIntegerField()), ], ), ] from_state = self.apply_operations(app_label, ProjectState(), operations) constraint = models.CheckConstraint( check=models.Q(read=(100 - models.F("unread"))), name="test_addconstraint_combinable_sum_100", ) operation = migrations.AddConstraint("Book", constraint) to_state = from_state.clone() operation.state_forwards(app_label, to_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, from_state, to_state) Book = to_state.apps.get_model(app_label, "Book") with self.assertRaises(IntegrityError), transaction.atomic(): Book.objects.create(read=70, unread=10) Book.objects.create(read=70, unread=30) @skipUnlessDBFeature("supports_table_check_constraints") def test_remove_constraint(self): project_state = self.set_up_test_model( "test_removeconstraint", constraints=[ models.CheckConstraint( check=models.Q(pink__gt=2), name="test_remove_constraint_pony_pink_gt_2", ), models.CheckConstraint( check=models.Q(pink__lt=100), name="test_remove_constraint_pony_pink_lt_100", ), ], ) gt_operation = migrations.RemoveConstraint( "Pony", "test_remove_constraint_pony_pink_gt_2" ) self.assertEqual( gt_operation.describe(), "Remove constraint test_remove_constraint_pony_pink_gt_2 from model Pony", ) self.assertEqual( gt_operation.migration_name_fragment, "remove_pony_test_remove_constraint_pony_pink_gt_2", ) # Test state alteration new_state = project_state.clone() gt_operation.state_forwards("test_removeconstraint", new_state) self.assertEqual( len( new_state.models["test_removeconstraint", "pony"].options["constraints"] ), 1, ) Pony = new_state.apps.get_model("test_removeconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test database alteration with connection.schema_editor() as editor: gt_operation.database_forwards( "test_removeconstraint", editor, project_state, new_state ) Pony.objects.create(pink=1, weight=1.0).delete() with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=100, weight=1.0) # Remove the other one. lt_operation = migrations.RemoveConstraint( "Pony", "test_remove_constraint_pony_pink_lt_100" ) lt_operation.state_forwards("test_removeconstraint", new_state) self.assertEqual( len( new_state.models["test_removeconstraint", "pony"].options["constraints"] ), 0, ) Pony = new_state.apps.get_model("test_removeconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor: lt_operation.database_forwards( "test_removeconstraint", editor, project_state, new_state ) Pony.objects.create(pink=100, weight=1.0).delete() # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_removeconstraint", editor, new_state, project_state ) with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=1.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "name": "test_remove_constraint_pony_pink_gt_2"}, ) def test_add_partial_unique_constraint(self): project_state = self.set_up_test_model("test_addpartialuniqueconstraint") partial_unique_constraint = models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ) operation = migrations.AddConstraint("Pony", partial_unique_constraint) self.assertEqual( operation.describe(), "Create constraint test_constraint_pony_pink_for_weight_gt_5_uniq " "on model Pony", ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_addpartialuniqueconstraint", new_state) self.assertEqual( len( new_state.models["test_addpartialuniqueconstraint", "pony"].options[ "constraints" ] ), 1, ) Pony = new_state.apps.get_model("test_addpartialuniqueconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 1) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_addpartialuniqueconstraint", editor, project_state, new_state ) # Test constraint works Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_addpartialuniqueconstraint", editor, new_state, project_state ) # Test constraint doesn't work Pony.objects.create(pink=1, weight=7.0) # Test deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": partial_unique_constraint}, ) def test_remove_partial_unique_constraint(self): project_state = self.set_up_test_model( "test_removepartialuniqueconstraint", constraints=[ models.UniqueConstraint( fields=["pink"], condition=models.Q(weight__gt=5), name="test_constraint_pony_pink_for_weight_gt_5_uniq", ), ], ) gt_operation = migrations.RemoveConstraint( "Pony", "test_constraint_pony_pink_for_weight_gt_5_uniq" ) self.assertEqual( gt_operation.describe(), "Remove constraint test_constraint_pony_pink_for_weight_gt_5_uniq from " "model Pony", ) # Test state alteration new_state = project_state.clone() gt_operation.state_forwards("test_removepartialuniqueconstraint", new_state) self.assertEqual( len( new_state.models["test_removepartialuniqueconstraint", "pony"].options[ "constraints" ] ), 0, ) Pony = new_state.apps.get_model("test_removepartialuniqueconstraint", "Pony") self.assertEqual(len(Pony._meta.constraints), 0) # Test database alteration with connection.schema_editor() as editor: gt_operation.database_forwards( "test_removepartialuniqueconstraint", editor, project_state, new_state ) # Test constraint doesn't work Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=6.0) Pony.objects.create(pink=1, weight=7.0).delete() # Test reversal with connection.schema_editor() as editor: gt_operation.database_backwards( "test_removepartialuniqueconstraint", editor, new_state, project_state ) # Test constraint works if connection.features.supports_partial_indexes: with self.assertRaises(IntegrityError), transaction.atomic(): Pony.objects.create(pink=1, weight=7.0) else: Pony.objects.create(pink=1, weight=7.0) # Test deconstruction definition = gt_operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "test_constraint_pony_pink_for_weight_gt_5_uniq", }, ) def test_add_deferred_unique_constraint(self): app_label = "test_adddeferred_uc" project_state = self.set_up_test_model(app_label) deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferred_pink_constraint_add", deferrable=models.Deferrable.DEFERRED, ) operation = migrations.AddConstraint("Pony", deferred_unique_constraint) self.assertEqual( operation.describe(), "Create constraint deferred_pink_constraint_add on model Pony", ) # Add constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 3 obj.save() else: self.assertEqual(len(ctx), 0) Pony.objects.create(pink=1, weight=4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": deferred_unique_constraint}, ) def test_remove_deferred_unique_constraint(self): app_label = "test_removedeferred_uc" deferred_unique_constraint = models.UniqueConstraint( fields=["pink"], name="deferred_pink_constraint_rm", deferrable=models.Deferrable.DEFERRED, ) project_state = self.set_up_test_model( app_label, constraints=[deferred_unique_constraint] ) operation = migrations.RemoveConstraint("Pony", deferred_unique_constraint.name) self.assertEqual( operation.describe(), "Remove constraint deferred_pink_constraint_rm from model Pony", ) # Remove constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0).delete() if not connection.features.supports_deferrable_unique_constraints: self.assertEqual(len(ctx), 0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_deferrable_unique_constraints: # Unique constraint is deferred. with transaction.atomic(): obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 2 obj.save() # Constraint behavior can be changed with SET CONSTRAINTS. with self.assertRaises(IntegrityError): with transaction.atomic(), connection.cursor() as cursor: quoted_name = connection.ops.quote_name( deferred_unique_constraint.name ) cursor.execute("SET CONSTRAINTS %s IMMEDIATE" % quoted_name) obj = Pony.objects.create(pink=1, weight=4.0) obj.pink = 3 obj.save() else: Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "deferred_pink_constraint_rm", }, ) def test_add_covering_unique_constraint(self): app_label = "test_addcovering_uc" project_state = self.set_up_test_model(app_label) covering_unique_constraint = models.UniqueConstraint( fields=["pink"], name="covering_pink_constraint_add", include=["weight"], ) operation = migrations.AddConstraint("Pony", covering_unique_constraint) self.assertEqual( operation.describe(), "Create constraint covering_pink_constraint_add on model Pony", ) # Add constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_covering_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=4.0) else: self.assertEqual(len(ctx), 0) Pony.objects.create(pink=1, weight=4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": covering_unique_constraint}, ) def test_remove_covering_unique_constraint(self): app_label = "test_removecovering_uc" covering_unique_constraint = models.UniqueConstraint( fields=["pink"], name="covering_pink_constraint_rm", include=["weight"], ) project_state = self.set_up_test_model( app_label, constraints=[covering_unique_constraint] ) operation = migrations.RemoveConstraint("Pony", covering_unique_constraint.name) self.assertEqual( operation.describe(), "Remove constraint covering_pink_constraint_rm from model Pony", ) # Remove constraint. new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) with connection.schema_editor() as editor, CaptureQueriesContext( connection ) as ctx: operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=4.0).delete() if not connection.features.supports_covering_indexes: self.assertEqual(len(ctx), 0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_covering_indexes: with self.assertRaises(IntegrityError): Pony.objects.create(pink=1, weight=4.0) else: Pony.objects.create(pink=1, weight=4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], { "model_name": "Pony", "name": "covering_pink_constraint_rm", }, ) def test_alter_field_with_func_unique_constraint(self): app_label = "test_alfuncuc" constraint_name = f"{app_label}_pony_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, constraints=[ models.UniqueConstraint("pink", "weight", name=constraint_name) ], ) operation = migrations.AlterField( "Pony", "pink", models.IntegerField(null=True) ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) def test_add_func_unique_constraint(self): app_label = "test_adfuncuc" constraint_name = f"{app_label}_pony_abs_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model(app_label) constraint = models.UniqueConstraint(Abs("weight"), name=constraint_name) operation = migrations.AddConstraint("Pony", constraint) self.assertEqual( operation.describe(), "Create constraint test_adfuncuc_pony_abs_uq on model Pony", ) self.assertEqual( operation.migration_name_fragment, "pony_test_adfuncuc_pony_abs_uq", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 1 ) self.assertIndexNameNotExists(table_name, constraint_name) # Add constraint. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) Pony = new_state.apps.get_model(app_label, "Pony") Pony.objects.create(weight=4.0) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with self.assertRaises(IntegrityError): Pony.objects.create(weight=-4.0) else: self.assertIndexNameNotExists(table_name, constraint_name) Pony.objects.create(weight=-4.0) # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameNotExists(table_name, constraint_name) # Constraint doesn't work. Pony.objects.create(weight=-4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "AddConstraint") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"model_name": "Pony", "constraint": constraint}, ) def test_remove_func_unique_constraint(self): app_label = "test_rmfuncuc" constraint_name = f"{app_label}_pony_abs_uq" table_name = f"{app_label}_pony" project_state = self.set_up_test_model( app_label, constraints=[ models.UniqueConstraint(Abs("weight"), name=constraint_name), ], ) self.assertTableExists(table_name) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) operation = migrations.RemoveConstraint("Pony", constraint_name) self.assertEqual( operation.describe(), "Remove constraint test_rmfuncuc_pony_abs_uq from model Pony", ) self.assertEqual( operation.migration_name_fragment, "remove_pony_test_rmfuncuc_pony_abs_uq", ) new_state = project_state.clone() operation.state_forwards(app_label, new_state) self.assertEqual( len(new_state.models[app_label, "pony"].options["constraints"]), 0 ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) # Remove constraint. with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, constraint_name) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) Pony.objects.create(pink=1, weight=-4.0).delete() # Reversal. with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) if connection.features.supports_expression_indexes: self.assertIndexNameExists(table_name, constraint_name) with self.assertRaises(IntegrityError): Pony.objects.create(weight=-4.0) else: self.assertIndexNameNotExists(table_name, constraint_name) Pony.objects.create(weight=-4.0) # Deconstruction. definition = operation.deconstruct() self.assertEqual(definition[0], "RemoveConstraint") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"model_name": "Pony", "name": constraint_name}) def test_alter_model_options(self): """ Tests the AlterModelOptions operation. """ project_state = self.set_up_test_model("test_almoop") # Test the state alteration (no DB alteration to test) operation = migrations.AlterModelOptions( "Pony", {"permissions": [("can_groom", "Can groom")]} ) self.assertEqual(operation.describe(), "Change Meta options on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_options") new_state = project_state.clone() operation.state_forwards("test_almoop", new_state) self.assertEqual( len( project_state.models["test_almoop", "pony"].options.get( "permissions", [] ) ), 0, ) self.assertEqual( len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 1, ) self.assertEqual( new_state.models["test_almoop", "pony"].options["permissions"][0][0], "can_groom", ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelOptions") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Pony", "options": {"permissions": [("can_groom", "Can groom")]}}, ) def test_alter_model_options_emptying(self): """ The AlterModelOptions operation removes keys from the dict (#23121) """ project_state = self.set_up_test_model("test_almoop", options=True) # Test the state alteration (no DB alteration to test) operation = migrations.AlterModelOptions("Pony", {}) self.assertEqual(operation.describe(), "Change Meta options on Pony") new_state = project_state.clone() operation.state_forwards("test_almoop", new_state) self.assertEqual( len( project_state.models["test_almoop", "pony"].options.get( "permissions", [] ) ), 1, ) self.assertEqual( len(new_state.models["test_almoop", "pony"].options.get("permissions", [])), 0, ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterModelOptions") self.assertEqual(definition[1], []) self.assertEqual(definition[2], {"name": "Pony", "options": {}}) def test_alter_order_with_respect_to(self): """ Tests the AlterOrderWithRespectTo operation. """ project_state = self.set_up_test_model("test_alorwrtto", related_model=True) # Test the state alteration operation = migrations.AlterOrderWithRespectTo("Rider", "pony") self.assertEqual( operation.describe(), "Set order_with_respect_to on Rider to pony" ) self.assertEqual( operation.migration_name_fragment, "alter_rider_order_with_respect_to", ) new_state = project_state.clone() operation.state_forwards("test_alorwrtto", new_state) self.assertIsNone( project_state.models["test_alorwrtto", "rider"].options.get( "order_with_respect_to", None ) ) self.assertEqual( new_state.models["test_alorwrtto", "rider"].options.get( "order_with_respect_to", None ), "pony", ) # Make sure there's no matching index self.assertColumnNotExists("test_alorwrtto_rider", "_order") # Create some rows before alteration rendered_state = project_state.apps pony = rendered_state.get_model("test_alorwrtto", "Pony").objects.create( weight=50 ) rider1 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create( pony=pony ) rider1.friend = rider1 rider1.save() rider2 = rendered_state.get_model("test_alorwrtto", "Rider").objects.create( pony=pony ) rider2.friend = rider2 rider2.save() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_alorwrtto", editor, project_state, new_state ) self.assertColumnExists("test_alorwrtto_rider", "_order") # Check for correct value in rows updated_riders = new_state.apps.get_model( "test_alorwrtto", "Rider" ).objects.all() self.assertEqual(updated_riders[0]._order, 0) self.assertEqual(updated_riders[1]._order, 0) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_alorwrtto", editor, new_state, project_state ) self.assertColumnNotExists("test_alorwrtto_rider", "_order") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "AlterOrderWithRespectTo") self.assertEqual(definition[1], []) self.assertEqual( definition[2], {"name": "Rider", "order_with_respect_to": "pony"} ) def test_alter_model_managers(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_almoma") # Test the state alteration operation = migrations.AlterModelManagers( "Pony", managers=[ ("food_qs", FoodQuerySet.as_manager()), ("food_mgr", FoodManager("a", "b")), ("food_mgr_kwargs", FoodManager("x", "y", 3, 4)), ], ) self.assertEqual(operation.describe(), "Change managers on Pony") self.assertEqual(operation.migration_name_fragment, "alter_pony_managers") managers = project_state.models["test_almoma", "pony"].managers self.assertEqual(managers, []) new_state = project_state.clone() operation.state_forwards("test_almoma", new_state) self.assertIn(("test_almoma", "pony"), new_state.models) managers = new_state.models["test_almoma", "pony"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) rendered_state = new_state.apps model = rendered_state.get_model("test_almoma", "pony") self.assertIsInstance(model.food_qs, models.Manager) self.assertIsInstance(model.food_mgr, FoodManager) self.assertIsInstance(model.food_mgr_kwargs, FoodManager) def test_alter_model_managers_emptying(self): """ The managers on a model are set. """ project_state = self.set_up_test_model("test_almomae", manager_model=True) # Test the state alteration operation = migrations.AlterModelManagers("Food", managers=[]) self.assertEqual(operation.describe(), "Change managers on Food") self.assertIn(("test_almomae", "food"), project_state.models) managers = project_state.models["test_almomae", "food"].managers self.assertEqual(managers[0][0], "food_qs") self.assertIsInstance(managers[0][1], models.Manager) self.assertEqual(managers[1][0], "food_mgr") self.assertIsInstance(managers[1][1], FoodManager) self.assertEqual(managers[1][1].args, ("a", "b", 1, 2)) self.assertEqual(managers[2][0], "food_mgr_kwargs") self.assertIsInstance(managers[2][1], FoodManager) self.assertEqual(managers[2][1].args, ("x", "y", 3, 4)) new_state = project_state.clone() operation.state_forwards("test_almomae", new_state) managers = new_state.models["test_almomae", "food"].managers self.assertEqual(managers, []) def test_alter_fk(self): """ Creating and then altering an FK works correctly and deals with the pending SQL (#23091) """ project_state = self.set_up_test_model("test_alfk") # Test adding and then altering the FK in one go create_operation = migrations.CreateModel( name="Rider", fields=[ ("id", models.AutoField(primary_key=True)), ("pony", models.ForeignKey("Pony", models.CASCADE)), ], ) create_state = project_state.clone() create_operation.state_forwards("test_alfk", create_state) alter_operation = migrations.AlterField( model_name="Rider", name="pony", field=models.ForeignKey("Pony", models.CASCADE, editable=False), ) alter_state = create_state.clone() alter_operation.state_forwards("test_alfk", alter_state) with connection.schema_editor() as editor: create_operation.database_forwards( "test_alfk", editor, project_state, create_state ) alter_operation.database_forwards( "test_alfk", editor, create_state, alter_state ) def test_alter_fk_non_fk(self): """ Altering an FK to a non-FK works (#23244) """ # Test the state alteration operation = migrations.AlterField( model_name="Rider", name="pony", field=models.FloatField(), ) project_state, new_state = self.make_test_state( "test_afknfk", operation, related_model=True ) # Test the database alteration self.assertColumnExists("test_afknfk_rider", "pony_id") self.assertColumnNotExists("test_afknfk_rider", "pony") with connection.schema_editor() as editor: operation.database_forwards("test_afknfk", editor, project_state, new_state) self.assertColumnExists("test_afknfk_rider", "pony") self.assertColumnNotExists("test_afknfk_rider", "pony_id") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_afknfk", editor, new_state, project_state ) self.assertColumnExists("test_afknfk_rider", "pony_id") self.assertColumnNotExists("test_afknfk_rider", "pony") def test_run_sql(self): """ Tests the RunSQL operation. """ project_state = self.set_up_test_model("test_runsql") # Create the operation operation = migrations.RunSQL( # Use a multi-line string with a comment to test splitting on # SQLite and MySQL respectively. "CREATE TABLE i_love_ponies (id int, special_thing varchar(15));\n" "INSERT INTO i_love_ponies (id, special_thing) " "VALUES (1, 'i love ponies'); -- this is magic!\n" "INSERT INTO i_love_ponies (id, special_thing) " "VALUES (2, 'i love django');\n" "UPDATE i_love_ponies SET special_thing = 'Ponies' " "WHERE special_thing LIKE '%%ponies';" "UPDATE i_love_ponies SET special_thing = 'Django' " "WHERE special_thing LIKE '%django';", # Run delete queries to test for parameter substitution failure # reported in #23426 "DELETE FROM i_love_ponies WHERE special_thing LIKE '%Django%';" "DELETE FROM i_love_ponies WHERE special_thing LIKE '%%Ponies%%';" "DROP TABLE i_love_ponies", state_operations=[ migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))] ) ], ) self.assertEqual(operation.describe(), "Raw SQL operation") # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_runsql", new_state) self.assertEqual( len(new_state.models["test_runsql", "somethingelse"].fields), 1 ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") # Test SQL collection with connection.schema_editor(collect_sql=True) as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) self.assertIn("LIKE '%%ponies';", "\n".join(editor.collected_sql)) operation.database_backwards( "test_runsql", editor, project_state, new_state ) self.assertIn("LIKE '%%Ponies%%';", "\n".join(editor.collected_sql)) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) self.assertTableExists("i_love_ponies") # Make sure all the SQL was processed with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 2) cursor.execute( "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Django'" ) self.assertEqual(cursor.fetchall()[0][0], 1) cursor.execute( "SELECT COUNT(*) FROM i_love_ponies WHERE special_thing = 'Ponies'" ) self.assertEqual(cursor.fetchall()[0][0], 1) # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_runsql", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunSQL") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["reverse_sql", "sql", "state_operations"] ) # And elidable reduction self.assertIs(False, operation.reduce(operation, [])) elidable_operation = migrations.RunSQL("SELECT 1 FROM void;", elidable=True) self.assertEqual(elidable_operation.reduce(operation, []), [operation]) def test_run_sql_params(self): """ #23426 - RunSQL should accept parameters. """ project_state = self.set_up_test_model("test_runsql") # Create the operation operation = migrations.RunSQL( ["CREATE TABLE i_love_ponies (id int, special_thing varchar(15));"], ["DROP TABLE i_love_ponies"], ) param_operation = migrations.RunSQL( # forwards ( "INSERT INTO i_love_ponies (id, special_thing) VALUES (1, 'Django');", [ "INSERT INTO i_love_ponies (id, special_thing) VALUES (2, %s);", ["Ponies"], ], ( "INSERT INTO i_love_ponies (id, special_thing) VALUES (%s, %s);", ( 3, "Python", ), ), ), # backwards [ "DELETE FROM i_love_ponies WHERE special_thing = 'Django';", ["DELETE FROM i_love_ponies WHERE special_thing = 'Ponies';", None], ( "DELETE FROM i_love_ponies WHERE id = %s OR special_thing = %s;", [3, "Python"], ), ], ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") new_state = project_state.clone() # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, project_state, new_state) # Test parameter passing with connection.schema_editor() as editor: param_operation.database_forwards( "test_runsql", editor, project_state, new_state ) # Make sure all the SQL was processed with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 3) with connection.schema_editor() as editor: param_operation.database_backwards( "test_runsql", editor, new_state, project_state ) with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM i_love_ponies") self.assertEqual(cursor.fetchall()[0][0], 0) # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_runsql", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") def test_run_sql_params_invalid(self): """ #23426 - RunSQL should fail when a list of statements with an incorrect number of tuples is given. """ project_state = self.set_up_test_model("test_runsql") new_state = project_state.clone() operation = migrations.RunSQL( # forwards [["INSERT INTO foo (bar) VALUES ('buz');"]], # backwards (("DELETE FROM foo WHERE bar = 'buz';", "invalid", "parameter count"),), ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 1"): operation.database_forwards( "test_runsql", editor, project_state, new_state ) with connection.schema_editor() as editor: with self.assertRaisesMessage(ValueError, "Expected a 2-tuple but got 3"): operation.database_backwards( "test_runsql", editor, new_state, project_state ) def test_run_sql_noop(self): """ #24098 - Tests no-op RunSQL operations. """ operation = migrations.RunSQL(migrations.RunSQL.noop, migrations.RunSQL.noop) with connection.schema_editor() as editor: operation.database_forwards("test_runsql", editor, None, None) operation.database_backwards("test_runsql", editor, None, None) def test_run_sql_add_missing_semicolon_on_collect_sql(self): project_state = self.set_up_test_model("test_runsql") new_state = project_state.clone() tests = [ "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1);\n", "INSERT INTO test_runsql_pony (pink, weight) VALUES (1, 1)\n", ] for sql in tests: with self.subTest(sql=sql): operation = migrations.RunSQL(sql, migrations.RunPython.noop) with connection.schema_editor(collect_sql=True) as editor: operation.database_forwards( "test_runsql", editor, project_state, new_state ) collected_sql = "\n".join(editor.collected_sql) self.assertEqual(collected_sql.count(";"), 1) def test_run_python(self): """ Tests the RunPython operation """ project_state = self.set_up_test_model("test_runpython", mti_model=True) # Create the operation def inner_method(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") Pony.objects.create(pink=1, weight=3.55) Pony.objects.create(weight=5) def inner_method_reverse(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") Pony.objects.filter(pink=1, weight=3.55).delete() Pony.objects.filter(weight=5).delete() operation = migrations.RunPython( inner_method, reverse_code=inner_method_reverse ) self.assertEqual(operation.describe(), "Raw Python operation") # Test the state alteration does nothing new_state = project_state.clone() operation.state_forwards("test_runpython", new_state) self.assertEqual(new_state, project_state) # Test the database alteration self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0 ) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2 ) # Now test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 0 ) # Now test we can't use a string with self.assertRaisesMessage( ValueError, "RunPython must be supplied with a callable" ): migrations.RunPython("print 'ahahaha'") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["code", "reverse_code"]) # Also test reversal fails, with an operation identical to above but # without reverse_code set. no_reverse_operation = migrations.RunPython(inner_method) self.assertFalse(no_reverse_operation.reversible) with connection.schema_editor() as editor: no_reverse_operation.database_forwards( "test_runpython", editor, project_state, new_state ) with self.assertRaises(NotImplementedError): no_reverse_operation.database_backwards( "test_runpython", editor, new_state, project_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 2 ) def create_ponies(models, schema_editor): Pony = models.get_model("test_runpython", "Pony") pony1 = Pony.objects.create(pink=1, weight=3.55) self.assertIsNot(pony1.pk, None) pony2 = Pony.objects.create(weight=5) self.assertIsNot(pony2.pk, None) self.assertNotEqual(pony1.pk, pony2.pk) operation = migrations.RunPython(create_ponies) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 4 ) # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["code"]) def create_shetlandponies(models, schema_editor): ShetlandPony = models.get_model("test_runpython", "ShetlandPony") pony1 = ShetlandPony.objects.create(weight=4.0) self.assertIsNot(pony1.pk, None) pony2 = ShetlandPony.objects.create(weight=5.0) self.assertIsNot(pony2.pk, None) self.assertNotEqual(pony1.pk, pony2.pk) operation = migrations.RunPython(create_shetlandponies) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) self.assertEqual( project_state.apps.get_model("test_runpython", "Pony").objects.count(), 6 ) self.assertEqual( project_state.apps.get_model( "test_runpython", "ShetlandPony" ).objects.count(), 2, ) # And elidable reduction self.assertIs(False, operation.reduce(operation, [])) elidable_operation = migrations.RunPython(inner_method, elidable=True) self.assertEqual(elidable_operation.reduce(operation, []), [operation]) def test_run_python_atomic(self): """ Tests the RunPython operation correctly handles the "atomic" keyword """ project_state = self.set_up_test_model("test_runpythonatomic", mti_model=True) def inner_method(models, schema_editor): Pony = models.get_model("test_runpythonatomic", "Pony") Pony.objects.create(pink=1, weight=3.55) raise ValueError("Adrian hates ponies.") # Verify atomicity when applying. atomic_migration = Migration("test", "test_runpythonatomic") atomic_migration.operations = [ migrations.RunPython(inner_method, reverse_code=inner_method) ] non_atomic_migration = Migration("test", "test_runpythonatomic") non_atomic_migration.operations = [ migrations.RunPython(inner_method, reverse_code=inner_method, atomic=False) ] # If we're a fully-transactional database, both versions should rollback if connection.features.can_rollback_ddl: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) # Otherwise, the non-atomic operation should leave a row there else: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.apply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 1, ) # Reset object count to zero and verify atomicity when unapplying. project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.all().delete() # On a fully-transactional database, both versions rollback. if connection.features.can_rollback_ddl: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) # Otherwise, the non-atomic operation leaves a row there. else: self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 0, ) with self.assertRaises(ValueError): with connection.schema_editor() as editor: non_atomic_migration.unapply(project_state, editor) self.assertEqual( project_state.apps.get_model( "test_runpythonatomic", "Pony" ).objects.count(), 1, ) # Verify deconstruction. definition = non_atomic_migration.operations[0].deconstruct() self.assertEqual(definition[0], "RunPython") self.assertEqual(definition[1], []) self.assertEqual(sorted(definition[2]), ["atomic", "code", "reverse_code"]) def test_run_python_related_assignment(self): """ #24282 - Model changes to a FK reverse side update the model on the FK side as well. """ def inner_method(models, schema_editor): Author = models.get_model("test_authors", "Author") Book = models.get_model("test_books", "Book") author = Author.objects.create(name="Hemingway") Book.objects.create(title="Old Man and The Sea", author=author) create_author = migrations.CreateModel( "Author", [ ("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_book = migrations.CreateModel( "Book", [ ("id", models.AutoField(primary_key=True)), ("title", models.CharField(max_length=100)), ("author", models.ForeignKey("test_authors.Author", models.CASCADE)), ], options={}, ) add_hometown = migrations.AddField( "Author", "hometown", models.CharField(max_length=100), ) create_old_man = migrations.RunPython(inner_method, inner_method) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_author.state_forwards("test_authors", new_state) create_author.database_forwards( "test_authors", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_book.state_forwards("test_books", new_state) create_book.database_forwards( "test_books", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: add_hometown.state_forwards("test_authors", new_state) add_hometown.database_forwards( "test_authors", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_old_man.state_forwards("test_books", new_state) create_old_man.database_forwards( "test_books", editor, project_state, new_state ) def test_model_with_bigautofield(self): """ A model with BigAutoField can be created. """ def create_data(models, schema_editor): Author = models.get_model("test_author", "Author") Book = models.get_model("test_book", "Book") author1 = Author.objects.create(name="Hemingway") Book.objects.create(title="Old Man and The Sea", author=author1) Book.objects.create(id=2**33, title="A farewell to arms", author=author1) author2 = Author.objects.create(id=2**33, name="Remarque") Book.objects.create(title="All quiet on the western front", author=author2) Book.objects.create(title="Arc de Triomphe", author=author2) create_author = migrations.CreateModel( "Author", [ ("id", models.BigAutoField(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_book = migrations.CreateModel( "Book", [ ("id", models.BigAutoField(primary_key=True)), ("title", models.CharField(max_length=100)), ( "author", models.ForeignKey( to="test_author.Author", on_delete=models.CASCADE ), ), ], options={}, ) fill_data = migrations.RunPython(create_data) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_author.state_forwards("test_author", new_state) create_author.database_forwards( "test_author", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_book.state_forwards("test_book", new_state) create_book.database_forwards("test_book", editor, project_state, new_state) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_data.state_forwards("fill_data", new_state) fill_data.database_forwards("fill_data", editor, project_state, new_state) def _test_autofield_foreignfield_growth( self, source_field, target_field, target_value ): """ A field may be migrated in the following ways: - AutoField to BigAutoField - SmallAutoField to AutoField - SmallAutoField to BigAutoField """ def create_initial_data(models, schema_editor): Article = models.get_model("test_article", "Article") Blog = models.get_model("test_blog", "Blog") blog = Blog.objects.create(name="web development done right") Article.objects.create(name="Frameworks", blog=blog) Article.objects.create(name="Programming Languages", blog=blog) def create_big_data(models, schema_editor): Article = models.get_model("test_article", "Article") Blog = models.get_model("test_blog", "Blog") blog2 = Blog.objects.create(name="Frameworks", id=target_value) Article.objects.create(name="Django", blog=blog2) Article.objects.create(id=target_value, name="Django2", blog=blog2) create_blog = migrations.CreateModel( "Blog", [ ("id", source_field(primary_key=True)), ("name", models.CharField(max_length=100)), ], options={}, ) create_article = migrations.CreateModel( "Article", [ ("id", source_field(primary_key=True)), ( "blog", models.ForeignKey(to="test_blog.Blog", on_delete=models.CASCADE), ), ("name", models.CharField(max_length=100)), ("data", models.TextField(default="")), ], options={}, ) fill_initial_data = migrations.RunPython( create_initial_data, create_initial_data ) fill_big_data = migrations.RunPython(create_big_data, create_big_data) grow_article_id = migrations.AlterField( "Article", "id", target_field(primary_key=True) ) grow_blog_id = migrations.AlterField( "Blog", "id", target_field(primary_key=True) ) project_state = ProjectState() new_state = project_state.clone() with connection.schema_editor() as editor: create_blog.state_forwards("test_blog", new_state) create_blog.database_forwards("test_blog", editor, project_state, new_state) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: create_article.state_forwards("test_article", new_state) create_article.database_forwards( "test_article", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_initial_data.state_forwards("fill_initial_data", new_state) fill_initial_data.database_forwards( "fill_initial_data", editor, project_state, new_state ) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: grow_article_id.state_forwards("test_article", new_state) grow_article_id.database_forwards( "test_article", editor, project_state, new_state ) state = new_state.clone() article = state.apps.get_model("test_article.Article") self.assertIsInstance(article._meta.pk, target_field) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: grow_blog_id.state_forwards("test_blog", new_state) grow_blog_id.database_forwards( "test_blog", editor, project_state, new_state ) state = new_state.clone() blog = state.apps.get_model("test_blog.Blog") self.assertIsInstance(blog._meta.pk, target_field) project_state = new_state new_state = new_state.clone() with connection.schema_editor() as editor: fill_big_data.state_forwards("fill_big_data", new_state) fill_big_data.database_forwards( "fill_big_data", editor, project_state, new_state ) def test_autofield__bigautofield_foreignfield_growth(self): """A field may be migrated from AutoField to BigAutoField.""" self._test_autofield_foreignfield_growth( models.AutoField, models.BigAutoField, 2**33, ) def test_smallfield_autofield_foreignfield_growth(self): """A field may be migrated from SmallAutoField to AutoField.""" self._test_autofield_foreignfield_growth( models.SmallAutoField, models.AutoField, 2**22, ) def test_smallfield_bigautofield_foreignfield_growth(self): """A field may be migrated from SmallAutoField to BigAutoField.""" self._test_autofield_foreignfield_growth( models.SmallAutoField, models.BigAutoField, 2**33, ) def test_run_python_noop(self): """ #24098 - Tests no-op RunPython operations. """ project_state = ProjectState() new_state = project_state.clone() operation = migrations.RunPython( migrations.RunPython.noop, migrations.RunPython.noop ) with connection.schema_editor() as editor: operation.database_forwards( "test_runpython", editor, project_state, new_state ) operation.database_backwards( "test_runpython", editor, new_state, project_state ) def test_separate_database_and_state(self): """ Tests the SeparateDatabaseAndState operation. """ project_state = self.set_up_test_model("test_separatedatabaseandstate") # Create the operation database_operation = migrations.RunSQL( "CREATE TABLE i_love_ponies (id int, special_thing int);", "DROP TABLE i_love_ponies;", ) state_operation = migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))] ) operation = migrations.SeparateDatabaseAndState( state_operations=[state_operation], database_operations=[database_operation] ) self.assertEqual( operation.describe(), "Custom state/database change combination" ) # Test the state alteration new_state = project_state.clone() operation.state_forwards("test_separatedatabaseandstate", new_state) self.assertEqual( len( new_state.models[ "test_separatedatabaseandstate", "somethingelse" ].fields ), 1, ) # Make sure there's no table self.assertTableNotExists("i_love_ponies") # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards( "test_separatedatabaseandstate", editor, project_state, new_state ) self.assertTableExists("i_love_ponies") # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards( "test_separatedatabaseandstate", editor, new_state, project_state ) self.assertTableNotExists("i_love_ponies") # And deconstruction definition = operation.deconstruct() self.assertEqual(definition[0], "SeparateDatabaseAndState") self.assertEqual(definition[1], []) self.assertEqual( sorted(definition[2]), ["database_operations", "state_operations"] ) def test_separate_database_and_state2(self): """ A complex SeparateDatabaseAndState operation: Multiple operations both for state and database. Verify the state dependencies within each list and that state ops don't affect the database. """ app_label = "test_separatedatabaseandstate2" project_state = self.set_up_test_model(app_label) # Create the operation database_operations = [ migrations.CreateModel( "ILovePonies", [("id", models.AutoField(primary_key=True))], options={"db_table": "iloveponies"}, ), migrations.CreateModel( "ILoveMorePonies", # We use IntegerField and not AutoField because # the model is going to be deleted immediately # and with an AutoField this fails on Oracle [("id", models.IntegerField(primary_key=True))], options={"db_table": "ilovemoreponies"}, ), migrations.DeleteModel("ILoveMorePonies"), migrations.CreateModel( "ILoveEvenMorePonies", [("id", models.AutoField(primary_key=True))], options={"db_table": "iloveevenmoreponies"}, ), ] state_operations = [ migrations.CreateModel( "SomethingElse", [("id", models.AutoField(primary_key=True))], options={"db_table": "somethingelse"}, ), migrations.DeleteModel("SomethingElse"), migrations.CreateModel( "SomethingCompletelyDifferent", [("id", models.AutoField(primary_key=True))], options={"db_table": "somethingcompletelydifferent"}, ), ] operation = migrations.SeparateDatabaseAndState( state_operations=state_operations, database_operations=database_operations, ) # Test the state alteration new_state = project_state.clone() operation.state_forwards(app_label, new_state) def assertModelsAndTables(after_db): # Tables and models exist, or don't, as they should: self.assertNotIn((app_label, "somethingelse"), new_state.models) self.assertEqual( len(new_state.models[app_label, "somethingcompletelydifferent"].fields), 1, ) self.assertNotIn((app_label, "iloveponiesonies"), new_state.models) self.assertNotIn((app_label, "ilovemoreponies"), new_state.models) self.assertNotIn((app_label, "iloveevenmoreponies"), new_state.models) self.assertTableNotExists("somethingelse") self.assertTableNotExists("somethingcompletelydifferent") self.assertTableNotExists("ilovemoreponies") if after_db: self.assertTableExists("iloveponies") self.assertTableExists("iloveevenmoreponies") else: self.assertTableNotExists("iloveponies") self.assertTableNotExists("iloveevenmoreponies") assertModelsAndTables(after_db=False) # Test the database alteration with connection.schema_editor() as editor: operation.database_forwards(app_label, editor, project_state, new_state) assertModelsAndTables(after_db=True) # And test reversal self.assertTrue(operation.reversible) with connection.schema_editor() as editor: operation.database_backwards(app_label, editor, new_state, project_state) assertModelsAndTables(after_db=False) class SwappableOperationTests(OperationTestBase): """ Key operations ignore swappable models (we don't want to replicate all of them here, as the functionality is in a common base class anyway) """ available_apps = ["migrations"] @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_create_ignore_swapped(self): """ The CreateTable operation ignores swapped models. """ operation = migrations.CreateModel( "Pony", [ ("id", models.AutoField(primary_key=True)), ("pink", models.IntegerField(default=1)), ], options={ "swappable": "TEST_SWAP_MODEL", }, ) # Test the state alteration (it should still be there!) project_state = ProjectState() new_state = project_state.clone() operation.state_forwards("test_crigsw", new_state) self.assertEqual(new_state.models["test_crigsw", "pony"].name, "Pony") self.assertEqual(len(new_state.models["test_crigsw", "pony"].fields), 2) # Test the database alteration self.assertTableNotExists("test_crigsw_pony") with connection.schema_editor() as editor: operation.database_forwards("test_crigsw", editor, project_state, new_state) self.assertTableNotExists("test_crigsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_crigsw", editor, new_state, project_state ) self.assertTableNotExists("test_crigsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_delete_ignore_swapped(self): """ Tests the DeleteModel operation ignores swapped models. """ operation = migrations.DeleteModel("Pony") project_state, new_state = self.make_test_state("test_dligsw", operation) # Test the database alteration self.assertTableNotExists("test_dligsw_pony") with connection.schema_editor() as editor: operation.database_forwards("test_dligsw", editor, project_state, new_state) self.assertTableNotExists("test_dligsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_dligsw", editor, new_state, project_state ) self.assertTableNotExists("test_dligsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_add_field_ignore_swapped(self): """ Tests the AddField operation. """ # Test the state alteration operation = migrations.AddField( "Pony", "height", models.FloatField(null=True, default=5), ) project_state, new_state = self.make_test_state("test_adfligsw", operation) # Test the database alteration self.assertTableNotExists("test_adfligsw_pony") with connection.schema_editor() as editor: operation.database_forwards( "test_adfligsw", editor, project_state, new_state ) self.assertTableNotExists("test_adfligsw_pony") # And test reversal with connection.schema_editor() as editor: operation.database_backwards( "test_adfligsw", editor, new_state, project_state ) self.assertTableNotExists("test_adfligsw_pony") @override_settings(TEST_SWAP_MODEL="migrations.SomeFakeModel") def test_indexes_ignore_swapped(self): """ Add/RemoveIndex operations ignore swapped models. """ operation = migrations.AddIndex( "Pony", models.Index(fields=["pink"], name="my_name_idx") ) project_state, new_state = self.make_test_state("test_adinigsw", operation) with connection.schema_editor() as editor: # No database queries should be run for swapped models operation.database_forwards( "test_adinigsw", editor, project_state, new_state ) operation.database_backwards( "test_adinigsw", editor, new_state, project_state ) operation = migrations.RemoveIndex( "Pony", models.Index(fields=["pink"], name="my_name_idx") ) project_state, new_state = self.make_test_state("test_rminigsw", operation) with connection.schema_editor() as editor: operation.database_forwards( "test_rminigsw", editor, project_state, new_state ) operation.database_backwards( "test_rminigsw", editor, new_state, project_state ) class TestCreateModel(SimpleTestCase): def test_references_model_mixin(self): migrations.CreateModel( "name", fields=[], bases=(Mixin, models.Model), ).references_model("other_model", "migrations") class FieldOperationTests(SimpleTestCase): def test_references_model(self): operation = FieldOperation( "MoDel", "field", models.ForeignKey("Other", models.CASCADE) ) # Model name match. self.assertIs(operation.references_model("mOdEl", "migrations"), True) # Referenced field. self.assertIs(operation.references_model("oTher", "migrations"), True) # Doesn't reference. self.assertIs(operation.references_model("Whatever", "migrations"), False) def test_references_field_by_name(self): operation = FieldOperation("MoDel", "field", models.BooleanField(default=False)) self.assertIs(operation.references_field("model", "field", "migrations"), True) def test_references_field_by_remote_field_model(self): operation = FieldOperation( "Model", "field", models.ForeignKey("Other", models.CASCADE) ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_references_field_by_from_fields(self): operation = FieldOperation( "Model", "field", models.fields.related.ForeignObject( "Other", models.CASCADE, ["from"], ["to"] ), ) self.assertIs(operation.references_field("Model", "from", "migrations"), True) self.assertIs(operation.references_field("Model", "to", "migrations"), False) self.assertIs(operation.references_field("Other", "from", "migrations"), False) self.assertIs(operation.references_field("Model", "to", "migrations"), False) def test_references_field_by_to_fields(self): operation = FieldOperation( "Model", "field", models.ForeignKey("Other", models.CASCADE, to_field="field"), ) self.assertIs(operation.references_field("Other", "field", "migrations"), True) self.assertIs( operation.references_field("Other", "whatever", "migrations"), False ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_references_field_by_through(self): operation = FieldOperation( "Model", "field", models.ManyToManyField("Other", through="Through") ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Through", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Missing", "whatever", "migrations"), False ) def test_reference_field_by_through_fields(self): operation = FieldOperation( "Model", "field", models.ManyToManyField( "Other", through="Through", through_fields=("first", "second") ), ) self.assertIs( operation.references_field("Other", "whatever", "migrations"), True ) self.assertIs( operation.references_field("Through", "whatever", "migrations"), False ) self.assertIs( operation.references_field("Through", "first", "migrations"), True ) self.assertIs( operation.references_field("Through", "second", "migrations"), True )
bf048add726d0771208647d33ff453b935a33a810328ea7210ff3c114a85a89b
import datetime from xml.dom import minidom from django.contrib.sites.models import Site from django.contrib.syndication import views from django.core.exceptions import ImproperlyConfigured from django.test import TestCase, override_settings from django.test.utils import requires_tz_support from django.utils import timezone from django.utils.feedgenerator import ( Atom1Feed, Rss201rev2Feed, rfc2822_date, rfc3339_date, ) from .models import Article, Entry TZ = timezone.get_default_timezone() class FeedTestCase(TestCase): @classmethod def setUpTestData(cls): cls.e1 = Entry.objects.create( title="My first entry", updated=datetime.datetime(1980, 1, 1, 12, 30), published=datetime.datetime(1986, 9, 25, 20, 15, 00), ) cls.e2 = Entry.objects.create( title="My second entry", updated=datetime.datetime(2008, 1, 2, 12, 30), published=datetime.datetime(2006, 3, 17, 18, 0), ) cls.e3 = Entry.objects.create( title="My third entry", updated=datetime.datetime(2008, 1, 2, 13, 30), published=datetime.datetime(2005, 6, 14, 10, 45), ) cls.e4 = Entry.objects.create( title="A & B < C > D", updated=datetime.datetime(2008, 1, 3, 13, 30), published=datetime.datetime(2005, 11, 25, 12, 11, 23), ) cls.e5 = Entry.objects.create( title="My last entry", updated=datetime.datetime(2013, 1, 20, 0, 0), published=datetime.datetime(2013, 3, 25, 20, 0), ) cls.a1 = Article.objects.create( title="My first article", entry=cls.e1, updated=datetime.datetime(1986, 11, 21, 9, 12, 18), published=datetime.datetime(1986, 10, 21, 9, 12, 18), ) def assertChildNodes(self, elem, expected): actual = {n.nodeName for n in elem.childNodes} expected = set(expected) self.assertEqual(actual, expected) def assertChildNodeContent(self, elem, expected): for k, v in expected.items(): self.assertEqual(elem.getElementsByTagName(k)[0].firstChild.wholeText, v) def assertCategories(self, elem, expected): self.assertEqual( { i.firstChild.wholeText for i in elem.childNodes if i.nodeName == "category" }, set(expected), ) @override_settings(ROOT_URLCONF="syndication_tests.urls") class SyndicationFeedTest(FeedTestCase): """ Tests for the high-level syndication feed framework. """ @classmethod def setUpClass(cls): super().setUpClass() # This cleanup is necessary because contrib.sites cache # makes tests interfere with each other, see #11505 Site.objects.clear_cache() def test_rss2_feed(self): """ Test the structure and content of feeds generated by Rss201rev2Feed. """ response = self.client.get("/syndication/rss2/") doc = minidom.parseString(response.content) # Making sure there's only 1 `rss` element and that the correct # RSS version was specified. feed_elem = doc.getElementsByTagName("rss") self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute("version"), "2.0") self.assertEqual( feed.getElementsByTagName("language")[0].firstChild.nodeValue, "en" ) # Making sure there's only one `channel` element w/in the # `rss` element. chan_elem = feed.getElementsByTagName("channel") self.assertEqual(len(chan_elem), 1) chan = chan_elem[0] # Find the last build date d = Entry.objects.latest("published").published last_build_date = rfc2822_date(timezone.make_aware(d, TZ)) self.assertChildNodes( chan, [ "title", "link", "description", "language", "lastBuildDate", "item", "atom:link", "ttl", "copyright", "category", ], ) self.assertChildNodeContent( chan, { "title": "My blog", "description": "A more thorough description of my blog.", "link": "http://example.com/blog/", "language": "en", "lastBuildDate": last_build_date, "ttl": "600", "copyright": "Copyright (c) 2007, Sally Smith", }, ) self.assertCategories(chan, ["python", "django"]) # Ensure the content of the channel is correct self.assertChildNodeContent( chan, { "title": "My blog", "link": "http://example.com/blog/", }, ) # Check feed_url is passed self.assertEqual( chan.getElementsByTagName("atom:link")[0].getAttribute("href"), "http://example.com/syndication/rss2/", ) # Find the pubdate of the first feed item d = Entry.objects.get(pk=self.e1.pk).published pub_date = rfc2822_date(timezone.make_aware(d, TZ)) items = chan.getElementsByTagName("item") self.assertEqual(len(items), Entry.objects.count()) self.assertChildNodeContent( items[0], { "title": "My first entry", "description": "Overridden description: My first entry", "link": "http://example.com/blog/%s/" % self.e1.pk, "guid": "http://example.com/blog/%s/" % self.e1.pk, "pubDate": pub_date, "author": "[email protected] (Sally Smith)", "comments": "/blog/%s/comments" % self.e1.pk, }, ) self.assertCategories(items[0], ["python", "testing"]) for item in items: self.assertChildNodes( item, [ "title", "link", "description", "guid", "category", "pubDate", "author", "comments", ], ) # Assert that <guid> does not have any 'isPermaLink' attribute self.assertIsNone( item.getElementsByTagName("guid")[0].attributes.get("isPermaLink") ) def test_rss2_feed_with_callable_object(self): response = self.client.get("/syndication/rss2/with-callable-object/") doc = minidom.parseString(response.content) chan = doc.getElementsByTagName("rss")[0].getElementsByTagName("channel")[0] self.assertChildNodeContent(chan, {"ttl": "700"}) def test_rss2_feed_guid_permalink_false(self): """ Test if the 'isPermaLink' attribute of <guid> element of an item in the RSS feed is 'false'. """ response = self.client.get("/syndication/rss2/guid_ispermalink_false/") doc = minidom.parseString(response.content) chan = doc.getElementsByTagName("rss")[0].getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") for item in items: self.assertEqual( item.getElementsByTagName("guid")[0] .attributes.get("isPermaLink") .value, "false", ) def test_rss2_feed_guid_permalink_true(self): """ Test if the 'isPermaLink' attribute of <guid> element of an item in the RSS feed is 'true'. """ response = self.client.get("/syndication/rss2/guid_ispermalink_true/") doc = minidom.parseString(response.content) chan = doc.getElementsByTagName("rss")[0].getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") for item in items: self.assertEqual( item.getElementsByTagName("guid")[0] .attributes.get("isPermaLink") .value, "true", ) def test_rss2_single_enclosure(self): response = self.client.get("/syndication/rss2/single-enclosure/") doc = minidom.parseString(response.content) chan = doc.getElementsByTagName("rss")[0].getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") for item in items: enclosures = item.getElementsByTagName("enclosure") self.assertEqual(len(enclosures), 1) def test_rss2_multiple_enclosures(self): with self.assertRaisesMessage( ValueError, "RSS feed items may only have one enclosure, see " "http://www.rssboard.org/rss-profile#element-channel-item-enclosure", ): self.client.get("/syndication/rss2/multiple-enclosure/") def test_rss091_feed(self): """ Test the structure and content of feeds generated by RssUserland091Feed. """ response = self.client.get("/syndication/rss091/") doc = minidom.parseString(response.content) # Making sure there's only 1 `rss` element and that the correct # RSS version was specified. feed_elem = doc.getElementsByTagName("rss") self.assertEqual(len(feed_elem), 1) feed = feed_elem[0] self.assertEqual(feed.getAttribute("version"), "0.91") # Making sure there's only one `channel` element w/in the # `rss` element. chan_elem = feed.getElementsByTagName("channel") self.assertEqual(len(chan_elem), 1) chan = chan_elem[0] self.assertChildNodes( chan, [ "title", "link", "description", "language", "lastBuildDate", "item", "atom:link", "ttl", "copyright", "category", ], ) # Ensure the content of the channel is correct self.assertChildNodeContent( chan, { "title": "My blog", "link": "http://example.com/blog/", }, ) self.assertCategories(chan, ["python", "django"]) # Check feed_url is passed self.assertEqual( chan.getElementsByTagName("atom:link")[0].getAttribute("href"), "http://example.com/syndication/rss091/", ) items = chan.getElementsByTagName("item") self.assertEqual(len(items), Entry.objects.count()) self.assertChildNodeContent( items[0], { "title": "My first entry", "description": "Overridden description: My first entry", "link": "http://example.com/blog/%s/" % self.e1.pk, }, ) for item in items: self.assertChildNodes(item, ["title", "link", "description"]) self.assertCategories(item, []) def test_atom_feed(self): """ Test the structure and content of feeds generated by Atom1Feed. """ response = self.client.get("/syndication/atom/") feed = minidom.parseString(response.content).firstChild self.assertEqual(feed.nodeName, "feed") self.assertEqual(feed.getAttribute("xmlns"), "http://www.w3.org/2005/Atom") self.assertChildNodes( feed, [ "title", "subtitle", "link", "id", "updated", "entry", "rights", "category", "author", ], ) for link in feed.getElementsByTagName("link"): if link.getAttribute("rel") == "self": self.assertEqual( link.getAttribute("href"), "http://example.com/syndication/atom/" ) entries = feed.getElementsByTagName("entry") self.assertEqual(len(entries), Entry.objects.count()) for entry in entries: self.assertChildNodes( entry, [ "title", "link", "id", "summary", "category", "updated", "published", "rights", "author", ], ) summary = entry.getElementsByTagName("summary")[0] self.assertEqual(summary.getAttribute("type"), "html") def test_atom_feed_published_and_updated_elements(self): """ The published and updated elements are not the same and now adhere to RFC 4287. """ response = self.client.get("/syndication/atom/") feed = minidom.parseString(response.content).firstChild entries = feed.getElementsByTagName("entry") published = entries[0].getElementsByTagName("published")[0].firstChild.wholeText updated = entries[0].getElementsByTagName("updated")[0].firstChild.wholeText self.assertNotEqual(published, updated) def test_atom_single_enclosure(self): response = self.client.get("/syndication/atom/single-enclosure/") feed = minidom.parseString(response.content).firstChild items = feed.getElementsByTagName("entry") for item in items: links = item.getElementsByTagName("link") links = [link for link in links if link.getAttribute("rel") == "enclosure"] self.assertEqual(len(links), 1) def test_atom_multiple_enclosures(self): response = self.client.get("/syndication/atom/multiple-enclosure/") feed = minidom.parseString(response.content).firstChild items = feed.getElementsByTagName("entry") for item in items: links = item.getElementsByTagName("link") links = [link for link in links if link.getAttribute("rel") == "enclosure"] self.assertEqual(len(links), 2) def test_latest_post_date(self): """ Both the published and updated dates are considered when determining the latest post date. """ # this feed has a `published` element with the latest date response = self.client.get("/syndication/atom/") feed = minidom.parseString(response.content).firstChild updated = feed.getElementsByTagName("updated")[0].firstChild.wholeText d = Entry.objects.latest("published").published latest_published = rfc3339_date(timezone.make_aware(d, TZ)) self.assertEqual(updated, latest_published) # this feed has an `updated` element with the latest date response = self.client.get("/syndication/latest/") feed = minidom.parseString(response.content).firstChild updated = feed.getElementsByTagName("updated")[0].firstChild.wholeText d = Entry.objects.exclude(title="My last entry").latest("updated").updated latest_updated = rfc3339_date(timezone.make_aware(d, TZ)) self.assertEqual(updated, latest_updated) def test_custom_feed_generator(self): response = self.client.get("/syndication/custom/") feed = minidom.parseString(response.content).firstChild self.assertEqual(feed.nodeName, "feed") self.assertEqual(feed.getAttribute("django"), "rocks") self.assertChildNodes( feed, [ "title", "subtitle", "link", "id", "updated", "entry", "spam", "rights", "category", "author", ], ) entries = feed.getElementsByTagName("entry") self.assertEqual(len(entries), Entry.objects.count()) for entry in entries: self.assertEqual(entry.getAttribute("bacon"), "yum") self.assertChildNodes( entry, [ "title", "link", "id", "summary", "ministry", "rights", "author", "updated", "published", "category", ], ) summary = entry.getElementsByTagName("summary")[0] self.assertEqual(summary.getAttribute("type"), "html") def test_feed_generator_language_attribute(self): response = self.client.get("/syndication/language/") feed = minidom.parseString(response.content).firstChild self.assertEqual( feed.firstChild.getElementsByTagName("language")[0].firstChild.nodeValue, "de", ) def test_title_escaping(self): """ Titles are escaped correctly in RSS feeds. """ response = self.client.get("/syndication/rss2/") doc = minidom.parseString(response.content) for item in doc.getElementsByTagName("item"): link = item.getElementsByTagName("link")[0] if link.firstChild.wholeText == "http://example.com/blog/4/": title = item.getElementsByTagName("title")[0] self.assertEqual(title.firstChild.wholeText, "A &amp; B &lt; C &gt; D") def test_naive_datetime_conversion(self): """ Datetimes are correctly converted to the local time zone. """ # Naive date times passed in get converted to the local time zone, so # check the received zone offset against the local offset. response = self.client.get("/syndication/naive-dates/") doc = minidom.parseString(response.content) updated = doc.getElementsByTagName("updated")[0].firstChild.wholeText d = Entry.objects.latest("published").published latest = rfc3339_date(timezone.make_aware(d, TZ)) self.assertEqual(updated, latest) def test_aware_datetime_conversion(self): """ Datetimes with timezones don't get trodden on. """ response = self.client.get("/syndication/aware-dates/") doc = minidom.parseString(response.content) published = doc.getElementsByTagName("published")[0].firstChild.wholeText self.assertEqual(published[-6:], "+00:42") def test_feed_no_content_self_closing_tag(self): tests = [ (Atom1Feed, "link"), (Rss201rev2Feed, "atom:link"), ] for feedgenerator, tag in tests: with self.subTest(feedgenerator=feedgenerator.__name__): feed = feedgenerator( title="title", link="https://example.com", description="self closing tags test", feed_url="https://feed.url.com", ) doc = feed.writeString("utf-8") self.assertIn(f'<{tag} href="https://feed.url.com" rel="self"/>', doc) @requires_tz_support def test_feed_last_modified_time_naive_date(self): """ Tests the Last-Modified header with naive publication dates. """ response = self.client.get("/syndication/naive-dates/") self.assertEqual( response.headers["Last-Modified"], "Tue, 26 Mar 2013 01:00:00 GMT" ) def test_feed_last_modified_time(self): """ Tests the Last-Modified header with aware publication dates. """ response = self.client.get("/syndication/aware-dates/") self.assertEqual( response.headers["Last-Modified"], "Mon, 25 Mar 2013 19:18:00 GMT" ) # No last-modified when feed has no item_pubdate response = self.client.get("/syndication/no_pubdate/") self.assertFalse(response.has_header("Last-Modified")) def test_feed_url(self): """ The feed_url can be overridden. """ response = self.client.get("/syndication/feedurl/") doc = minidom.parseString(response.content) for link in doc.getElementsByTagName("link"): if link.getAttribute("rel") == "self": self.assertEqual( link.getAttribute("href"), "http://example.com/customfeedurl/" ) def test_secure_urls(self): """ Test URLs are prefixed with https:// when feed is requested over HTTPS. """ response = self.client.get( "/syndication/rss2/", **{ "wsgi.url_scheme": "https", }, ) doc = minidom.parseString(response.content) chan = doc.getElementsByTagName("channel")[0] self.assertEqual( chan.getElementsByTagName("link")[0].firstChild.wholeText[0:5], "https" ) atom_link = chan.getElementsByTagName("atom:link")[0] self.assertEqual(atom_link.getAttribute("href")[0:5], "https") for link in doc.getElementsByTagName("link"): if link.getAttribute("rel") == "self": self.assertEqual(link.getAttribute("href")[0:5], "https") def test_item_link_error(self): """ An ImproperlyConfigured is raised if no link could be found for the item(s). """ msg = ( "Give your Article class a get_absolute_url() method, or define " "an item_link() method in your Feed class." ) with self.assertRaisesMessage(ImproperlyConfigured, msg): self.client.get("/syndication/articles/") def test_template_feed(self): """ The item title and description can be overridden with templates. """ response = self.client.get("/syndication/template/") doc = minidom.parseString(response.content) feed = doc.getElementsByTagName("rss")[0] chan = feed.getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") self.assertChildNodeContent( items[0], { "title": "Title in your templates: My first entry\n", "description": "Description in your templates: My first entry\n", "link": "http://example.com/blog/%s/" % self.e1.pk, }, ) def test_template_context_feed(self): """ Custom context data can be passed to templates for title and description. """ response = self.client.get("/syndication/template_context/") doc = minidom.parseString(response.content) feed = doc.getElementsByTagName("rss")[0] chan = feed.getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") self.assertChildNodeContent( items[0], { "title": "My first entry (foo is bar)\n", "description": "My first entry (foo is bar)\n", }, ) def test_add_domain(self): """ add_domain() prefixes domains onto the correct URLs. """ prefix_domain_mapping = ( (("example.com", "/foo/?arg=value"), "http://example.com/foo/?arg=value"), ( ("example.com", "/foo/?arg=value", True), "https://example.com/foo/?arg=value", ), ( ("example.com", "http://djangoproject.com/doc/"), "http://djangoproject.com/doc/", ), ( ("example.com", "https://djangoproject.com/doc/"), "https://djangoproject.com/doc/", ), ( ("example.com", "mailto:[email protected]"), "mailto:[email protected]", ), ( ("example.com", "//example.com/foo/?arg=value"), "http://example.com/foo/?arg=value", ), ) for prefix in prefix_domain_mapping: with self.subTest(prefix=prefix): self.assertEqual(views.add_domain(*prefix[0]), prefix[1]) def test_get_object(self): response = self.client.get("/syndication/rss2/articles/%s/" % self.e1.pk) doc = minidom.parseString(response.content) feed = doc.getElementsByTagName("rss")[0] chan = feed.getElementsByTagName("channel")[0] items = chan.getElementsByTagName("item") self.assertChildNodeContent( items[0], { "comments": "/blog/%s/article/%s/comments" % (self.e1.pk, self.a1.pk), "description": "Article description: My first article", "link": "http://example.com/blog/%s/article/%s/" % (self.e1.pk, self.a1.pk), "title": "Title: My first article", "pubDate": rfc2822_date(timezone.make_aware(self.a1.published, TZ)), }, ) def test_get_non_existent_object(self): response = self.client.get("/syndication/rss2/articles/0/") self.assertEqual(response.status_code, 404)
04b882eb2b13dc088a436bf5cc15142ad2cc4f6d2d7dfe5ca0a5ac29c76b4323
from django.contrib.syndication import views from django.utils import feedgenerator from django.utils.timezone import get_fixed_timezone from .models import Article, Entry class TestRss2Feed(views.Feed): title = "My blog" description = "A more thorough description of my blog." link = "/blog/" feed_guid = "/foo/bar/1234" author_name = "Sally Smith" author_email = "[email protected]" author_link = "http://www.example.com/" categories = ("python", "django") feed_copyright = "Copyright (c) 2007, Sally Smith" ttl = 600 def items(self): return Entry.objects.all() def item_description(self, item): return "Overridden description: %s" % item def item_pubdate(self, item): return item.published def item_updateddate(self, item): return item.updated def item_comments(self, item): return "%scomments" % item.get_absolute_url() item_author_name = "Sally Smith" item_author_email = "[email protected]" item_author_link = "http://www.example.com/" item_categories = ("python", "testing") item_copyright = "Copyright (c) 2007, Sally Smith" class TestRss2FeedWithCallableObject(TestRss2Feed): class TimeToLive: def __call__(self): return 700 ttl = TimeToLive() class TestRss2FeedWithGuidIsPermaLinkTrue(TestRss2Feed): def item_guid_is_permalink(self, item): return True class TestRss2FeedWithGuidIsPermaLinkFalse(TestRss2Feed): def item_guid(self, item): return str(item.pk) def item_guid_is_permalink(self, item): return False class TestRss091Feed(TestRss2Feed): feed_type = feedgenerator.RssUserland091Feed class TestNoPubdateFeed(views.Feed): title = "Test feed" link = "/feed/" def items(self): return Entry.objects.all() class TestAtomFeed(TestRss2Feed): feed_type = feedgenerator.Atom1Feed subtitle = TestRss2Feed.description class TestLatestFeed(TestRss2Feed): """ A feed where the latest entry date is an `updated` element. """ feed_type = feedgenerator.Atom1Feed subtitle = TestRss2Feed.description def items(self): return Entry.objects.exclude(title="My last entry") class ArticlesFeed(TestRss2Feed): """ A feed to test no link being defined. Articles have no get_absolute_url() method, and item_link() is not defined. """ def items(self): return Article.objects.all() class TestSingleEnclosureRSSFeed(TestRss2Feed): """ A feed to test that RSS feeds work with a single enclosure. """ def item_enclosure_url(self, item): return "http://example.com" def item_enclosure_size(self, item): return 0 def item_mime_type(self, item): return "image/png" class TestMultipleEnclosureRSSFeed(TestRss2Feed): """ A feed to test that RSS feeds raise an exception with multiple enclosures. """ def item_enclosures(self, item): return [ feedgenerator.Enclosure("http://example.com/hello.png", 0, "image/png"), feedgenerator.Enclosure("http://example.com/goodbye.png", 0, "image/png"), ] class TemplateFeed(TestRss2Feed): """ A feed to test defining item titles and descriptions with templates. """ title_template = "syndication/title.html" description_template = "syndication/description.html" # Defining a template overrides any item_title definition def item_title(self): return "Not in a template" class TemplateContextFeed(TestRss2Feed): """ A feed to test custom context data in templates for title or description. """ title_template = "syndication/title_context.html" description_template = "syndication/description_context.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["foo"] = "bar" return context class TestLanguageFeed(TestRss2Feed): language = "de" class TestGetObjectFeed(TestRss2Feed): def get_object(self, request, entry_id): return Entry.objects.get(pk=entry_id) def items(self, obj): return Article.objects.filter(entry=obj) def item_link(self, item): return "%sarticle/%s/" % (item.entry.get_absolute_url(), item.pk) def item_comments(self, item): return "%scomments" % self.item_link(item) def item_description(self, item): return "Article description: %s" % item.title def item_title(self, item): return "Title: %s" % item.title class NaiveDatesFeed(TestAtomFeed): """ A feed with naive (non-timezone-aware) dates. """ def item_pubdate(self, item): return item.published class TZAwareDatesFeed(TestAtomFeed): """ A feed with timezone-aware dates. """ def item_pubdate(self, item): # Provide a weird offset so that the test can know it's getting this # specific offset and not accidentally getting on from # settings.TIME_ZONE. return item.published.replace(tzinfo=get_fixed_timezone(42)) class TestFeedUrlFeed(TestAtomFeed): feed_url = "http://example.com/customfeedurl/" class MyCustomAtom1Feed(feedgenerator.Atom1Feed): """ Test of a custom feed generator class. """ def root_attributes(self): attrs = super().root_attributes() attrs["django"] = "rocks" return attrs def add_root_elements(self, handler): super().add_root_elements(handler) handler.addQuickElement("spam", "eggs") def item_attributes(self, item): attrs = super().item_attributes(item) attrs["bacon"] = "yum" return attrs def add_item_elements(self, handler, item): super().add_item_elements(handler, item) handler.addQuickElement("ministry", "silly walks") class TestCustomFeed(TestAtomFeed): feed_type = MyCustomAtom1Feed class TestSingleEnclosureAtomFeed(TestAtomFeed): """ A feed to test that Atom feeds work with a single enclosure. """ def item_enclosure_url(self, item): return "http://example.com" def item_enclosure_size(self, item): return 0 def item_mime_type(self, item): return "image/png" class TestMultipleEnclosureAtomFeed(TestAtomFeed): """ A feed to test that Atom feeds work with multiple enclosures. """ def item_enclosures(self, item): return [ feedgenerator.Enclosure("http://example.com/hello.png", "0", "image/png"), feedgenerator.Enclosure("http://example.com/goodbye.png", "0", "image/png"), ]
bd465e92ad3eba1c937351205daf3bc8b541256b283e13a41b5d32000959659a
from django.urls import path from . import feeds urlpatterns = [ path("syndication/rss2/", feeds.TestRss2Feed()), path( "syndication/rss2/with-callable-object/", feeds.TestRss2FeedWithCallableObject() ), path("syndication/rss2/articles/<int:entry_id>/", feeds.TestGetObjectFeed()), path( "syndication/rss2/guid_ispermalink_true/", feeds.TestRss2FeedWithGuidIsPermaLinkTrue(), ), path( "syndication/rss2/guid_ispermalink_false/", feeds.TestRss2FeedWithGuidIsPermaLinkFalse(), ), path("syndication/rss091/", feeds.TestRss091Feed()), path("syndication/no_pubdate/", feeds.TestNoPubdateFeed()), path("syndication/atom/", feeds.TestAtomFeed()), path("syndication/latest/", feeds.TestLatestFeed()), path("syndication/custom/", feeds.TestCustomFeed()), path("syndication/language/", feeds.TestLanguageFeed()), path("syndication/naive-dates/", feeds.NaiveDatesFeed()), path("syndication/aware-dates/", feeds.TZAwareDatesFeed()), path("syndication/feedurl/", feeds.TestFeedUrlFeed()), path("syndication/articles/", feeds.ArticlesFeed()), path("syndication/template/", feeds.TemplateFeed()), path("syndication/template_context/", feeds.TemplateContextFeed()), path("syndication/rss2/single-enclosure/", feeds.TestSingleEnclosureRSSFeed()), path("syndication/rss2/multiple-enclosure/", feeds.TestMultipleEnclosureRSSFeed()), path("syndication/atom/single-enclosure/", feeds.TestSingleEnclosureAtomFeed()), path("syndication/atom/multiple-enclosure/", feeds.TestMultipleEnclosureAtomFeed()), ]
e62186ca6ad5df70668b4ff1cc9cb49b3b53c837c05e3a718d614d8e54bd9eb5
import json import mimetypes import os import sys from copy import copy from functools import partial from http import HTTPStatus from importlib import import_module from io import BytesIO from urllib.parse import unquote_to_bytes, urljoin, urlparse, urlsplit from asgiref.sync import sync_to_async from django.conf import settings from django.core.handlers.asgi import ASGIRequest from django.core.handlers.base import BaseHandler from django.core.handlers.wsgi import WSGIRequest from django.core.serializers.json import DjangoJSONEncoder from django.core.signals import got_request_exception, request_finished, request_started from django.db import close_old_connections from django.http import HttpRequest, QueryDict, SimpleCookie from django.test import signals from django.test.utils import ContextList from django.urls import resolve from django.utils.encoding import force_bytes from django.utils.functional import SimpleLazyObject from django.utils.http import urlencode from django.utils.itercompat import is_iterable from django.utils.regex_helper import _lazy_re_compile __all__ = ( "AsyncClient", "AsyncRequestFactory", "Client", "RedirectCycleError", "RequestFactory", "encode_file", "encode_multipart", ) BOUNDARY = "BoUnDaRyStRiNg" MULTIPART_CONTENT = "multipart/form-data; boundary=%s" % BOUNDARY CONTENT_TYPE_RE = _lazy_re_compile(r".*; charset=([\w-]+);?") # Structured suffix spec: https://tools.ietf.org/html/rfc6838#section-4.2.8 JSON_CONTENT_TYPE_RE = _lazy_re_compile(r"^application\/(.+\+)?json") class RedirectCycleError(Exception): """The test client has been asked to follow a redirect loop.""" def __init__(self, message, last_response): super().__init__(message) self.last_response = last_response self.redirect_chain = last_response.redirect_chain class FakePayload: """ A wrapper around BytesIO that restricts what can be read since data from the network can't be sought and cannot be read outside of its content length. This makes sure that views can't do anything under the test client that wouldn't work in real life. """ def __init__(self, content=None): self.__content = BytesIO() self.__len = 0 self.read_started = False if content is not None: self.write(content) def __len__(self): return self.__len def read(self, num_bytes=None): if not self.read_started: self.__content.seek(0) self.read_started = True if num_bytes is None: num_bytes = self.__len or 0 assert ( self.__len >= num_bytes ), "Cannot read more than the available bytes from the HTTP incoming data." content = self.__content.read(num_bytes) self.__len -= num_bytes return content def write(self, content): if self.read_started: raise ValueError("Unable to write a payload after it's been read") content = force_bytes(content) self.__content.write(content) self.__len += len(content) def close(self): pass def closing_iterator_wrapper(iterable, close): try: yield from iterable finally: request_finished.disconnect(close_old_connections) close() # will fire request_finished request_finished.connect(close_old_connections) def conditional_content_removal(request, response): """ Simulate the behavior of most web servers by removing the content of responses for HEAD requests, 1xx, 204, and 304 responses. Ensure compliance with RFC 7230, section 3.3.3. """ if 100 <= response.status_code < 200 or response.status_code in (204, 304): if response.streaming: response.streaming_content = [] else: response.content = b"" if request.method == "HEAD": if response.streaming: response.streaming_content = [] else: response.content = b"" return response class ClientHandler(BaseHandler): """ An HTTP Handler that can be used for testing purposes. Use the WSGI interface to compose requests, but return the raw HttpResponse object with the originating WSGIRequest attached to its ``wsgi_request`` attribute. """ def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super().__init__(*args, **kwargs) def __call__(self, environ): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware() request_started.disconnect(close_old_connections) request_started.send(sender=self.__class__, environ=environ) request_started.connect(close_old_connections) request = WSGIRequest(environ) # sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably # required for backwards compatibility with external tests against # admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = self.get_response(request) # Simulate behaviors of most web servers. conditional_content_removal(request, response) # Attach the originating request to the response so that it could be # later retrieved. response.wsgi_request = request # Emulate a WSGI server by calling the close method on completion. if response.streaming: response.streaming_content = closing_iterator_wrapper( response.streaming_content, response.close ) else: request_finished.disconnect(close_old_connections) response.close() # will fire request_finished request_finished.connect(close_old_connections) return response class AsyncClientHandler(BaseHandler): """An async version of ClientHandler.""" def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super().__init__(*args, **kwargs) async def __call__(self, scope): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware(is_async=True) # Extract body file from the scope, if provided. if "_body_file" in scope: body_file = scope.pop("_body_file") else: body_file = FakePayload("") request_started.disconnect(close_old_connections) await sync_to_async(request_started.send, thread_sensitive=False)( sender=self.__class__, scope=scope ) request_started.connect(close_old_connections) request = ASGIRequest(scope, body_file) # Sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably required # for backwards compatibility with external tests against admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = await self.get_response_async(request) # Simulate behaviors of most web servers. conditional_content_removal(request, response) # Attach the originating ASGI request to the response so that it could # be later retrieved. response.asgi_request = request # Emulate a server by calling the close method on completion. if response.streaming: response.streaming_content = await sync_to_async( closing_iterator_wrapper, thread_sensitive=False )( response.streaming_content, response.close, ) else: request_finished.disconnect(close_old_connections) # Will fire request_finished. await sync_to_async(response.close, thread_sensitive=False)() request_finished.connect(close_old_connections) return response def store_rendered_templates(store, signal, sender, template, context, **kwargs): """ Store templates and contexts that are rendered. The context is copied so that it is an accurate representation at the time of rendering. """ store.setdefault("templates", []).append(template) if "context" not in store: store["context"] = ContextList() store["context"].append(copy(context)) def encode_multipart(boundary, data): """ Encode multipart POST data from a dictionary of form values. The key will be used as the form data name; the value will be transmitted as content. If the value is a file, the contents of the file will be sent as an application/octet-stream; otherwise, str(value) will be sent. """ lines = [] def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # Not by any means perfect, but good enough for our purposes. def is_file(thing): return hasattr(thing, "read") and callable(thing.read) # Each bit of the multipart form data could be either a form value or a # file, or a *list* of form values and/or files. Remember that HTTP field # names can be duplicated! for (key, value) in data.items(): if value is None: raise TypeError( "Cannot encode None for key '%s' as POST data. Did you mean " "to pass an empty string or omit the value?" % key ) elif is_file(value): lines.extend(encode_file(boundary, key, value)) elif not isinstance(value, str) and is_iterable(value): for item in value: if is_file(item): lines.extend(encode_file(boundary, key, item)) else: lines.extend( to_bytes(val) for val in [ "--%s" % boundary, 'Content-Disposition: form-data; name="%s"' % key, "", item, ] ) else: lines.extend( to_bytes(val) for val in [ "--%s" % boundary, 'Content-Disposition: form-data; name="%s"' % key, "", value, ] ) lines.extend( [ to_bytes("--%s--" % boundary), b"", ] ) return b"\r\n".join(lines) def encode_file(boundary, key, file): def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # file.name might not be a string. For example, it's an int for # tempfile.TemporaryFile(). file_has_string_name = hasattr(file, "name") and isinstance(file.name, str) filename = os.path.basename(file.name) if file_has_string_name else "" if hasattr(file, "content_type"): content_type = file.content_type elif filename: content_type = mimetypes.guess_type(filename)[0] else: content_type = None if content_type is None: content_type = "application/octet-stream" filename = filename or key return [ to_bytes("--%s" % boundary), to_bytes( 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename) ), to_bytes("Content-Type: %s" % content_type), b"", to_bytes(file.read()), ] class RequestFactory: """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__(self, *, json_encoder=DjangoJSONEncoder, **defaults): self.json_encoder = json_encoder self.defaults = defaults self.cookies = SimpleCookie() self.errors = BytesIO() def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See https://www.python.org/dev/peps/pep-3333/#environ-variables return { "HTTP_COOKIE": "; ".join( sorted( "%s=%s" % (morsel.key, morsel.coded_value) for morsel in self.cookies.values() ) ), "PATH_INFO": "/", "REMOTE_ADDR": "127.0.0.1", "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "SERVER_NAME": "testserver", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": FakePayload(b""), "wsgi.errors": self.errors, "wsgi.multiprocess": True, "wsgi.multithread": False, "wsgi.run_once": False, **self.defaults, **request, } def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _encode_data(self, data, content_type): if content_type is MULTIPART_CONTENT: return encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match[1] else: charset = settings.DEFAULT_CHARSET return force_bytes(data, encoding=charset) def _encode_json(self, data, content_type): """ Return encoded JSON if data is a dict, list, or tuple and content_type is application/json. """ should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance( data, (dict, list, tuple) ) return json.dumps(data, cls=self.json_encoder) if should_encode else data def _get_path(self, parsed): path = parsed.path # If there are parameters, add them if parsed.params: path += ";" + parsed.params path = unquote_to_bytes(path) # Replace the behavior where non-ASCII values in the WSGI environ are # arbitrarily decoded with ISO-8859-1. # Refs comment in `get_bytes_from_wsgi()`. return path.decode("iso-8859-1") def get(self, path, data=None, secure=False, **extra): """Construct a GET request.""" data = {} if data is None else data return self.generic( "GET", path, secure=secure, **{ "QUERY_STRING": urlencode(data, doseq=True), **extra, }, ) def post( self, path, data=None, content_type=MULTIPART_CONTENT, secure=False, **extra ): """Construct a POST request.""" data = self._encode_json({} if data is None else data, content_type) post_data = self._encode_data(data, content_type) return self.generic( "POST", path, post_data, content_type, secure=secure, **extra ) def head(self, path, data=None, secure=False, **extra): """Construct a HEAD request.""" data = {} if data is None else data return self.generic( "HEAD", path, secure=secure, **{ "QUERY_STRING": urlencode(data, doseq=True), **extra, }, ) def trace(self, path, secure=False, **extra): """Construct a TRACE request.""" return self.generic("TRACE", path, secure=secure, **extra) def options( self, path, data="", content_type="application/octet-stream", secure=False, **extra, ): "Construct an OPTIONS request." return self.generic("OPTIONS", path, data, content_type, secure=secure, **extra) def put( self, path, data="", content_type="application/octet-stream", secure=False, **extra, ): """Construct a PUT request.""" data = self._encode_json(data, content_type) return self.generic("PUT", path, data, content_type, secure=secure, **extra) def patch( self, path, data="", content_type="application/octet-stream", secure=False, **extra, ): """Construct a PATCH request.""" data = self._encode_json(data, content_type) return self.generic("PATCH", path, data, content_type, secure=secure, **extra) def delete( self, path, data="", content_type="application/octet-stream", secure=False, **extra, ): """Construct a DELETE request.""" data = self._encode_json(data, content_type) return self.generic("DELETE", path, data, content_type, secure=secure, **extra) def generic( self, method, path, data="", content_type="application/octet-stream", secure=False, **extra, ): """Construct an arbitrary HTTP request.""" parsed = urlparse(str(path)) # path can be lazy data = force_bytes(data, settings.DEFAULT_CHARSET) r = { "PATH_INFO": self._get_path(parsed), "REQUEST_METHOD": method, "SERVER_PORT": "443" if secure else "80", "wsgi.url_scheme": "https" if secure else "http", } if data: r.update( { "CONTENT_LENGTH": str(len(data)), "CONTENT_TYPE": content_type, "wsgi.input": FakePayload(data), } ) r.update(extra) # If QUERY_STRING is absent or empty, we want to extract it from the URL. if not r.get("QUERY_STRING"): # WSGI requires latin-1 encoded strings. See get_path_info(). query_string = parsed[4].encode().decode("iso-8859-1") r["QUERY_STRING"] = query_string return self.request(**r) class AsyncRequestFactory(RequestFactory): """ Class that lets you create mock ASGI-like Request objects for use in testing. Usage: rf = AsyncRequestFactory() get_request = await rf.get('/hello/') post_request = await rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, including synchronous ones. The reason we have a separate class here is: a) this makes ASGIRequest subclasses, and b) AsyncTestClient can subclass it. """ def _base_scope(self, **request): """The base scope for a request.""" # This is a minimal valid ASGI scope, plus: # - headers['cookie'] for cookie support, # - 'client' often useful, see #8551. scope = { "asgi": {"version": "3.0"}, "type": "http", "http_version": "1.1", "client": ["127.0.0.1", 0], "server": ("testserver", "80"), "scheme": "http", "method": "GET", "headers": [], **self.defaults, **request, } scope["headers"].append( ( b"cookie", b"; ".join( sorted( ("%s=%s" % (morsel.key, morsel.coded_value)).encode("ascii") for morsel in self.cookies.values() ) ), ) ) return scope def request(self, **request): """Construct a generic request object.""" # This is synchronous, which means all methods on this class are. # AsyncClient, however, has an async request function, which makes all # its methods async. if "_body_file" in request: body_file = request.pop("_body_file") else: body_file = FakePayload("") return ASGIRequest(self._base_scope(**request), body_file) def generic( self, method, path, data="", content_type="application/octet-stream", secure=False, **extra, ): """Construct an arbitrary HTTP request.""" parsed = urlparse(str(path)) # path can be lazy. data = force_bytes(data, settings.DEFAULT_CHARSET) s = { "method": method, "path": self._get_path(parsed), "server": ("127.0.0.1", "443" if secure else "80"), "scheme": "https" if secure else "http", "headers": [(b"host", b"testserver")], } if data: s["headers"].extend( [ (b"content-length", str(len(data)).encode("ascii")), (b"content-type", content_type.encode("ascii")), ] ) s["_body_file"] = FakePayload(data) follow = extra.pop("follow", None) if follow is not None: s["follow"] = follow if query_string := extra.pop("QUERY_STRING", None): s["query_string"] = query_string s["headers"] += [ (key.lower().encode("ascii"), value.encode("latin1")) for key, value in extra.items() ] # If QUERY_STRING is absent or empty, we want to extract it from the # URL. if not s.get("query_string"): s["query_string"] = parsed[4] return self.request(**s) class ClientMixin: """ Mixin with common methods between Client and AsyncClient. """ def store_exc_info(self, **kwargs): """Store exceptions when they are generated by a view.""" self.exc_info = sys.exc_info() def check_exception(self, response): """ Look for a signaled exception, clear the current context exception data, re-raise the signaled exception, and clear the signaled exception from the local cache. """ response.exc_info = self.exc_info if self.exc_info: _, exc_value, _ = self.exc_info self.exc_info = None if self.raise_request_exception: raise exc_value @property def session(self): """Return the current session variables.""" engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) if cookie: return engine.SessionStore(cookie.value) session = engine.SessionStore() session.save() self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key return session def login(self, **credentials): """ Set the Factory to appear as if it has successfully logged into a site. Return True if login is possible or False if the provided credentials are incorrect. """ from django.contrib.auth import authenticate user = authenticate(**credentials) if user: self._login(user) return True return False def force_login(self, user, backend=None): def get_backend(): from django.contrib.auth import load_backend for backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) if hasattr(backend, "get_user"): return backend_path if backend is None: backend = get_backend() user.backend = backend self._login(user, backend) def _login(self, user, backend=None): from django.contrib.auth import login # Create a fake request to store login details. request = HttpRequest() if self.session: request.session = self.session else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() login(request, user, backend) # Save the session values. request.session.save() # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME self.cookies[session_cookie] = request.session.session_key cookie_data = { "max-age": None, "path": "/", "domain": settings.SESSION_COOKIE_DOMAIN, "secure": settings.SESSION_COOKIE_SECURE or None, "expires": None, } self.cookies[session_cookie].update(cookie_data) def logout(self): """Log out the user by removing the cookies and session object.""" from django.contrib.auth import get_user, logout request = HttpRequest() if self.session: request.session = self.session request.user = get_user(request) else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() logout(request) self.cookies = SimpleCookie() def _parse_json(self, response, **extra): if not hasattr(response, "_json"): if not JSON_CONTENT_TYPE_RE.match(response.get("Content-Type")): raise ValueError( 'Content-Type header is "%s", not "application/json"' % response.get("Content-Type") ) response._json = json.loads( response.content.decode(response.charset), **extra ) return response._json class Client(ClientMixin, RequestFactory): """ A class that can act as a client 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 the like - it is here to allow testing against the contexts and templates produced by a view, rather than the HTML rendered to the end-user. """ def __init__( self, enforce_csrf_checks=False, raise_request_exception=True, **defaults ): super().__init__(**defaults) self.handler = ClientHandler(enforce_csrf_checks) self.raise_request_exception = raise_request_exception self.exc_info = None self.extra = None def request(self, **request): """ Make a generic request. Compose the environment dictionary and pass to the handler, return the result of the handler. Assume defaults for the query environment, which can be overridden using the arguments to the request. """ environ = self._base_environ(**request) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = partial(store_rendered_templates, data) signal_uid = "template-render-%s" % id(request) signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid) # Capture exceptions created by the handler. exception_uid = "request-exception-%s" % id(request) got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid) try: response = self.handler(environ) finally: signals.template_rendered.disconnect(dispatch_uid=signal_uid) got_request_exception.disconnect(dispatch_uid=exception_uid) # Check for signaled exceptions. self.check_exception(response) # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response. response.templates = data.get("templates", []) response.context = data.get("context") response.json = partial(self._parse_json, response) # Attach the ResolverMatch instance to the response. urlconf = getattr(response.wsgi_request, "urlconf", None) response.resolver_match = SimpleLazyObject( lambda: resolve(request["PATH_INFO"], urlconf=urlconf), ) # Flatten a single context. Not really necessary anymore thanks to the # __getattr__ flattening in ContextList, but has some edge case # backwards compatibility implications. if response.context and len(response.context) == 1: response.context = response.context[0] # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response def get(self, path, data=None, follow=False, secure=False, **extra): """Request a response from the server using GET.""" self.extra = extra response = super().get(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, data=data, **extra) return response def post( self, path, data=None, content_type=MULTIPART_CONTENT, follow=False, secure=False, **extra, ): """Request a response from the server using POST.""" self.extra = extra response = super().post( path, data=data, content_type=content_type, secure=secure, **extra ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, **extra ) return response def head(self, path, data=None, follow=False, secure=False, **extra): """Request a response from the server using HEAD.""" self.extra = extra response = super().head(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, data=data, **extra) return response def options( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, **extra, ): """Request a response from the server using OPTIONS.""" self.extra = extra response = super().options( path, data=data, content_type=content_type, secure=secure, **extra ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, **extra ) return response def put( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, **extra, ): """Send a resource to the server using PUT.""" self.extra = extra response = super().put( path, data=data, content_type=content_type, secure=secure, **extra ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, **extra ) return response def patch( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, **extra, ): """Send a resource to the server using PATCH.""" self.extra = extra response = super().patch( path, data=data, content_type=content_type, secure=secure, **extra ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, **extra ) return response def delete( self, path, data="", content_type="application/octet-stream", follow=False, secure=False, **extra, ): """Send a DELETE request to the server.""" self.extra = extra response = super().delete( path, data=data, content_type=content_type, secure=secure, **extra ) if follow: response = self._handle_redirects( response, data=data, content_type=content_type, **extra ) return response def trace(self, path, data="", follow=False, secure=False, **extra): """Send a TRACE request to the server.""" self.extra = extra response = super().trace(path, data=data, secure=secure, **extra) if follow: response = self._handle_redirects(response, data=data, **extra) return response def _handle_redirects(self, response, data="", content_type="", **extra): """ Follow any redirects by requesting responses from the server using GET. """ response.redirect_chain = [] redirect_status_codes = ( HTTPStatus.MOVED_PERMANENTLY, HTTPStatus.FOUND, HTTPStatus.SEE_OTHER, HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT, ) while response.status_code in redirect_status_codes: response_url = response.url redirect_chain = response.redirect_chain redirect_chain.append((response_url, response.status_code)) url = urlsplit(response_url) if url.scheme: extra["wsgi.url_scheme"] = url.scheme if url.hostname: extra["SERVER_NAME"] = url.hostname if url.port: extra["SERVER_PORT"] = str(url.port) path = url.path # RFC 2616: bare domains without path are treated as the root. if not path and url.netloc: path = "/" # Prepend the request path to handle relative path redirects if not path.startswith("/"): path = urljoin(response.request["PATH_INFO"], path) if response.status_code in ( HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT, ): # Preserve request method and query string (if needed) # post-redirect for 307/308 responses. request_method = response.request["REQUEST_METHOD"].lower() if request_method not in ("get", "head"): extra["QUERY_STRING"] = url.query request_method = getattr(self, request_method) else: request_method = self.get data = QueryDict(url.query) content_type = None response = request_method( path, data=data, content_type=content_type, follow=False, **extra ) response.redirect_chain = redirect_chain if redirect_chain[-1] in redirect_chain[:-1]: # Check that we're not redirecting to somewhere we've already # been to, to prevent loops. raise RedirectCycleError( "Redirect loop detected.", last_response=response ) if len(redirect_chain) > 20: # Such a lengthy chain likely also means a loop, but one with # a growing path, changing view, or changing query argument; # 20 is the value of "network.http.redirection-limit" from Firefox. raise RedirectCycleError("Too many redirects.", last_response=response) return response class AsyncClient(ClientMixin, AsyncRequestFactory): """ An async version of Client that creates ASGIRequests and calls through an async request path. Does not currently support "follow" on its methods. """ def __init__( self, enforce_csrf_checks=False, raise_request_exception=True, **defaults ): super().__init__(**defaults) self.handler = AsyncClientHandler(enforce_csrf_checks) self.raise_request_exception = raise_request_exception self.exc_info = None self.extra = None async def request(self, **request): """ Make a generic request. Compose the scope dictionary and pass to the handler, return the result of the handler. Assume defaults for the query environment, which can be overridden using the arguments to the request. """ if "follow" in request: raise NotImplementedError( "AsyncClient request methods do not accept the follow parameter." ) scope = self._base_scope(**request) # Curry a data dictionary into an instance of the template renderer # callback function. data = {} on_template_render = partial(store_rendered_templates, data) signal_uid = "template-render-%s" % id(request) signals.template_rendered.connect(on_template_render, dispatch_uid=signal_uid) # Capture exceptions created by the handler. exception_uid = "request-exception-%s" % id(request) got_request_exception.connect(self.store_exc_info, dispatch_uid=exception_uid) try: response = await self.handler(scope) finally: signals.template_rendered.disconnect(dispatch_uid=signal_uid) got_request_exception.disconnect(dispatch_uid=exception_uid) # Check for signaled exceptions. self.check_exception(response) # Save the client and request that stimulated the response. response.client = self response.request = request # Add any rendered template detail to the response. response.templates = data.get("templates", []) response.context = data.get("context") response.json = partial(self._parse_json, response) # Attach the ResolverMatch instance to the response. urlconf = getattr(response.asgi_request, "urlconf", None) response.resolver_match = SimpleLazyObject( lambda: resolve(request["path"], urlconf=urlconf), ) # Flatten a single context. Not really necessary anymore thanks to the # __getattr__ flattening in ContextList, but has some edge case # backwards compatibility implications. if response.context and len(response.context) == 1: response.context = response.context[0] # Update persistent cookie data. if response.cookies: self.cookies.update(response.cookies) return response
27217a208beb82c0d61d3276822bce4166725488653226dbf354b365c33ff3b0
"""HTML utilities suitable for global use.""" import html import json import re from html.parser import HTMLParser from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit from django.utils.encoding import punycode from django.utils.functional import Promise, keep_lazy, keep_lazy_text from django.utils.http import RFC3986_GENDELIMS, RFC3986_SUBDELIMS from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import SafeData, SafeString, mark_safe from django.utils.text import normalize_newlines @keep_lazy(SafeString) def escape(text): """ Return the given text with ampersands, quotes and angle brackets encoded for use in HTML. Always escape input, even if it's already escaped and marked as such. This may result in double-escaping. If this is a concern, use conditional_escape() instead. """ return SafeString(html.escape(str(text))) _js_escapes = { ord("\\"): "\\u005C", ord("'"): "\\u0027", ord('"'): "\\u0022", ord(">"): "\\u003E", ord("<"): "\\u003C", ord("&"): "\\u0026", ord("="): "\\u003D", ord("-"): "\\u002D", ord(";"): "\\u003B", ord("`"): "\\u0060", ord("\u2028"): "\\u2028", ord("\u2029"): "\\u2029", } # Escape every ASCII character with a value less than 32. _js_escapes.update((ord("%c" % z), "\\u%04X" % z) for z in range(32)) @keep_lazy(SafeString) def escapejs(value): """Hex encode characters for use in JavaScript strings.""" return mark_safe(str(value).translate(_js_escapes)) _json_script_escapes = { ord(">"): "\\u003E", ord("<"): "\\u003C", ord("&"): "\\u0026", } def json_script(value, element_id=None, encoder=None): """ Escape all the HTML/XML special characters with their unicode escapes, so value is safe to be output anywhere except for inside a tag attribute. Wrap the escaped JSON in a script tag. """ from django.core.serializers.json import DjangoJSONEncoder json_str = json.dumps(value, cls=encoder or DjangoJSONEncoder).translate( _json_script_escapes ) if element_id: template = '<script id="{}" type="application/json">{}</script>' args = (element_id, mark_safe(json_str)) else: template = '<script type="application/json">{}</script>' args = (mark_safe(json_str),) return format_html(template, *args) def conditional_escape(text): """ Similar to escape(), except that it doesn't operate on pre-escaped strings. This function relies on the __html__ convention used both by Django's SafeData class and by third-party libraries like markupsafe. """ if isinstance(text, Promise): text = str(text) if hasattr(text, "__html__"): return text.__html__() else: return escape(text) def format_html(format_string, *args, **kwargs): """ Similar to str.format, but pass all arguments through conditional_escape(), and call mark_safe() on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments. """ args_safe = map(conditional_escape, args) kwargs_safe = {k: conditional_escape(v) for (k, v) in kwargs.items()} return mark_safe(format_string.format(*args_safe, **kwargs_safe)) def format_html_join(sep, format_string, args_generator): """ A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape. 'args_generator' should be an iterator that returns the sequence of 'args' that will be passed to format_html. Example: format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name) for u in users)) """ return mark_safe( conditional_escape(sep).join( format_html(format_string, *args) for args in args_generator ) ) @keep_lazy_text def linebreaks(value, autoescape=False): """Convert newlines into <p> and <br>s.""" value = normalize_newlines(value) paras = re.split("\n{2,}", str(value)) if autoescape: paras = ["<p>%s</p>" % escape(p).replace("\n", "<br>") for p in paras] else: paras = ["<p>%s</p>" % p.replace("\n", "<br>") for p in paras] return "\n\n".join(paras) class MLStripper(HTMLParser): def __init__(self): super().__init__(convert_charrefs=False) self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def handle_entityref(self, name): self.fed.append("&%s;" % name) def handle_charref(self, name): self.fed.append("&#%s;" % name) def get_data(self): return "".join(self.fed) def _strip_once(value): """ Internal tag stripping utility used by strip_tags. """ s = MLStripper() s.feed(value) s.close() return s.get_data() @keep_lazy_text def strip_tags(value): """Return the given HTML with all tags stripped.""" # Note: in typical case this loop executes _strip_once once. Loop condition # is redundant, but helps to reduce number of executions of _strip_once. value = str(value) while "<" in value and ">" in value: new_value = _strip_once(value) if value.count("<") == new_value.count("<"): # _strip_once wasn't able to detect more tags. break value = new_value return value @keep_lazy_text def strip_spaces_between_tags(value): """Return the given HTML with spaces between tags removed.""" return re.sub(r">\s+<", "><", str(value)) def smart_urlquote(url): """Quote a URL if it isn't already quoted.""" def unquote_quote(segment): segment = unquote(segment) # Tilde is part of RFC3986 Unreserved Characters # https://tools.ietf.org/html/rfc3986#section-2.3 # See also https://bugs.python.org/issue16285 return quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + "~") # Handle IDN before quoting. try: scheme, netloc, path, query, fragment = urlsplit(url) except ValueError: # invalid IPv6 URL (normally square brackets in hostname part). return unquote_quote(url) try: netloc = punycode(netloc) # IDN -> ACE except UnicodeError: # invalid domain part return unquote_quote(url) if query: # Separately unquoting key/value, so as to not mix querystring separators # included in query values. See #22267. query_parts = [ (unquote(q[0]), unquote(q[1])) for q in parse_qsl(query, keep_blank_values=True) ] # urlencode will take care of quoting query = urlencode(query_parts) path = unquote_quote(path) fragment = unquote_quote(fragment) return urlunsplit((scheme, netloc, path, query, fragment)) class Urlizer: """ Convert any URLs in text into clickable links. Work on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org). Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. """ trailing_punctuation_chars = ".,:;!" wrapping_punctuation = [("(", ")"), ("[", "]")] simple_url_re = _lazy_re_compile(r"^https?://\[?\w", re.IGNORECASE) simple_url_2_re = _lazy_re_compile( r"^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$", re.IGNORECASE ) word_split_re = _lazy_re_compile(r"""([\s<>"']+)""") mailto_template = "mailto:{local}@{domain}" url_template = '<a href="{href}"{attrs}>{url}</a>' def __call__(self, text, trim_url_limit=None, nofollow=False, autoescape=False): """ If trim_url_limit is not None, truncate the URLs in the link text longer than this limit to trim_url_limit - 1 characters and append an ellipsis. If nofollow is True, give the links a rel="nofollow" attribute. If autoescape is True, autoescape the link text and URLs. """ safe_input = isinstance(text, SafeData) words = self.word_split_re.split(str(text)) return "".join( [ self.handle_word( word, safe_input=safe_input, trim_url_limit=trim_url_limit, nofollow=nofollow, autoescape=autoescape, ) for word in words ] ) def handle_word( self, word, *, safe_input, trim_url_limit=None, nofollow=False, autoescape=False, ): if "." in word or "@" in word or ":" in word: # lead: Punctuation trimmed from the beginning of the word. # middle: State of the word. # trail: Punctuation trimmed from the end of the word. lead, middle, trail = self.trim_punctuation(word) # Make URL we want to point to. url = None nofollow_attr = ' rel="nofollow"' if nofollow else "" if self.simple_url_re.match(middle): url = smart_urlquote(html.unescape(middle)) elif self.simple_url_2_re.match(middle): url = smart_urlquote("http://%s" % html.unescape(middle)) elif ":" not in middle and self.is_email_simple(middle): local, domain = middle.rsplit("@", 1) try: domain = punycode(domain) except UnicodeError: return word url = self.mailto_template.format(local=local, domain=domain) nofollow_attr = "" # Make link. if url: trimmed = self.trim_url(middle, limit=trim_url_limit) if autoescape and not safe_input: lead, trail = escape(lead), escape(trail) trimmed = escape(trimmed) middle = self.url_template.format( href=escape(url), attrs=nofollow_attr, url=trimmed, ) return mark_safe(f"{lead}{middle}{trail}") else: if safe_input: return mark_safe(word) elif autoescape: return escape(word) elif safe_input: return mark_safe(word) elif autoescape: return escape(word) return word def trim_url(self, x, *, limit): if limit is None or len(x) <= limit: return x return "%s…" % x[: max(0, limit - 1)] def trim_punctuation(self, word): """ Trim trailing and wrapping punctuation from `word`. Return the items of the new state. """ lead, middle, trail = "", word, "" # Continue trimming until middle remains unchanged. trimmed_something = True while trimmed_something: trimmed_something = False # Trim wrapping punctuation. for opening, closing in self.wrapping_punctuation: if middle.startswith(opening): middle = middle[len(opening) :] lead += opening trimmed_something = True # Keep parentheses at the end only if they're balanced. if ( middle.endswith(closing) and middle.count(closing) == middle.count(opening) + 1 ): middle = middle[: -len(closing)] trail = closing + trail trimmed_something = True # Trim trailing punctuation (after trimming wrapping punctuation, # as encoded entities contain ';'). Unescape entities to avoid # breaking them by removing ';'. middle_unescaped = html.unescape(middle) stripped = middle_unescaped.rstrip(self.trailing_punctuation_chars) if middle_unescaped != stripped: punctuation_count = len(middle_unescaped) - len(stripped) trail = middle[-punctuation_count:] + trail middle = middle[:-punctuation_count] trimmed_something = True return lead, middle, trail @staticmethod def is_email_simple(value): """Return True if value looks like an email address.""" # An @ must be in the middle of the value. if "@" not in value or value.startswith("@") or value.endswith("@"): return False try: p1, p2 = value.split("@") except ValueError: # value contains more than one @. return False # Dot must be in p2 (e.g. example.com) if "." not in p2 or p2.startswith("."): return False return True urlizer = Urlizer() @keep_lazy_text def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): return urlizer( text, trim_url_limit=trim_url_limit, nofollow=nofollow, autoescape=autoescape ) def avoid_wrapping(value): """ Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces. """ return value.replace(" ", "\xa0") def html_safe(klass): """ A decorator that defines the __html__ method. This helps non-Django templates to detect classes whose __str__ methods return SafeString. """ if "__html__" in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it defines " "__html__()." % klass.__name__ ) if "__str__" not in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it doesn't " "define __str__()." % klass.__name__ ) klass_str = klass.__str__ klass.__str__ = lambda self: mark_safe(klass_str(self)) klass.__html__ = lambda self: str(self) return klass
4ea00e13094d561fdd6a1fbddb8942f243cd3960b54549684e1c172e6b7156f6
import base64 import datetime import re import unicodedata from binascii import Error as BinasciiError from email.utils import formatdate from urllib.parse import ( ParseResult, SplitResult, _coerce_args, _splitnetloc, _splitparams, scheme_chars, unquote, ) from urllib.parse import urlencode as original_urlencode from urllib.parse import uses_params from django.utils.datastructures import MultiValueDict from django.utils.regex_helper import _lazy_re_compile # based on RFC 7232, Appendix C ETAG_MATCH = _lazy_re_compile( r""" \A( # start of string and capture group (?:W/)? # optional weak indicator " # opening quote [^"]* # any sequence of non-quote characters " # end quote )\Z # end of string and capture group """, re.X, ) MONTHS = "jan feb mar apr may jun jul aug sep oct nov dec".split() __D = r"(?P<day>[0-9]{2})" __D2 = r"(?P<day>[ 0-9][0-9])" __M = r"(?P<mon>\w{3})" __Y = r"(?P<year>[0-9]{4})" __Y2 = r"(?P<year>[0-9]{2})" __T = r"(?P<hour>[0-9]{2}):(?P<min>[0-9]{2}):(?P<sec>[0-9]{2})" RFC1123_DATE = _lazy_re_compile(r"^\w{3}, %s %s %s %s GMT$" % (__D, __M, __Y, __T)) RFC850_DATE = _lazy_re_compile(r"^\w{6,9}, %s-%s-%s %s GMT$" % (__D, __M, __Y2, __T)) ASCTIME_DATE = _lazy_re_compile(r"^\w{3} %s %s %s %s$" % (__M, __D2, __T, __Y)) RFC3986_GENDELIMS = ":/?#[]@" RFC3986_SUBDELIMS = "!$&'()*+,;=" # TODO: Remove when dropping support for PY38. # Unsafe bytes to be removed per WHATWG spec. _UNSAFE_URL_BYTES_TO_REMOVE = ["\t", "\r", "\n"] def urlencode(query, doseq=False): """ A version of Python's urllib.parse.urlencode() function that can operate on MultiValueDict and non-string values. """ if isinstance(query, MultiValueDict): query = query.lists() elif hasattr(query, "items"): query = query.items() query_params = [] for key, value in query: if value is None: raise TypeError( "Cannot encode None for key '%s' in a query string. Did you " "mean to pass an empty string or omit the value?" % key ) elif not doseq or isinstance(value, (str, bytes)): query_val = value else: try: itr = iter(value) except TypeError: query_val = value else: # Consume generators and iterators, when doseq=True, to # work around https://bugs.python.org/issue31706. query_val = [] for item in itr: if item is None: raise TypeError( "Cannot encode None for key '%s' in a query " "string. Did you mean to pass an empty string or " "omit the value?" % key ) elif not isinstance(item, bytes): item = str(item) query_val.append(item) query_params.append((key, query_val)) return original_urlencode(query_params, doseq) def http_date(epoch_seconds=None): """ Format the time to match the RFC1123 date format as specified by HTTP RFC7231 section 7.1.1.1. `epoch_seconds` is a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, it defaults to the current time. Output a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'. """ return formatdate(epoch_seconds, usegmt=True) def parse_http_date(date): """ Parse a date format as specified by HTTP RFC7231 section 7.1.1.1. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Return an integer expressed in seconds since the epoch, in UTC. """ # email.utils.parsedate() does the job for RFC1123 dates; unfortunately # RFC7231 makes it mandatory to support RFC850 dates too. So we roll # our own RFC-compliant parsing. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE: m = regex.match(date) if m is not None: break else: raise ValueError("%r is not in a valid HTTP date format" % date) try: tz = datetime.timezone.utc year = int(m["year"]) if year < 100: current_year = datetime.datetime.now(tz=tz).year current_century = current_year - (current_year % 100) if year - (current_year % 100) > 50: # year that appears to be more than 50 years in the future are # interpreted as representing the past. year += current_century - 100 else: year += current_century month = MONTHS.index(m["mon"].lower()) + 1 day = int(m["day"]) hour = int(m["hour"]) min = int(m["min"]) sec = int(m["sec"]) result = datetime.datetime(year, month, day, hour, min, sec, tzinfo=tz) return int(result.timestamp()) except Exception as exc: raise ValueError("%r is not a valid date" % date) from exc def parse_http_date_safe(date): """ Same as parse_http_date, but return None if the input is invalid. """ try: return parse_http_date(date) except Exception: pass # Base 36 functions: useful for generating compact URLs def base36_to_int(s): """ Convert a base 36 string to an int. Raise ValueError if the input won't fit into an int. """ # To prevent overconsumption of server resources, reject any # base36 string that is longer than 13 base36 digits (13 digits # is sufficient to base36-encode any 64-bit integer) if len(s) > 13: raise ValueError("Base36 input too large") return int(s, 36) def int_to_base36(i): """Convert an integer to a base36 string.""" char_set = "0123456789abcdefghijklmnopqrstuvwxyz" if i < 0: raise ValueError("Negative base36 conversion input.") if i < 36: return char_set[i] b36 = "" while i != 0: i, n = divmod(i, 36) b36 = char_set[n] + b36 return b36 def urlsafe_base64_encode(s): """ Encode a bytestring to a base64 string for use in URLs. Strip any trailing equal signs. """ return base64.urlsafe_b64encode(s).rstrip(b"\n=").decode("ascii") def urlsafe_base64_decode(s): """ Decode a base64 encoded string. Add back any trailing equal signs that might have been stripped. """ s = s.encode() try: return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b"=")) except (LookupError, BinasciiError) as e: raise ValueError(e) def parse_etags(etag_str): """ Parse a string of ETags given in an If-None-Match or If-Match header as defined by RFC 7232. Return a list of quoted ETags, or ['*'] if all ETags should be matched. """ if etag_str.strip() == "*": return ["*"] else: # Parse each ETag individually, and return any that are valid. etag_matches = (ETAG_MATCH.match(etag.strip()) for etag in etag_str.split(",")) return [match[1] for match in etag_matches if match] def quote_etag(etag_str): """ If the provided string is already a quoted ETag, return it. Otherwise, wrap the string in quotes, making it a strong ETag. """ if ETAG_MATCH.match(etag_str): return etag_str else: return '"%s"' % etag_str def is_same_domain(host, pattern): """ Return ``True`` if the host is either an exact match or a match to the wildcard pattern. Any pattern beginning with a period matches a domain and all of its subdomains. (e.g. ``.example.com`` matches ``example.com`` and ``foo.example.com``). Anything else is an exact string match. """ if not pattern: return False pattern = pattern.lower() return ( pattern[0] == "." and (host.endswith(pattern) or host == pattern[1:]) or pattern == host ) def url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False): """ Return ``True`` if the url uses an allowed host and a safe scheme. Always return ``False`` on an empty url. If ``require_https`` is ``True``, only 'https' will be considered a valid scheme, as opposed to 'http' and 'https' with the default, ``False``. Note: "True" doesn't entail that a URL is "safe". It may still be e.g. quoted incorrectly. Ensure to also use django.utils.encoding.iri_to_uri() on the path component of untrusted URLs. """ if url is not None: url = url.strip() if not url: return False if allowed_hosts is None: allowed_hosts = set() elif isinstance(allowed_hosts, str): allowed_hosts = {allowed_hosts} # Chrome treats \ completely as / in paths but it could be part of some # basic auth credentials so we need to check both URLs. return _url_has_allowed_host_and_scheme( url, allowed_hosts, require_https=require_https ) and _url_has_allowed_host_and_scheme( url.replace("\\", "/"), allowed_hosts, require_https=require_https ) # TODO: Remove when dropping support for PY38. # Copied from urllib.parse.urlparse() but uses fixed urlsplit() function. def _urlparse(url, scheme="", allow_fragments=True): """Parse a URL into 6 components: <scheme>://<netloc>/<path>;<params>?<query>#<fragment> Return a 6-tuple: (scheme, netloc, path, params, query, fragment). Note that we don't break the components up in smaller bits (e.g. netloc is a single string) and we don't expand % escapes.""" url, scheme, _coerce_result = _coerce_args(url, scheme) splitresult = _urlsplit(url, scheme, allow_fragments) scheme, netloc, url, query, fragment = splitresult if scheme in uses_params and ";" in url: url, params = _splitparams(url) else: params = "" result = ParseResult(scheme, netloc, url, params, query, fragment) return _coerce_result(result) # TODO: Remove when dropping support for PY38. def _remove_unsafe_bytes_from_url(url): for b in _UNSAFE_URL_BYTES_TO_REMOVE: url = url.replace(b, "") return url # TODO: Remove when dropping support for PY38. # Backport of urllib.parse.urlsplit() from Python 3.9. def _urlsplit(url, scheme="", allow_fragments=True): """Parse a URL into 5 components: <scheme>://<netloc>/<path>?<query>#<fragment> Return a 5-tuple: (scheme, netloc, path, query, fragment). Note that we don't break the components up in smaller bits (e.g. netloc is a single string) and we don't expand % escapes.""" url, scheme, _coerce_result = _coerce_args(url, scheme) url = _remove_unsafe_bytes_from_url(url) scheme = _remove_unsafe_bytes_from_url(scheme) netloc = query = fragment = "" i = url.find(":") if i > 0: for c in url[:i]: if c not in scheme_chars: break else: scheme, url = url[:i].lower(), url[i + 1 :] if url[:2] == "//": netloc, url = _splitnetloc(url, 2) if ("[" in netloc and "]" not in netloc) or ( "]" in netloc and "[" not in netloc ): raise ValueError("Invalid IPv6 URL") if allow_fragments and "#" in url: url, fragment = url.split("#", 1) if "?" in url: url, query = url.split("?", 1) v = SplitResult(scheme, netloc, url, query, fragment) return _coerce_result(v) def _url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False): # Chrome considers any URL with more than two slashes to be absolute, but # urlparse is not so flexible. Treat any url with three slashes as unsafe. if url.startswith("///"): return False try: url_info = _urlparse(url) except ValueError: # e.g. invalid IPv6 addresses return False # Forbid URLs like http:///example.com - with a scheme, but without a hostname. # In that URL, example.com is not the hostname but, a path component. However, # Chrome will still consider example.com to be the hostname, so we must not # allow this syntax. if not url_info.netloc and url_info.scheme: return False # Forbid URLs that start with control characters. Some browsers (like # Chrome) ignore quite a few control characters at the start of a # URL and might consider the URL as scheme relative. if unicodedata.category(url[0])[0] == "C": return False scheme = url_info.scheme # Consider URLs without a scheme (e.g. //example.com/p) to be http. if not url_info.scheme and url_info.netloc: scheme = "http" valid_schemes = ["https"] if require_https else ["http", "https"] return (not url_info.netloc or url_info.netloc in allowed_hosts) and ( not scheme or scheme in valid_schemes ) def escape_leading_slashes(url): """ If redirecting to an absolute path (two leading slashes), a slash must be escaped to prevent browsers from handling the path as schemaless and redirecting to another host. """ if url.startswith("//"): url = "/%2F{}".format(url[2:]) return url def _parseparam(s): while s[:1] == ";": s = s[1:] end = s.find(";") while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2: end = s.find(";", end + 1) if end < 0: end = len(s) f = s[:end] yield f.strip() s = s[end:] def parse_header_parameters(line): """ Parse a Content-type like header. Return the main content-type and a dictionary of options. """ parts = _parseparam(";" + line) key = parts.__next__().lower() pdict = {} for p in parts: i = p.find("=") if i >= 0: has_encoding = False name = p[:i].strip().lower() if name.endswith("*"): # Lang/encoding embedded in the value (like "filename*=UTF-8''file.ext") # https://tools.ietf.org/html/rfc2231#section-4 name = name[:-1] if p.count("'") == 2: has_encoding = True value = p[i + 1 :].strip() if len(value) >= 2 and value[0] == value[-1] == '"': value = value[1:-1] value = value.replace("\\\\", "\\").replace('\\"', '"') if has_encoding: encoding, lang, value = value.split("'") value = unquote(value, encoding=encoding) pdict[name] = value return key, pdict
a90753b483d157295b19c16c2a797bc4c1f00336af52acd7795b38b079babceb
from django.http import HttpResponse from .loader import get_template, select_template class ContentNotRenderedError(Exception): pass class SimpleTemplateResponse(HttpResponse): non_picklable_attrs = HttpResponse.non_picklable_attrs | frozenset( ["template_name", "context_data", "_post_render_callbacks"] ) def __init__( self, template, context=None, content_type=None, status=None, charset=None, using=None, headers=None, ): # It would seem obvious to call these next two members 'template' and # 'context', but those names are reserved as part of the test Client # API. To avoid the name collision, we use different names. self.template_name = template self.context_data = context self.using = using self._post_render_callbacks = [] # _request stores the current request object in subclasses that know # about requests, like TemplateResponse. It's defined in the base class # to minimize code duplication. # It's called self._request because self.request gets overwritten by # django.test.client.Client. Unlike template_name and context_data, # _request should not be considered part of the public API. self._request = None # content argument doesn't make sense here because it will be replaced # with rendered template so we always pass empty string in order to # prevent errors and provide shorter signature. super().__init__("", content_type, status, charset=charset, headers=headers) # _is_rendered tracks whether the template and context has been baked # into a final response. # Super __init__ doesn't know any better than to set self.content to # the empty string we just gave it, which wrongly sets _is_rendered # True, so we initialize it to False after the call to super __init__. self._is_rendered = False def __getstate__(self): """ Raise an exception if trying to pickle an unrendered response. Pickle only rendered data, not the data used to construct the response. """ if not self._is_rendered: raise ContentNotRenderedError( "The response content must be rendered before it can be pickled." ) return super().__getstate__() def resolve_template(self, template): """Accept a template object, path-to-template, or list of paths.""" if isinstance(template, (list, tuple)): return select_template(template, using=self.using) elif isinstance(template, str): return get_template(template, using=self.using) else: return template def resolve_context(self, context): return context @property def rendered_content(self): """Return the freshly rendered content for the template and context described by the TemplateResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using the value of this property. """ template = self.resolve_template(self.template_name) context = self.resolve_context(self.context_data) return template.render(context, self._request) def add_post_render_callback(self, callback): """Add a new post-rendering callback. If the response has already been rendered, invoke the callback immediately. """ if self._is_rendered: callback(self) else: self._post_render_callbacks.append(callback) def render(self): """Render (thereby finalizing) the content of the response. If the content has already been rendered, this is a no-op. Return the baked response instance. """ retval = self if not self._is_rendered: self.content = self.rendered_content for post_callback in self._post_render_callbacks: newretval = post_callback(retval) if newretval is not None: retval = newretval return retval @property def is_rendered(self): return self._is_rendered def __iter__(self): if not self._is_rendered: raise ContentNotRenderedError( "The response content must be rendered before it can be iterated over." ) return super().__iter__() @property def content(self): if not self._is_rendered: raise ContentNotRenderedError( "The response content must be rendered before it can be accessed." ) return super().content @content.setter def content(self, value): """Set the content for the response.""" HttpResponse.content.fset(self, value) self._is_rendered = True class TemplateResponse(SimpleTemplateResponse): non_picklable_attrs = SimpleTemplateResponse.non_picklable_attrs | frozenset( ["_request"] ) def __init__( self, request, template, context=None, content_type=None, status=None, charset=None, using=None, headers=None, ): super().__init__( template, context, content_type, status, charset, using, headers=headers ) self._request = request
95a8513833b3fc6924fdafeda171897b788567d9f4c24fdd3aa50b90c8af3720
import re from urllib.parse import urlparse from django.conf import settings from django.core.exceptions import PermissionDenied from django.core.mail import mail_managers from django.http import HttpResponsePermanentRedirect from django.urls import is_valid_path from django.utils.deprecation import MiddlewareMixin from django.utils.http import escape_leading_slashes class CommonMiddleware(MiddlewareMixin): """ "Common" middleware for taking care of some basic operations: - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings, append missing slashes and/or prepends missing "www."s. - If APPEND_SLASH is set and the initial URL doesn't end with a slash, and it is not found in urlpatterns, form a new URL by appending a slash at the end. If this new URL is found in urlpatterns, return an HTTP redirect to this new URL; otherwise process the initial URL as usual. This behavior can be customized by subclassing CommonMiddleware and overriding the response_redirect_class attribute. """ response_redirect_class = HttpResponsePermanentRedirect def process_request(self, request): """ Check for denied User-Agents and rewrite the URL based on settings.APPEND_SLASH and settings.PREPEND_WWW """ # Check for denied User-Agents user_agent = request.META.get("HTTP_USER_AGENT") if user_agent is not None: for user_agent_regex in settings.DISALLOWED_USER_AGENTS: if user_agent_regex.search(user_agent): raise PermissionDenied("Forbidden user agent") # Check for a redirect based on settings.PREPEND_WWW host = request.get_host() if settings.PREPEND_WWW and host and not host.startswith("www."): # Check if we also need to append a slash so we can do it all # with a single redirect. (This check may be somewhat expensive, # so we only do it if we already know we're sending a redirect, # or in process_response if we get a 404.) if self.should_redirect_with_slash(request): path = self.get_full_path_with_slash(request) else: path = request.get_full_path() return self.response_redirect_class(f"{request.scheme}://www.{host}{path}") def should_redirect_with_slash(self, request): """ Return True if settings.APPEND_SLASH is True and appending a slash to the request path turns an invalid path into a valid one. """ if settings.APPEND_SLASH and not request.path_info.endswith("/"): urlconf = getattr(request, "urlconf", None) if not is_valid_path(request.path_info, urlconf): match = is_valid_path("%s/" % request.path_info, urlconf) if match: view = match.func return getattr(view, "should_append_slash", True) return False def get_full_path_with_slash(self, request): """ Return the full path of the request with a trailing slash appended. Raise a RuntimeError if settings.DEBUG is True and request.method is POST, PUT, or PATCH. """ new_path = request.get_full_path(force_append_slash=True) # Prevent construction of scheme relative urls. new_path = escape_leading_slashes(new_path) if settings.DEBUG and request.method in ("POST", "PUT", "PATCH"): raise RuntimeError( "You called this URL via %(method)s, but the URL doesn't end " "in a slash and you have APPEND_SLASH set. Django can't " "redirect to the slash URL while maintaining %(method)s data. " "Change your form to point to %(url)s (note the trailing " "slash), or set APPEND_SLASH=False in your Django settings." % { "method": request.method, "url": request.get_host() + new_path, } ) return new_path def process_response(self, request, response): """ When the status code of the response is 404, it may redirect to a path with an appended slash if should_redirect_with_slash() returns True. """ # If the given URL is "Not Found", then check if we should redirect to # a path with a slash appended. if response.status_code == 404 and self.should_redirect_with_slash(request): return self.response_redirect_class(self.get_full_path_with_slash(request)) # Add the Content-Length header to non-streaming responses if not # already set. if not response.streaming and not response.has_header("Content-Length"): response.headers["Content-Length"] = str(len(response.content)) return response class BrokenLinkEmailsMiddleware(MiddlewareMixin): def process_response(self, request, response): """Send broken link emails for relevant 404 NOT FOUND responses.""" if response.status_code == 404 and not settings.DEBUG: domain = request.get_host() path = request.get_full_path() referer = request.META.get("HTTP_REFERER", "") if not self.is_ignorable_request(request, path, domain, referer): ua = request.META.get("HTTP_USER_AGENT", "<none>") ip = request.META.get("REMOTE_ADDR", "<none>") mail_managers( "Broken %slink on %s" % ( ( "INTERNAL " if self.is_internal_request(domain, referer) else "" ), domain, ), "Referrer: %s\nRequested URL: %s\nUser agent: %s\n" "IP address: %s\n" % (referer, path, ua, ip), fail_silently=True, ) return response def is_internal_request(self, domain, referer): """ Return True if the referring URL is the same domain as the current request. """ # Different subdomains are treated as different domains. return bool(re.match("^https?://%s/" % re.escape(domain), referer)) def is_ignorable_request(self, request, uri, domain, referer): """ Return True if the given request *shouldn't* notify the site managers according to project settings or in situations outlined by the inline comments. """ # The referer is empty. if not referer: return True # APPEND_SLASH is enabled and the referer is equal to the current URL # without a trailing slash indicating an internal redirect. if settings.APPEND_SLASH and uri.endswith("/") and referer == uri[:-1]: return True # A '?' in referer is identified as a search engine source. if not self.is_internal_request(domain, referer) and "?" in referer: return True # The referer is equal to the current URL, ignoring the scheme (assumed # to be a poorly implemented bot). parsed_referer = urlparse(referer) if parsed_referer.netloc in ["", domain] and parsed_referer.path == uri: return True return any(pattern.search(uri) for pattern in settings.IGNORABLE_404_URLS)
70a73145dd1afb6ac2782138c34c4ffeb4bff7c18eb6bbb2b2d56aed04b63989
""" HTML Widget classes """ import copy import datetime import warnings from collections import defaultdict from itertools import chain from django.forms.utils import to_current_timezone from django.templatetags.static import static from django.utils import formats from django.utils.datastructures import OrderedSet from django.utils.dates import MONTHS from django.utils.formats import get_format from django.utils.html import format_html, html_safe from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.utils.topological_sort import CyclicDependencyError, stable_topological_sort from django.utils.translation import gettext_lazy as _ from .renderers import get_default_renderer __all__ = ( "Media", "MediaDefiningClass", "Widget", "TextInput", "NumberInput", "EmailInput", "URLInput", "PasswordInput", "HiddenInput", "MultipleHiddenInput", "FileInput", "ClearableFileInput", "Textarea", "DateInput", "DateTimeInput", "TimeInput", "CheckboxInput", "Select", "NullBooleanSelect", "SelectMultiple", "RadioSelect", "CheckboxSelectMultiple", "MultiWidget", "SplitDateTimeWidget", "SplitHiddenDateTimeWidget", "SelectDateWidget", ) MEDIA_TYPES = ("css", "js") class MediaOrderConflictWarning(RuntimeWarning): pass @html_safe class Media: def __init__(self, media=None, css=None, js=None): if media is not None: css = getattr(media, "css", {}) js = getattr(media, "js", []) else: if css is None: css = {} if js is None: js = [] self._css_lists = [css] self._js_lists = [js] def __repr__(self): return "Media(css=%r, js=%r)" % (self._css, self._js) def __str__(self): return self.render() @property def _css(self): css = defaultdict(list) for css_list in self._css_lists: for medium, sublist in css_list.items(): css[medium].append(sublist) return {medium: self.merge(*lists) for medium, lists in css.items()} @property def _js(self): return self.merge(*self._js_lists) def render(self): return mark_safe( "\n".join( chain.from_iterable( getattr(self, "render_" + name)() for name in MEDIA_TYPES ) ) ) def render_js(self): return [ path.__html__() if hasattr(path, "__html__") else format_html('<script src="{}"></script>', self.absolute_path(path)) for path in self._js ] def render_css(self): # To keep rendering order consistent, we can't just iterate over items(). # We need to sort the keys, and iterate over the sorted list. media = sorted(self._css) return chain.from_iterable( [ path.__html__() if hasattr(path, "__html__") else format_html( '<link href="{}" media="{}" rel="stylesheet">', self.absolute_path(path), medium, ) for path in self._css[medium] ] for medium in media ) def absolute_path(self, path): """ Given a relative or absolute path to a static asset, return an absolute path. An absolute path will be returned unchanged while a relative path will be passed to django.templatetags.static.static(). """ if path.startswith(("http://", "https://", "/")): return path return static(path) def __getitem__(self, name): """Return a Media object that only contains media of the given type.""" if name in MEDIA_TYPES: return Media(**{str(name): getattr(self, "_" + name)}) raise KeyError('Unknown media type "%s"' % name) @staticmethod def merge(*lists): """ Merge lists while trying to keep the relative order of the elements. Warn if the lists have the same elements in a different relative order. For static assets it can be important to have them included in the DOM in a certain order. In JavaScript you may not be able to reference a global or in CSS you might want to override a style. """ dependency_graph = defaultdict(set) all_items = OrderedSet() for list_ in filter(None, lists): head = list_[0] # The first items depend on nothing but have to be part of the # dependency graph to be included in the result. dependency_graph.setdefault(head, set()) for item in list_: all_items.add(item) # No self dependencies if head != item: dependency_graph[item].add(head) head = item try: return stable_topological_sort(all_items, dependency_graph) except CyclicDependencyError: warnings.warn( "Detected duplicate Media files in an opposite order: {}".format( ", ".join(repr(list_) for list_ in lists) ), MediaOrderConflictWarning, ) return list(all_items) def __add__(self, other): combined = Media() combined._css_lists = self._css_lists[:] combined._js_lists = self._js_lists[:] for item in other._css_lists: if item and item not in self._css_lists: combined._css_lists.append(item) for item in other._js_lists: if item and item not in self._js_lists: combined._js_lists.append(item) return combined def media_property(cls): def _media(self): # Get the media property of the superclass, if it exists sup_cls = super(cls, self) try: base = sup_cls.media except AttributeError: base = Media() # Get the media definition for this class definition = getattr(cls, "Media", None) if definition: extend = getattr(definition, "extend", True) if extend: if extend is True: m = base else: m = Media() for medium in extend: m = m + base[medium] return m + Media(definition) return Media(definition) return base return property(_media) class MediaDefiningClass(type): """ Metaclass for classes that can have media definitions. """ def __new__(mcs, name, bases, attrs): new_class = super().__new__(mcs, name, bases, attrs) if "media" not in attrs: new_class.media = media_property(new_class) return new_class class Widget(metaclass=MediaDefiningClass): needs_multipart_form = False # Determines does this widget need multipart form is_localized = False is_required = False supports_microseconds = True use_fieldset = False def __init__(self, attrs=None): self.attrs = {} if attrs is None else attrs.copy() def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() memo[id(self)] = obj return obj @property def is_hidden(self): return self.input_type == "hidden" if hasattr(self, "input_type") else False def subwidgets(self, name, value, attrs=None): context = self.get_context(name, value, attrs) yield context["widget"] def format_value(self, value): """ Return a value as it should appear when rendered in a template. """ if value == "" or value is None: return None if self.is_localized: return formats.localize_input(value) return str(value) def get_context(self, name, value, attrs): return { "widget": { "name": name, "is_hidden": self.is_hidden, "required": self.is_required, "value": self.format_value(value), "attrs": self.build_attrs(self.attrs, attrs), "template_name": self.template_name, }, } def render(self, name, value, attrs=None, renderer=None): """Render the widget as an HTML string.""" context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer) def _render(self, template_name, context, renderer=None): if renderer is None: renderer = get_default_renderer() return mark_safe(renderer.render(template_name, context)) def build_attrs(self, base_attrs, extra_attrs=None): """Build an attribute dictionary.""" return {**base_attrs, **(extra_attrs or {})} def value_from_datadict(self, data, files, name): """ Given a dictionary of data and this widget's name, return the value of this widget or None if it's not provided. """ return data.get(name) def value_omitted_from_data(self, data, files, name): return name not in data def id_for_label(self, id_): """ Return the HTML ID attribute of this Widget for use by a <label>, given the ID of the field. Return an empty string if no ID is available. This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget's tags. """ return id_ def use_required_attribute(self, initial): return not self.is_hidden class Input(Widget): """ Base class for all <input> widgets. """ input_type = None # Subclasses must define this. template_name = "django/forms/widgets/input.html" def __init__(self, attrs=None): if attrs is not None: attrs = attrs.copy() self.input_type = attrs.pop("type", self.input_type) super().__init__(attrs) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["type"] = self.input_type return context class TextInput(Input): input_type = "text" template_name = "django/forms/widgets/text.html" class NumberInput(Input): input_type = "number" template_name = "django/forms/widgets/number.html" class EmailInput(Input): input_type = "email" template_name = "django/forms/widgets/email.html" class URLInput(Input): input_type = "url" template_name = "django/forms/widgets/url.html" class PasswordInput(Input): input_type = "password" template_name = "django/forms/widgets/password.html" def __init__(self, attrs=None, render_value=False): super().__init__(attrs) self.render_value = render_value def get_context(self, name, value, attrs): if not self.render_value: value = None return super().get_context(name, value, attrs) class HiddenInput(Input): input_type = "hidden" template_name = "django/forms/widgets/hidden.html" class MultipleHiddenInput(HiddenInput): """ Handle <input type="hidden"> for fields that have a list of values. """ template_name = "django/forms/widgets/multiple_hidden.html" def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) final_attrs = context["widget"]["attrs"] id_ = context["widget"]["attrs"].get("id") subwidgets = [] for index, value_ in enumerate(context["widget"]["value"]): widget_attrs = final_attrs.copy() if id_: # An ID attribute was given. Add a numeric index as a suffix # so that the inputs don't all have the same ID attribute. widget_attrs["id"] = "%s_%s" % (id_, index) widget = HiddenInput() widget.is_required = self.is_required subwidgets.append(widget.get_context(name, value_, widget_attrs)["widget"]) context["widget"]["subwidgets"] = subwidgets return context def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def format_value(self, value): return [] if value is None else value class FileInput(Input): input_type = "file" needs_multipart_form = True template_name = "django/forms/widgets/file.html" def format_value(self, value): """File input never renders a value.""" return def value_from_datadict(self, data, files, name): "File widgets take data from FILES, not POST" return files.get(name) def value_omitted_from_data(self, data, files, name): return name not in files def use_required_attribute(self, initial): return super().use_required_attribute(initial) and not initial FILE_INPUT_CONTRADICTION = object() class ClearableFileInput(FileInput): clear_checkbox_label = _("Clear") initial_text = _("Currently") input_text = _("Change") template_name = "django/forms/widgets/clearable_file_input.html" def clear_checkbox_name(self, name): """ Given the name of the file input, return the name of the clear checkbox input. """ return name + "-clear" def clear_checkbox_id(self, name): """ Given the name of the clear checkbox input, return the HTML id for it. """ return name + "_id" def is_initial(self, value): """ Return whether value is considered to be initial value. """ return bool(value and getattr(value, "url", False)) def format_value(self, value): """ Return the file object if it has a defined url attribute. """ if self.is_initial(value): return value def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) context["widget"].update( { "checkbox_name": checkbox_name, "checkbox_id": checkbox_id, "is_initial": self.is_initial(value), "input_text": self.input_text, "initial_text": self.initial_text, "clear_checkbox_label": self.clear_checkbox_label, } ) return context def value_from_datadict(self, data, files, name): upload = super().value_from_datadict(data, files, name) if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name) ): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just None return False return upload def value_omitted_from_data(self, data, files, name): return ( super().value_omitted_from_data(data, files, name) and self.clear_checkbox_name(name) not in data ) class Textarea(Widget): template_name = "django/forms/widgets/textarea.html" def __init__(self, attrs=None): # Use slightly better defaults than HTML's 20x2 box default_attrs = {"cols": "40", "rows": "10"} if attrs: default_attrs.update(attrs) super().__init__(default_attrs) class DateTimeBaseInput(TextInput): format_key = "" supports_microseconds = False def __init__(self, attrs=None, format=None): super().__init__(attrs) self.format = format or None def format_value(self, value): return formats.localize_input( value, self.format or formats.get_format(self.format_key)[0] ) class DateInput(DateTimeBaseInput): format_key = "DATE_INPUT_FORMATS" template_name = "django/forms/widgets/date.html" class DateTimeInput(DateTimeBaseInput): format_key = "DATETIME_INPUT_FORMATS" template_name = "django/forms/widgets/datetime.html" class TimeInput(DateTimeBaseInput): format_key = "TIME_INPUT_FORMATS" template_name = "django/forms/widgets/time.html" # Defined at module level so that CheckboxInput is picklable (#17976) def boolean_check(v): return not (v is False or v is None or v == "") class CheckboxInput(Input): input_type = "checkbox" template_name = "django/forms/widgets/checkbox.html" def __init__(self, attrs=None, check_test=None): super().__init__(attrs) # check_test is a callable that takes a value and returns True # if the checkbox should be checked for that value. self.check_test = boolean_check if check_test is None else check_test def format_value(self, value): """Only return the 'value' attribute if value isn't empty.""" if value is True or value is False or value is None or value == "": return return str(value) def get_context(self, name, value, attrs): if self.check_test(value): attrs = {**(attrs or {}), "checked": True} return super().get_context(name, value, attrs) def value_from_datadict(self, data, files, name): if name not in data: # A missing value means False because HTML form submission does not # send results for unselected checkboxes. return False value = data.get(name) # Translate true and false strings to boolean values. values = {"true": True, "false": False} if isinstance(value, str): value = values.get(value.lower(), value) return bool(value) def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class ChoiceWidget(Widget): allow_multiple_selected = False input_type = None template_name = None option_template_name = None add_id_index = True checked_attribute = {"checked": True} option_inherits_attrs = True def __init__(self, attrs=None, choices=()): super().__init__(attrs) # choices can be any iterable, but we may need to render this widget # multiple times. Thus, collapse it into a list so it can be consumed # more than once. self.choices = list(choices) def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() obj.choices = copy.copy(self.choices) memo[id(self)] = obj return obj def subwidgets(self, name, value, attrs=None): """ Yield all "subwidgets" of this widget. Used to enable iterating options from a BoundField for choice widgets. """ value = self.format_value(value) yield from self.options(name, value, attrs) def options(self, name, value, attrs=None): """Yield a flat list of options for this widget.""" for group in self.optgroups(name, value, attrs): yield from group[1] def optgroups(self, name, value, attrs=None): """Return a list of optgroups for this widget.""" groups = [] has_selected = False for index, (option_value, option_label) in enumerate(self.choices): if option_value is None: option_value = "" subgroup = [] if isinstance(option_label, (list, tuple)): group_name = option_value subindex = 0 choices = option_label else: group_name = None subindex = None choices = [(option_value, option_label)] groups.append((group_name, subgroup, index)) for subvalue, sublabel in choices: selected = (not has_selected or self.allow_multiple_selected) and str( subvalue ) in value has_selected |= selected subgroup.append( self.create_option( name, subvalue, sublabel, selected, index, subindex=subindex, attrs=attrs, ) ) if subindex is not None: subindex += 1 return groups def create_option( self, name, value, label, selected, index, subindex=None, attrs=None ): index = str(index) if subindex is None else "%s_%s" % (index, subindex) option_attrs = ( self.build_attrs(self.attrs, attrs) if self.option_inherits_attrs else {} ) if selected: option_attrs.update(self.checked_attribute) if "id" in option_attrs: option_attrs["id"] = self.id_for_label(option_attrs["id"], index) return { "name": name, "value": value, "label": label, "selected": selected, "index": index, "attrs": option_attrs, "type": self.input_type, "template_name": self.option_template_name, "wrap_label": True, } def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["optgroups"] = self.optgroups( name, context["widget"]["value"], attrs ) return context def id_for_label(self, id_, index="0"): """ Use an incremented id for each option where the main widget references the zero index. """ if id_ and self.add_id_index: id_ = "%s_%s" % (id_, index) return id_ def value_from_datadict(self, data, files, name): getter = data.get if self.allow_multiple_selected: try: getter = data.getlist except AttributeError: pass return getter(name) def format_value(self, value): """Return selected values as a list.""" if value is None and self.allow_multiple_selected: return [] if not isinstance(value, (tuple, list)): value = [value] return [str(v) if v is not None else "" for v in value] class Select(ChoiceWidget): input_type = "select" template_name = "django/forms/widgets/select.html" option_template_name = "django/forms/widgets/select_option.html" add_id_index = False checked_attribute = {"selected": True} option_inherits_attrs = False def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.allow_multiple_selected: context["widget"]["attrs"]["multiple"] = True return context @staticmethod def _choice_has_empty_value(choice): """Return True if the choice's value is empty string or None.""" value, _ = choice return value is None or value == "" def use_required_attribute(self, initial): """ Don't render 'required' if the first <option> has a value, as that's invalid HTML. """ use_required_attribute = super().use_required_attribute(initial) # 'required' is always okay for <select multiple>. if self.allow_multiple_selected: return use_required_attribute first_choice = next(iter(self.choices), None) return ( use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice) ) class NullBooleanSelect(Select): """ A Select Widget intended to be used with NullBooleanField. """ def __init__(self, attrs=None): choices = ( ("unknown", _("Unknown")), ("true", _("Yes")), ("false", _("No")), ) super().__init__(attrs, choices) def format_value(self, value): try: return { True: "true", False: "false", "true": "true", "false": "false", # For backwards compatibility with Django < 2.2. "2": "true", "3": "false", }[value] except KeyError: return "unknown" def value_from_datadict(self, data, files, name): value = data.get(name) return { True: True, "True": True, "False": False, False: False, "true": True, "false": False, # For backwards compatibility with Django < 2.2. "2": True, "3": False, }.get(value) class SelectMultiple(Select): allow_multiple_selected = True def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def value_omitted_from_data(self, data, files, name): # An unselected <select multiple> doesn't appear in POST data, so it's # never known if the value is actually omitted. return False class RadioSelect(ChoiceWidget): input_type = "radio" template_name = "django/forms/widgets/radio.html" option_template_name = "django/forms/widgets/radio_option.html" use_fieldset = True def id_for_label(self, id_, index=None): """ Don't include for="field_0" in <label> to improve accessibility when using a screen reader, in addition clicking such a label would toggle the first input. """ if index is None: return "" return super().id_for_label(id_, index) class CheckboxSelectMultiple(RadioSelect): allow_multiple_selected = True input_type = "checkbox" template_name = "django/forms/widgets/checkbox_select.html" option_template_name = "django/forms/widgets/checkbox_option.html" def use_required_attribute(self, initial): # Don't use the 'required' attribute because browser validation would # require all checkboxes to be checked instead of at least one. return False def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class MultiWidget(Widget): """ A widget that is composed of multiple widgets. In addition to the values added by Widget.get_context(), this widget adds a list of subwidgets to the context as widget['subwidgets']. These can be looped over and rendered like normal widgets. You'll probably want to use this class with MultiValueField. """ template_name = "django/forms/widgets/multiwidget.html" use_fieldset = True def __init__(self, widgets, attrs=None): if isinstance(widgets, dict): self.widgets_names = [("_%s" % name) if name else "" for name in widgets] widgets = widgets.values() else: self.widgets_names = ["_%s" % i for i in range(len(widgets))] self.widgets = [w() if isinstance(w, type) else w for w in widgets] super().__init__(attrs) @property def is_hidden(self): return all(w.is_hidden for w in self.widgets) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_localized # value is a list/tuple of values, each corresponding to a widget # in self.widgets. if not isinstance(value, (list, tuple)): value = self.decompress(value) final_attrs = context["widget"]["attrs"] input_type = final_attrs.pop("type", None) id_ = final_attrs.get("id") subwidgets = [] for i, (widget_name, widget) in enumerate( zip(self.widgets_names, self.widgets) ): if input_type is not None: widget.input_type = input_type widget_name = name + widget_name try: widget_value = value[i] except IndexError: widget_value = None if id_: widget_attrs = final_attrs.copy() widget_attrs["id"] = "%s_%s" % (id_, i) else: widget_attrs = final_attrs subwidgets.append( widget.get_context(widget_name, widget_value, widget_attrs)["widget"] ) context["widget"]["subwidgets"] = subwidgets return context def id_for_label(self, id_): return "" def value_from_datadict(self, data, files, name): return [ widget.value_from_datadict(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ] def value_omitted_from_data(self, data, files, name): return all( widget.value_omitted_from_data(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ) def decompress(self, value): """ Return a list of decompressed values for the given compressed value. The given value can be assumed to be valid, but not necessarily non-empty. """ raise NotImplementedError("Subclasses must implement this method.") def _get_media(self): """ Media for a multiwidget is the combination of all media of the subwidgets. """ media = Media() for w in self.widgets: media = media + w.media return media media = property(_get_media) def __deepcopy__(self, memo): obj = super().__deepcopy__(memo) obj.widgets = copy.deepcopy(self.widgets) return obj @property def needs_multipart_form(self): return any(w.needs_multipart_form for w in self.widgets) class SplitDateTimeWidget(MultiWidget): """ A widget that splits datetime input into two <input type="text"> boxes. """ supports_microseconds = False template_name = "django/forms/widgets/splitdatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None, ): widgets = ( DateInput( attrs=attrs if date_attrs is None else date_attrs, format=date_format, ), TimeInput( attrs=attrs if time_attrs is None else time_attrs, format=time_format, ), ) super().__init__(widgets) def decompress(self, value): if value: value = to_current_timezone(value) return [value.date(), value.time()] return [None, None] class SplitHiddenDateTimeWidget(SplitDateTimeWidget): """ A widget that splits datetime input into two <input type="hidden"> inputs. """ template_name = "django/forms/widgets/splithiddendatetime.html" def __init__( self, attrs=None, date_format=None, time_format=None, date_attrs=None, time_attrs=None, ): super().__init__(attrs, date_format, time_format, date_attrs, time_attrs) for widget in self.widgets: widget.input_type = "hidden" class SelectDateWidget(Widget): """ A widget that splits date input into three <select> boxes. This also serves as an example of a Widget that has more than one HTML element and hence implements value_from_datadict. """ none_value = ("", "---") month_field = "%s_month" day_field = "%s_day" year_field = "%s_year" template_name = "django/forms/widgets/select_date.html" input_type = "select" select_widget = Select date_re = _lazy_re_compile(r"(\d{4}|0)-(\d\d?)-(\d\d?)$") use_fieldset = True def __init__(self, attrs=None, years=None, months=None, empty_label=None): self.attrs = attrs or {} # Optional list or tuple of years to use in the "year" select box. if years: self.years = years else: this_year = datetime.date.today().year self.years = range(this_year, this_year + 10) # Optional dict of months to use in the "month" select box. if months: self.months = months else: self.months = MONTHS # Optional string, list, or tuple to use as empty_label. if isinstance(empty_label, (list, tuple)): if not len(empty_label) == 3: raise ValueError("empty_label list/tuple must have 3 elements.") self.year_none_value = ("", empty_label[0]) self.month_none_value = ("", empty_label[1]) self.day_none_value = ("", empty_label[2]) else: if empty_label is not None: self.none_value = ("", empty_label) self.year_none_value = self.none_value self.month_none_value = self.none_value self.day_none_value = self.none_value def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) date_context = {} year_choices = [(i, str(i)) for i in self.years] if not self.is_required: year_choices.insert(0, self.year_none_value) year_name = self.year_field % name date_context["year"] = self.select_widget( attrs, choices=year_choices ).get_context( name=year_name, value=context["widget"]["value"]["year"], attrs={**context["widget"]["attrs"], "id": "id_%s" % year_name}, ) month_choices = list(self.months.items()) if not self.is_required: month_choices.insert(0, self.month_none_value) month_name = self.month_field % name date_context["month"] = self.select_widget( attrs, choices=month_choices ).get_context( name=month_name, value=context["widget"]["value"]["month"], attrs={**context["widget"]["attrs"], "id": "id_%s" % month_name}, ) day_choices = [(i, i) for i in range(1, 32)] if not self.is_required: day_choices.insert(0, self.day_none_value) day_name = self.day_field % name date_context["day"] = self.select_widget( attrs, choices=day_choices, ).get_context( name=day_name, value=context["widget"]["value"]["day"], attrs={**context["widget"]["attrs"], "id": "id_%s" % day_name}, ) subwidgets = [] for field in self._parse_date_fmt(): subwidgets.append(date_context[field]["widget"]) context["widget"]["subwidgets"] = subwidgets return context def format_value(self, value): """ Return a dict containing the year, month, and day of the current value. Use dict instead of a datetime to allow invalid dates such as February 31 to display correctly. """ year, month, day = None, None, None if isinstance(value, (datetime.date, datetime.datetime)): year, month, day = value.year, value.month, value.day elif isinstance(value, str): match = self.date_re.match(value) if match: # Convert any zeros in the date to empty strings to match the # empty option value. year, month, day = [int(val) or "" for val in match.groups()] else: input_format = get_format("DATE_INPUT_FORMATS")[0] try: d = datetime.datetime.strptime(value, input_format) except ValueError: pass else: year, month, day = d.year, d.month, d.day return {"year": year, "month": month, "day": day} @staticmethod def _parse_date_fmt(): fmt = get_format("DATE_FORMAT") escaped = False for char in fmt: if escaped: escaped = False elif char == "\\": escaped = True elif char in "Yy": yield "year" elif char in "bEFMmNn": yield "month" elif char in "dj": yield "day" def id_for_label(self, id_): for first_select in self._parse_date_fmt(): return "%s_%s" % (id_, first_select) return "%s_month" % id_ def value_from_datadict(self, data, files, name): y = data.get(self.year_field % name) m = data.get(self.month_field % name) d = data.get(self.day_field % name) if y == m == d == "": return None if y is not None and m is not None and d is not None: input_format = get_format("DATE_INPUT_FORMATS")[0] input_format = formats.sanitize_strftime_format(input_format) try: date_value = datetime.date(int(y), int(m), int(d)) except ValueError: # Return pseudo-ISO dates with zeros for any unselected values, # e.g. '2017-0-23'. return "%s-%s-%s" % (y or 0, m or 0, d or 0) return date_value.strftime(input_format) return data.get(name) def value_omitted_from_data(self, data, files, name): return not any( ("{}_{}".format(name, interval) in data) for interval in ("year", "month", "day") )