tests.py 23 KB

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