tests.py 23 KB

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