tests.py 28 KB

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