1. import tempfile
    
  2. from io import StringIO
    
  3. 
    
  4. from django.contrib.gis import gdal
    
  5. from django.contrib.gis.db.models import Extent, MakeLine, Union, functions
    
  6. from django.contrib.gis.geos import (
    
  7.     GeometryCollection,
    
  8.     GEOSGeometry,
    
  9.     LinearRing,
    
  10.     LineString,
    
  11.     MultiLineString,
    
  12.     MultiPoint,
    
  13.     MultiPolygon,
    
  14.     Point,
    
  15.     Polygon,
    
  16.     fromstr,
    
  17. )
    
  18. from django.core.management import call_command
    
  19. from django.db import DatabaseError, NotSupportedError, connection
    
  20. from django.db.models import F, OuterRef, Subquery
    
  21. from django.test import TestCase, skipUnlessDBFeature
    
  22. from django.test.utils import CaptureQueriesContext
    
  23. 
    
  24. from ..utils import skipUnlessGISLookup
    
  25. from .models import (
    
  26.     City,
    
  27.     Country,
    
  28.     Feature,
    
  29.     MinusOneSRID,
    
  30.     MultiFields,
    
  31.     NonConcreteModel,
    
  32.     PennsylvaniaCity,
    
  33.     State,
    
  34.     Track,
    
  35. )
    
  36. 
    
  37. 
    
  38. class GeoModelTest(TestCase):
    
  39.     fixtures = ["initial"]
    
  40. 
    
  41.     def test_fixtures(self):
    
  42.         "Testing geographic model initialization from fixtures."
    
  43.         # Ensuring that data was loaded from initial data fixtures.
    
  44.         self.assertEqual(2, Country.objects.count())
    
  45.         self.assertEqual(8, City.objects.count())
    
  46.         self.assertEqual(2, State.objects.count())
    
  47. 
    
  48.     def test_proxy(self):
    
  49.         "Testing Lazy-Geometry support (using the GeometryProxy)."
    
  50.         # Testing on a Point
    
  51.         pnt = Point(0, 0)
    
  52.         nullcity = City(name="NullCity", point=pnt)
    
  53.         nullcity.save()
    
  54. 
    
  55.         # Making sure TypeError is thrown when trying to set with an
    
  56.         #  incompatible type.
    
  57.         for bad in [5, 2.0, LineString((0, 0), (1, 1))]:
    
  58.             with self.assertRaisesMessage(TypeError, "Cannot set"):
    
  59.                 nullcity.point = bad
    
  60. 
    
  61.         # Now setting with a compatible GEOS Geometry, saving, and ensuring
    
  62.         #  the save took, notice no SRID is explicitly set.
    
  63.         new = Point(5, 23)
    
  64.         nullcity.point = new
    
  65. 
    
  66.         # Ensuring that the SRID is automatically set to that of the
    
  67.         #  field after assignment, but before saving.
    
  68.         self.assertEqual(4326, nullcity.point.srid)
    
  69.         nullcity.save()
    
  70. 
    
  71.         # Ensuring the point was saved correctly after saving
    
  72.         self.assertEqual(new, City.objects.get(name="NullCity").point)
    
  73. 
    
  74.         # Setting the X and Y of the Point
    
  75.         nullcity.point.x = 23
    
  76.         nullcity.point.y = 5
    
  77.         # Checking assignments pre & post-save.
    
  78.         self.assertNotEqual(
    
  79.             Point(23, 5, srid=4326), City.objects.get(name="NullCity").point
    
  80.         )
    
  81.         nullcity.save()
    
  82.         self.assertEqual(
    
  83.             Point(23, 5, srid=4326), City.objects.get(name="NullCity").point
    
  84.         )
    
  85.         nullcity.delete()
    
  86. 
    
  87.         # Testing on a Polygon
    
  88.         shell = LinearRing((0, 0), (0, 90), (100, 90), (100, 0), (0, 0))
    
  89.         inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40))
    
  90. 
    
  91.         # Creating a State object using a built Polygon
    
  92.         ply = Polygon(shell, inner)
    
  93.         nullstate = State(name="NullState", poly=ply)
    
  94.         self.assertEqual(4326, nullstate.poly.srid)  # SRID auto-set from None
    
  95.         nullstate.save()
    
  96. 
    
  97.         ns = State.objects.get(name="NullState")
    
  98.         self.assertEqual(connection.ops.Adapter._fix_polygon(ply), ns.poly)
    
  99. 
    
  100.         # Testing the `ogr` and `srs` lazy-geometry properties.
    
  101.         self.assertIsInstance(ns.poly.ogr, gdal.OGRGeometry)
    
  102.         self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb)
    
  103.         self.assertIsInstance(ns.poly.srs, gdal.SpatialReference)
    
  104.         self.assertEqual("WGS 84", ns.poly.srs.name)
    
  105. 
    
  106.         # Changing the interior ring on the poly attribute.
    
  107.         new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30))
    
  108.         ns.poly[1] = new_inner
    
  109.         ply[1] = new_inner
    
  110.         self.assertEqual(4326, ns.poly.srid)
    
  111.         ns.save()
    
  112.         self.assertEqual(
    
  113.             connection.ops.Adapter._fix_polygon(ply),
    
  114.             State.objects.get(name="NullState").poly,
    
  115.         )
    
  116.         ns.delete()
    
  117. 
    
  118.     @skipUnlessDBFeature("supports_transform")
    
  119.     def test_lookup_insert_transform(self):
    
  120.         "Testing automatic transform for lookups and inserts."
    
  121.         # San Antonio in 'WGS84' (SRID 4326)
    
  122.         sa_4326 = "POINT (-98.493183 29.424170)"
    
  123.         wgs_pnt = fromstr(sa_4326, srid=4326)  # Our reference point in WGS84
    
  124.         # San Antonio in 'WGS 84 / Pseudo-Mercator' (SRID 3857)
    
  125.         other_srid_pnt = wgs_pnt.transform(3857, clone=True)
    
  126.         # Constructing & querying with a point from a different SRID. Oracle
    
  127.         # `SDO_OVERLAPBDYINTERSECT` operates differently from
    
  128.         # `ST_Intersects`, so contains is used instead.
    
  129.         if connection.ops.oracle:
    
  130.             tx = Country.objects.get(mpoly__contains=other_srid_pnt)
    
  131.         else:
    
  132.             tx = Country.objects.get(mpoly__intersects=other_srid_pnt)
    
  133.         self.assertEqual("Texas", tx.name)
    
  134. 
    
  135.         # Creating San Antonio.  Remember the Alamo.
    
  136.         sa = City.objects.create(name="San Antonio", point=other_srid_pnt)
    
  137. 
    
  138.         # Now verifying that San Antonio was transformed correctly
    
  139.         sa = City.objects.get(name="San Antonio")
    
  140.         self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6)
    
  141.         self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6)
    
  142. 
    
  143.         # If the GeometryField SRID is -1, then we shouldn't perform any
    
  144.         # transformation if the SRID of the input geometry is different.
    
  145.         m1 = MinusOneSRID(geom=Point(17, 23, srid=4326))
    
  146.         m1.save()
    
  147.         self.assertEqual(-1, m1.geom.srid)
    
  148. 
    
  149.     def test_createnull(self):
    
  150.         "Testing creating a model instance and the geometry being None"
    
  151.         c = City()
    
  152.         self.assertIsNone(c.point)
    
  153. 
    
  154.     def test_geometryfield(self):
    
  155.         "Testing the general GeometryField."
    
  156.         Feature(name="Point", geom=Point(1, 1)).save()
    
  157.         Feature(name="LineString", geom=LineString((0, 0), (1, 1), (5, 5))).save()
    
  158.         Feature(
    
  159.             name="Polygon",
    
  160.             geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))),
    
  161.         ).save()
    
  162.         Feature(
    
  163.             name="GeometryCollection",
    
  164.             geom=GeometryCollection(
    
  165.                 Point(2, 2),
    
  166.                 LineString((0, 0), (2, 2)),
    
  167.                 Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))),
    
  168.             ),
    
  169.         ).save()
    
  170. 
    
  171.         f_1 = Feature.objects.get(name="Point")
    
  172.         self.assertIsInstance(f_1.geom, Point)
    
  173.         self.assertEqual((1.0, 1.0), f_1.geom.tuple)
    
  174.         f_2 = Feature.objects.get(name="LineString")
    
  175.         self.assertIsInstance(f_2.geom, LineString)
    
  176.         self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple)
    
  177. 
    
  178.         f_3 = Feature.objects.get(name="Polygon")
    
  179.         self.assertIsInstance(f_3.geom, Polygon)
    
  180.         f_4 = Feature.objects.get(name="GeometryCollection")
    
  181.         self.assertIsInstance(f_4.geom, GeometryCollection)
    
  182.         self.assertEqual(f_3.geom, f_4.geom[2])
    
  183. 
    
  184.     @skipUnlessDBFeature("supports_transform")
    
  185.     def test_inherited_geofields(self):
    
  186.         "Database functions on inherited Geometry fields."
    
  187.         # Creating a Pennsylvanian city.
    
  188.         PennsylvaniaCity.objects.create(
    
  189.             name="Mansfield", county="Tioga", point="POINT(-77.071445 41.823881)"
    
  190.         )
    
  191. 
    
  192.         # All transformation SQL will need to be performed on the
    
  193.         # _parent_ table.
    
  194.         qs = PennsylvaniaCity.objects.annotate(
    
  195.             new_point=functions.Transform("point", srid=32128)
    
  196.         )
    
  197. 
    
  198.         self.assertEqual(1, qs.count())
    
  199.         for pc in qs:
    
  200.             self.assertEqual(32128, pc.new_point.srid)
    
  201. 
    
  202.     def test_raw_sql_query(self):
    
  203.         "Testing raw SQL query."
    
  204.         cities1 = City.objects.all()
    
  205.         point_select = connection.ops.select % "point"
    
  206.         cities2 = list(
    
  207.             City.objects.raw(
    
  208.                 "select id, name, %s as point from geoapp_city" % point_select
    
  209.             )
    
  210.         )
    
  211.         self.assertEqual(len(cities1), len(cities2))
    
  212.         with self.assertNumQueries(0):  # Ensure point isn't deferred.
    
  213.             self.assertIsInstance(cities2[0].point, Point)
    
  214. 
    
  215.     def test_gis_query_as_string(self):
    
  216.         """GIS queries can be represented as strings."""
    
  217.         query = City.objects.filter(point__within=Polygon.from_bbox((0, 0, 2, 2)))
    
  218.         self.assertIn(
    
  219.             connection.ops.quote_name(City._meta.db_table),
    
  220.             str(query.query),
    
  221.         )
    
  222. 
    
  223.     def test_dumpdata_loaddata_cycle(self):
    
  224.         """
    
  225.         Test a dumpdata/loaddata cycle with geographic data.
    
  226.         """
    
  227.         out = StringIO()
    
  228.         original_data = list(City.objects.order_by("name"))
    
  229.         call_command("dumpdata", "geoapp.City", stdout=out)
    
  230.         result = out.getvalue()
    
  231.         houston = City.objects.get(name="Houston")
    
  232.         self.assertIn('"point": "%s"' % houston.point.ewkt, result)
    
  233. 
    
  234.         # Reload now dumped data
    
  235.         with tempfile.NamedTemporaryFile(mode="w", suffix=".json") as tmp:
    
  236.             tmp.write(result)
    
  237.             tmp.seek(0)
    
  238.             call_command("loaddata", tmp.name, verbosity=0)
    
  239.         self.assertEqual(original_data, list(City.objects.order_by("name")))
    
  240. 
    
  241.     @skipUnlessDBFeature("supports_empty_geometries")
    
  242.     def test_empty_geometries(self):
    
  243.         geometry_classes = [
    
  244.             Point,
    
  245.             LineString,
    
  246.             LinearRing,
    
  247.             Polygon,
    
  248.             MultiPoint,
    
  249.             MultiLineString,
    
  250.             MultiPolygon,
    
  251.             GeometryCollection,
    
  252.         ]
    
  253.         for klass in geometry_classes:
    
  254.             g = klass(srid=4326)
    
  255.             feature = Feature.objects.create(name="Empty %s" % klass.__name__, geom=g)
    
  256.             feature.refresh_from_db()
    
  257.             if klass is LinearRing:
    
  258.                 # LinearRing isn't representable in WKB, so GEOSGeomtry.wkb
    
  259.                 # uses LineString instead.
    
  260.                 g = LineString(srid=4326)
    
  261.             self.assertEqual(feature.geom, g)
    
  262.             self.assertEqual(feature.geom.srid, g.srid)
    
  263. 
    
  264. 
    
  265. class GeoLookupTest(TestCase):
    
  266.     fixtures = ["initial"]
    
  267. 
    
  268.     def test_disjoint_lookup(self):
    
  269.         "Testing the `disjoint` lookup type."
    
  270.         ptown = City.objects.get(name="Pueblo")
    
  271.         qs1 = City.objects.filter(point__disjoint=ptown.point)
    
  272.         self.assertEqual(7, qs1.count())
    
  273.         qs2 = State.objects.filter(poly__disjoint=ptown.point)
    
  274.         self.assertEqual(1, qs2.count())
    
  275.         self.assertEqual("Kansas", qs2[0].name)
    
  276. 
    
  277.     def test_contains_contained_lookups(self):
    
  278.         "Testing the 'contained', 'contains', and 'bbcontains' lookup types."
    
  279.         # Getting Texas, yes we were a country -- once ;)
    
  280.         texas = Country.objects.get(name="Texas")
    
  281. 
    
  282.         # Seeing what cities are in Texas, should get Houston and Dallas,
    
  283.         #  and Oklahoma City because 'contained' only checks on the
    
  284.         #  _bounding box_ of the Geometries.
    
  285.         if connection.features.supports_contained_lookup:
    
  286.             qs = City.objects.filter(point__contained=texas.mpoly)
    
  287.             self.assertEqual(3, qs.count())
    
  288.             cities = ["Houston", "Dallas", "Oklahoma City"]
    
  289.             for c in qs:
    
  290.                 self.assertIn(c.name, cities)
    
  291. 
    
  292.         # Pulling out some cities.
    
  293.         houston = City.objects.get(name="Houston")
    
  294.         wellington = City.objects.get(name="Wellington")
    
  295.         pueblo = City.objects.get(name="Pueblo")
    
  296.         okcity = City.objects.get(name="Oklahoma City")
    
  297.         lawrence = City.objects.get(name="Lawrence")
    
  298. 
    
  299.         # Now testing contains on the countries using the points for
    
  300.         #  Houston and Wellington.
    
  301.         tx = Country.objects.get(mpoly__contains=houston.point)  # Query w/GEOSGeometry
    
  302.         nz = Country.objects.get(
    
  303.             mpoly__contains=wellington.point.hex
    
  304.         )  # Query w/EWKBHEX
    
  305.         self.assertEqual("Texas", tx.name)
    
  306.         self.assertEqual("New Zealand", nz.name)
    
  307. 
    
  308.         # Testing `contains` on the states using the point for Lawrence.
    
  309.         ks = State.objects.get(poly__contains=lawrence.point)
    
  310.         self.assertEqual("Kansas", ks.name)
    
  311. 
    
  312.         # Pueblo and Oklahoma City (even though OK City is within the bounding
    
  313.         # box of Texas) are not contained in Texas or New Zealand.
    
  314.         self.assertEqual(
    
  315.             len(Country.objects.filter(mpoly__contains=pueblo.point)), 0
    
  316.         )  # Query w/GEOSGeometry object
    
  317.         self.assertEqual(
    
  318.             len(Country.objects.filter(mpoly__contains=okcity.point.wkt)), 0
    
  319.         )  # Query w/WKT
    
  320. 
    
  321.         # OK City is contained w/in bounding box of Texas.
    
  322.         if connection.features.supports_bbcontains_lookup:
    
  323.             qs = Country.objects.filter(mpoly__bbcontains=okcity.point)
    
  324.             self.assertEqual(1, len(qs))
    
  325.             self.assertEqual("Texas", qs[0].name)
    
  326. 
    
  327.     @skipUnlessDBFeature("supports_crosses_lookup")
    
  328.     def test_crosses_lookup(self):
    
  329.         Track.objects.create(name="Line1", line=LineString([(-95, 29), (-60, 0)]))
    
  330.         self.assertEqual(
    
  331.             Track.objects.filter(
    
  332.                 line__crosses=LineString([(-95, 0), (-60, 29)])
    
  333.             ).count(),
    
  334.             1,
    
  335.         )
    
  336.         self.assertEqual(
    
  337.             Track.objects.filter(
    
  338.                 line__crosses=LineString([(-95, 30), (0, 30)])
    
  339.             ).count(),
    
  340.             0,
    
  341.         )
    
  342. 
    
  343.     @skipUnlessDBFeature("supports_isvalid_lookup")
    
  344.     def test_isvalid_lookup(self):
    
  345.         invalid_geom = fromstr("POLYGON((0 0, 0 1, 1 1, 1 0, 1 1, 1 0, 0 0))")
    
  346.         State.objects.create(name="invalid", poly=invalid_geom)
    
  347.         qs = State.objects.all()
    
  348.         if connection.ops.oracle or (
    
  349.             connection.ops.mysql and connection.mysql_version < (8, 0, 0)
    
  350.         ):
    
  351.             # Kansas has adjacent vertices with distance 6.99244813842e-12
    
  352.             # which is smaller than the default Oracle tolerance.
    
  353.             # It's invalid on MySQL < 8 also.
    
  354.             qs = qs.exclude(name="Kansas")
    
  355.             self.assertEqual(
    
  356.                 State.objects.filter(name="Kansas", poly__isvalid=False).count(), 1
    
  357.             )
    
  358.         self.assertEqual(qs.filter(poly__isvalid=False).count(), 1)
    
  359.         self.assertEqual(qs.filter(poly__isvalid=True).count(), qs.count() - 1)
    
  360. 
    
  361.     @skipUnlessGISLookup("left", "right")
    
  362.     def test_left_right_lookups(self):
    
  363.         "Testing the 'left' and 'right' lookup types."
    
  364.         # Left: A << B => true if xmax(A) < xmin(B)
    
  365.         # Right: A >> B => true if xmin(A) > xmax(B)
    
  366.         # See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source.
    
  367. 
    
  368.         # Getting the borders for Colorado & Kansas
    
  369.         co_border = State.objects.get(name="Colorado").poly
    
  370.         ks_border = State.objects.get(name="Kansas").poly
    
  371. 
    
  372.         # Note: Wellington has an 'X' value of 174, so it will not be considered
    
  373.         # to the left of CO.
    
  374. 
    
  375.         # These cities should be strictly to the right of the CO border.
    
  376.         cities = [
    
  377.             "Houston",
    
  378.             "Dallas",
    
  379.             "Oklahoma City",
    
  380.             "Lawrence",
    
  381.             "Chicago",
    
  382.             "Wellington",
    
  383.         ]
    
  384.         qs = City.objects.filter(point__right=co_border)
    
  385.         self.assertEqual(6, len(qs))
    
  386.         for c in qs:
    
  387.             self.assertIn(c.name, cities)
    
  388. 
    
  389.         # These cities should be strictly to the right of the KS border.
    
  390.         cities = ["Chicago", "Wellington"]
    
  391.         qs = City.objects.filter(point__right=ks_border)
    
  392.         self.assertEqual(2, len(qs))
    
  393.         for c in qs:
    
  394.             self.assertIn(c.name, cities)
    
  395. 
    
  396.         # Note: Wellington has an 'X' value of 174, so it will not be considered
    
  397.         #  to the left of CO.
    
  398.         vic = City.objects.get(point__left=co_border)
    
  399.         self.assertEqual("Victoria", vic.name)
    
  400. 
    
  401.         cities = ["Pueblo", "Victoria"]
    
  402.         qs = City.objects.filter(point__left=ks_border)
    
  403.         self.assertEqual(2, len(qs))
    
  404.         for c in qs:
    
  405.             self.assertIn(c.name, cities)
    
  406. 
    
  407.     @skipUnlessGISLookup("strictly_above", "strictly_below")
    
  408.     def test_strictly_above_below_lookups(self):
    
  409.         dallas = City.objects.get(name="Dallas")
    
  410.         self.assertQuerysetEqual(
    
  411.             City.objects.filter(point__strictly_above=dallas.point).order_by("name"),
    
  412.             ["Chicago", "Lawrence", "Oklahoma City", "Pueblo", "Victoria"],
    
  413.             lambda b: b.name,
    
  414.         )
    
  415.         self.assertQuerysetEqual(
    
  416.             City.objects.filter(point__strictly_below=dallas.point).order_by("name"),
    
  417.             ["Houston", "Wellington"],
    
  418.             lambda b: b.name,
    
  419.         )
    
  420. 
    
  421.     def test_equals_lookups(self):
    
  422.         "Testing the 'same_as' and 'equals' lookup types."
    
  423.         pnt = fromstr("POINT (-95.363151 29.763374)", srid=4326)
    
  424.         c1 = City.objects.get(point=pnt)
    
  425.         c2 = City.objects.get(point__same_as=pnt)
    
  426.         c3 = City.objects.get(point__equals=pnt)
    
  427.         for c in [c1, c2, c3]:
    
  428.             self.assertEqual("Houston", c.name)
    
  429. 
    
  430.     @skipUnlessDBFeature("supports_null_geometries")
    
  431.     def test_null_geometries(self):
    
  432.         "Testing NULL geometry support, and the `isnull` lookup type."
    
  433.         # Creating a state with a NULL boundary.
    
  434.         State.objects.create(name="Puerto Rico")
    
  435. 
    
  436.         # Querying for both NULL and Non-NULL values.
    
  437.         nullqs = State.objects.filter(poly__isnull=True)
    
  438.         validqs = State.objects.filter(poly__isnull=False)
    
  439. 
    
  440.         # Puerto Rico should be NULL (it's a commonwealth unincorporated territory)
    
  441.         self.assertEqual(1, len(nullqs))
    
  442.         self.assertEqual("Puerto Rico", nullqs[0].name)
    
  443.         # GeometryField=None is an alias for __isnull=True.
    
  444.         self.assertCountEqual(State.objects.filter(poly=None), nullqs)
    
  445.         self.assertCountEqual(State.objects.exclude(poly=None), validqs)
    
  446. 
    
  447.         # The valid states should be Colorado & Kansas
    
  448.         self.assertEqual(2, len(validqs))
    
  449.         state_names = [s.name for s in validqs]
    
  450.         self.assertIn("Colorado", state_names)
    
  451.         self.assertIn("Kansas", state_names)
    
  452. 
    
  453.         # Saving another commonwealth w/a NULL geometry.
    
  454.         nmi = State.objects.create(name="Northern Mariana Islands", poly=None)
    
  455.         self.assertIsNone(nmi.poly)
    
  456. 
    
  457.         # Assigning a geometry and saving -- then UPDATE back to NULL.
    
  458.         nmi.poly = "POLYGON((0 0,1 0,1 1,1 0,0 0))"
    
  459.         nmi.save()
    
  460.         State.objects.filter(name="Northern Mariana Islands").update(poly=None)
    
  461.         self.assertIsNone(State.objects.get(name="Northern Mariana Islands").poly)
    
  462. 
    
  463.     @skipUnlessDBFeature(
    
  464.         "supports_null_geometries", "supports_crosses_lookup", "supports_relate_lookup"
    
  465.     )
    
  466.     def test_null_geometries_excluded_in_lookups(self):
    
  467.         """NULL features are excluded in spatial lookup functions."""
    
  468.         null = State.objects.create(name="NULL", poly=None)
    
  469.         queries = [
    
  470.             ("equals", Point(1, 1)),
    
  471.             ("disjoint", Point(1, 1)),
    
  472.             ("touches", Point(1, 1)),
    
  473.             ("crosses", LineString((0, 0), (1, 1), (5, 5))),
    
  474.             ("within", Point(1, 1)),
    
  475.             ("overlaps", LineString((0, 0), (1, 1), (5, 5))),
    
  476.             ("contains", LineString((0, 0), (1, 1), (5, 5))),
    
  477.             ("intersects", LineString((0, 0), (1, 1), (5, 5))),
    
  478.             ("relate", (Point(1, 1), "T*T***FF*")),
    
  479.             ("same_as", Point(1, 1)),
    
  480.             ("exact", Point(1, 1)),
    
  481.             ("coveredby", Point(1, 1)),
    
  482.             ("covers", Point(1, 1)),
    
  483.         ]
    
  484.         for lookup, geom in queries:
    
  485.             with self.subTest(lookup=lookup):
    
  486.                 self.assertNotIn(
    
  487.                     null, State.objects.filter(**{"poly__%s" % lookup: geom})
    
  488.                 )
    
  489. 
    
  490.     def test_wkt_string_in_lookup(self):
    
  491.         # Valid WKT strings don't emit error logs.
    
  492.         with self.assertNoLogs("django.contrib.gis", "ERROR"):
    
  493.             State.objects.filter(poly__intersects="LINESTRING(0 0, 1 1, 5 5)")
    
  494. 
    
  495.     @skipUnlessDBFeature("supports_relate_lookup")
    
  496.     def test_relate_lookup(self):
    
  497.         "Testing the 'relate' lookup type."
    
  498.         # To make things more interesting, we will have our Texas reference point in
    
  499.         # different SRIDs.
    
  500.         pnt1 = fromstr("POINT (649287.0363174 4177429.4494686)", srid=2847)
    
  501.         pnt2 = fromstr("POINT(-98.4919715741052 29.4333344025053)", srid=4326)
    
  502. 
    
  503.         # Not passing in a geometry as first param raises a TypeError when
    
  504.         # initializing the QuerySet.
    
  505.         with self.assertRaises(ValueError):
    
  506.             Country.objects.filter(mpoly__relate=(23, "foo"))
    
  507. 
    
  508.         # Making sure the right exception is raised for the given
    
  509.         # bad arguments.
    
  510.         for bad_args, e in [
    
  511.             ((pnt1, 0), ValueError),
    
  512.             ((pnt2, "T*T***FF*", 0), ValueError),
    
  513.         ]:
    
  514.             qs = Country.objects.filter(mpoly__relate=bad_args)
    
  515.             with self.assertRaises(e):
    
  516.                 qs.count()
    
  517. 
    
  518.         contains_mask = "T*T***FF*"
    
  519.         within_mask = "T*F**F***"
    
  520.         intersects_mask = "T********"
    
  521.         # Relate works differently on Oracle.
    
  522.         if connection.ops.oracle:
    
  523.             contains_mask = "contains"
    
  524.             within_mask = "inside"
    
  525.             # TODO: This is not quite the same as the PostGIS mask above
    
  526.             intersects_mask = "overlapbdyintersect"
    
  527. 
    
  528.         # Testing contains relation mask.
    
  529.         if connection.features.supports_transform:
    
  530.             self.assertEqual(
    
  531.                 Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name,
    
  532.                 "Texas",
    
  533.             )
    
  534.         self.assertEqual(
    
  535.             "Texas", Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name
    
  536.         )
    
  537. 
    
  538.         # Testing within relation mask.
    
  539.         ks = State.objects.get(name="Kansas")
    
  540.         self.assertEqual(
    
  541.             "Lawrence", City.objects.get(point__relate=(ks.poly, within_mask)).name
    
  542.         )
    
  543. 
    
  544.         # Testing intersection relation mask.
    
  545.         if not connection.ops.oracle:
    
  546.             if connection.features.supports_transform:
    
  547.                 self.assertEqual(
    
  548.                     Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name,
    
  549.                     "Texas",
    
  550.                 )
    
  551.             self.assertEqual(
    
  552.                 "Texas", Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name
    
  553.             )
    
  554.             self.assertEqual(
    
  555.                 "Lawrence",
    
  556.                 City.objects.get(point__relate=(ks.poly, intersects_mask)).name,
    
  557.             )
    
  558. 
    
  559.         # With a complex geometry expression
    
  560.         mask = "anyinteract" if connection.ops.oracle else within_mask
    
  561.         self.assertFalse(
    
  562.             City.objects.exclude(
    
  563.                 point__relate=(functions.Union("point", "point"), mask)
    
  564.             )
    
  565.         )
    
  566. 
    
  567.     def test_gis_lookups_with_complex_expressions(self):
    
  568.         multiple_arg_lookups = {
    
  569.             "dwithin",
    
  570.             "relate",
    
  571.         }  # These lookups are tested elsewhere.
    
  572.         lookups = connection.ops.gis_operators.keys() - multiple_arg_lookups
    
  573.         self.assertTrue(lookups, "No lookups found")
    
  574.         for lookup in lookups:
    
  575.             with self.subTest(lookup):
    
  576.                 City.objects.filter(
    
  577.                     **{"point__" + lookup: functions.Union("point", "point")}
    
  578.                 ).exists()
    
  579. 
    
  580.     def test_subquery_annotation(self):
    
  581.         multifields = MultiFields.objects.create(
    
  582.             city=City.objects.create(point=Point(1, 1)),
    
  583.             point=Point(2, 2),
    
  584.             poly=Polygon.from_bbox((0, 0, 2, 2)),
    
  585.         )
    
  586.         qs = MultiFields.objects.annotate(
    
  587.             city_point=Subquery(
    
  588.                 City.objects.filter(
    
  589.                     id=OuterRef("city"),
    
  590.                 ).values("point")
    
  591.             ),
    
  592.         ).filter(
    
  593.             city_point__within=F("poly"),
    
  594.         )
    
  595.         self.assertEqual(qs.get(), multifields)
    
  596. 
    
  597. 
    
  598. class GeoQuerySetTest(TestCase):
    
  599.     # TODO: GeoQuerySet is removed, organize these test better.
    
  600.     fixtures = ["initial"]
    
  601. 
    
  602.     @skipUnlessDBFeature("supports_extent_aggr")
    
  603.     def test_extent(self):
    
  604.         """
    
  605.         Testing the `Extent` aggregate.
    
  606.         """
    
  607.         # Reference query:
    
  608.         #  SELECT ST_extent(point)
    
  609.         #  FROM geoapp_city
    
  610.         #  WHERE (name='Houston' or name='Dallas');`
    
  611.         #  => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203)
    
  612.         expected = (
    
  613.             -96.8016128540039,
    
  614.             29.7633724212646,
    
  615.             -95.3631439208984,
    
  616.             32.782058715820,
    
  617.         )
    
  618. 
    
  619.         qs = City.objects.filter(name__in=("Houston", "Dallas"))
    
  620.         extent = qs.aggregate(Extent("point"))["point__extent"]
    
  621.         for val, exp in zip(extent, expected):
    
  622.             self.assertAlmostEqual(exp, val, 4)
    
  623.         self.assertIsNone(
    
  624.             City.objects.filter(name=("Smalltown")).aggregate(Extent("point"))[
    
  625.                 "point__extent"
    
  626.             ]
    
  627.         )
    
  628. 
    
  629.     @skipUnlessDBFeature("supports_extent_aggr")
    
  630.     def test_extent_with_limit(self):
    
  631.         """
    
  632.         Testing if extent supports limit.
    
  633.         """
    
  634.         extent1 = City.objects.aggregate(Extent("point"))["point__extent"]
    
  635.         extent2 = City.objects.all()[:3].aggregate(Extent("point"))["point__extent"]
    
  636.         self.assertNotEqual(extent1, extent2)
    
  637. 
    
  638.     def test_make_line(self):
    
  639.         """
    
  640.         Testing the `MakeLine` aggregate.
    
  641.         """
    
  642.         if not connection.features.supports_make_line_aggr:
    
  643.             with self.assertRaises(NotSupportedError):
    
  644.                 City.objects.aggregate(MakeLine("point"))
    
  645.             return
    
  646. 
    
  647.         # MakeLine on an inappropriate field returns simply None
    
  648.         self.assertIsNone(State.objects.aggregate(MakeLine("poly"))["poly__makeline"])
    
  649.         # Reference query:
    
  650.         # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city;
    
  651.         ref_line = GEOSGeometry(
    
  652.             "LINESTRING(-95.363151 29.763374,-96.801611 32.782057,"
    
  653.             "-97.521157 34.464642,174.783117 -41.315268,-104.609252 38.255001,"
    
  654.             "-95.23506 38.971823,-87.650175 41.850385,-123.305196 48.462611)",
    
  655.             srid=4326,
    
  656.         )
    
  657.         # We check for equality with a tolerance of 10e-5 which is a lower bound
    
  658.         # of the precisions of ref_line coordinates
    
  659.         line = City.objects.aggregate(MakeLine("point"))["point__makeline"]
    
  660.         self.assertTrue(
    
  661.             ref_line.equals_exact(line, tolerance=10e-5), "%s != %s" % (ref_line, line)
    
  662.         )
    
  663. 
    
  664.     @skipUnlessDBFeature("supports_union_aggr")
    
  665.     def test_unionagg(self):
    
  666.         """
    
  667.         Testing the `Union` aggregate.
    
  668.         """
    
  669.         tx = Country.objects.get(name="Texas").mpoly
    
  670.         # Houston, Dallas -- Ordering may differ depending on backend or GEOS version.
    
  671.         union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)")
    
  672.         qs = City.objects.filter(point__within=tx)
    
  673.         with self.assertRaises(ValueError):
    
  674.             qs.aggregate(Union("name"))
    
  675.         # Using `field_name` keyword argument in one query and specifying an
    
  676.         # order in the other (which should not be used because this is
    
  677.         # an aggregate method on a spatial column)
    
  678.         u1 = qs.aggregate(Union("point"))["point__union"]
    
  679.         u2 = qs.order_by("name").aggregate(Union("point"))["point__union"]
    
  680.         self.assertTrue(union.equals(u1))
    
  681.         self.assertTrue(union.equals(u2))
    
  682.         qs = City.objects.filter(name="NotACity")
    
  683.         self.assertIsNone(qs.aggregate(Union("point"))["point__union"])
    
  684. 
    
  685.     @skipUnlessDBFeature("supports_union_aggr")
    
  686.     def test_geoagg_subquery(self):
    
  687.         tx = Country.objects.get(name="Texas")
    
  688.         union = GEOSGeometry("MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)")
    
  689.         # Use distinct() to force the usage of a subquery for aggregation.
    
  690.         with CaptureQueriesContext(connection) as ctx:
    
  691.             self.assertIs(
    
  692.                 union.equals(
    
  693.                     City.objects.filter(point__within=tx.mpoly)
    
  694.                     .distinct()
    
  695.                     .aggregate(
    
  696.                         Union("point"),
    
  697.                     )["point__union"],
    
  698.                 ),
    
  699.                 True,
    
  700.             )
    
  701.         self.assertIn("subquery", ctx.captured_queries[0]["sql"])
    
  702. 
    
  703.     @skipUnlessDBFeature("supports_tolerance_parameter")
    
  704.     def test_unionagg_tolerance(self):
    
  705.         City.objects.create(
    
  706.             point=fromstr("POINT(-96.467222 32.751389)", srid=4326),
    
  707.             name="Forney",
    
  708.         )
    
  709.         tx = Country.objects.get(name="Texas").mpoly
    
  710.         # Tolerance is greater than distance between Forney and Dallas, that's
    
  711.         # why Dallas is ignored.
    
  712.         forney_houston = GEOSGeometry(
    
  713.             "MULTIPOINT(-95.363151 29.763374, -96.467222 32.751389)",
    
  714.             srid=4326,
    
  715.         )
    
  716.         self.assertIs(
    
  717.             forney_houston.equals_exact(
    
  718.                 City.objects.filter(point__within=tx).aggregate(
    
  719.                     Union("point", tolerance=32000),
    
  720.                 )["point__union"],
    
  721.                 tolerance=10e-6,
    
  722.             ),
    
  723.             True,
    
  724.         )
    
  725. 
    
  726.     @skipUnlessDBFeature("supports_tolerance_parameter")
    
  727.     def test_unionagg_tolerance_escaping(self):
    
  728.         tx = Country.objects.get(name="Texas").mpoly
    
  729.         with self.assertRaises(DatabaseError):
    
  730.             City.objects.filter(point__within=tx).aggregate(
    
  731.                 Union("point", tolerance="0.05))), (((1"),
    
  732.             )
    
  733. 
    
  734.     def test_within_subquery(self):
    
  735.         """
    
  736.         Using a queryset inside a geo lookup is working (using a subquery)
    
  737.         (#14483).
    
  738.         """
    
  739.         tex_cities = City.objects.filter(
    
  740.             point__within=Country.objects.filter(name="Texas").values("mpoly")
    
  741.         ).order_by("name")
    
  742.         self.assertEqual(
    
  743.             list(tex_cities.values_list("name", flat=True)), ["Dallas", "Houston"]
    
  744.         )
    
  745. 
    
  746.     def test_non_concrete_field(self):
    
  747.         NonConcreteModel.objects.create(point=Point(0, 0), name="name")
    
  748.         list(NonConcreteModel.objects.all())
    
  749. 
    
  750.     def test_values_srid(self):
    
  751.         for c, v in zip(City.objects.all(), City.objects.values()):
    
  752.             self.assertEqual(c.point.srid, v["point"].srid)