tests.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. from __future__ import unicode_literals
  2. import re
  3. import tempfile
  4. from django.contrib.gis import gdal
  5. from django.contrib.gis.db.models import Extent, MakeLine, Union
  6. from django.contrib.gis.geos import (
  7. GeometryCollection, GEOSGeometry, LinearRing, LineString, Point, Polygon,
  8. fromstr,
  9. )
  10. from django.core.management import call_command
  11. from django.db import connection
  12. from django.test import TestCase, ignore_warnings, skipUnlessDBFeature
  13. from django.utils import six
  14. from django.utils.deprecation import (
  15. RemovedInDjango20Warning, RemovedInDjango110Warning,
  16. )
  17. from ..utils import no_oracle, oracle, postgis, spatialite
  18. from .models import (
  19. City, Country, Feature, MinusOneSRID, NonConcreteModel, PennsylvaniaCity,
  20. State, Track,
  21. )
  22. def postgis_bug_version():
  23. spatial_version = getattr(connection.ops, "spatial_version", (0, 0, 0))
  24. return spatial_version and (2, 0, 0) <= spatial_version <= (2, 0, 1)
  25. @skipUnlessDBFeature("gis_enabled")
  26. class GeoModelTest(TestCase):
  27. fixtures = ['initial']
  28. def test_fixtures(self):
  29. "Testing geographic model initialization from fixtures."
  30. # Ensuring that data was loaded from initial data fixtures.
  31. self.assertEqual(2, Country.objects.count())
  32. self.assertEqual(8, City.objects.count())
  33. self.assertEqual(2, State.objects.count())
  34. def test_proxy(self):
  35. "Testing Lazy-Geometry support (using the GeometryProxy)."
  36. # Testing on a Point
  37. pnt = Point(0, 0)
  38. nullcity = City(name='NullCity', point=pnt)
  39. nullcity.save()
  40. # Making sure TypeError is thrown when trying to set with an
  41. # incompatible type.
  42. for bad in [5, 2.0, LineString((0, 0), (1, 1))]:
  43. try:
  44. nullcity.point = bad
  45. except TypeError:
  46. pass
  47. else:
  48. self.fail('Should throw a TypeError')
  49. # Now setting with a compatible GEOS Geometry, saving, and ensuring
  50. # the save took, notice no SRID is explicitly set.
  51. new = Point(5, 23)
  52. nullcity.point = new
  53. # Ensuring that the SRID is automatically set to that of the
  54. # field after assignment, but before saving.
  55. self.assertEqual(4326, nullcity.point.srid)
  56. nullcity.save()
  57. # Ensuring the point was saved correctly after saving
  58. self.assertEqual(new, City.objects.get(name='NullCity').point)
  59. # Setting the X and Y of the Point
  60. nullcity.point.x = 23
  61. nullcity.point.y = 5
  62. # Checking assignments pre & post-save.
  63. self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point)
  64. nullcity.save()
  65. self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point)
  66. nullcity.delete()
  67. # Testing on a Polygon
  68. shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0))
  69. inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40))
  70. # Creating a State object using a built Polygon
  71. ply = Polygon(shell, inner)
  72. nullstate = State(name='NullState', poly=ply)
  73. self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None
  74. nullstate.save()
  75. ns = State.objects.get(name='NullState')
  76. self.assertEqual(ply, ns.poly)
  77. # Testing the `ogr` and `srs` lazy-geometry properties.
  78. if gdal.HAS_GDAL:
  79. self.assertIsInstance(ns.poly.ogr, gdal.OGRGeometry)
  80. self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb)
  81. self.assertIsInstance(ns.poly.srs, gdal.SpatialReference)
  82. self.assertEqual('WGS 84', ns.poly.srs.name)
  83. # Changing the interior ring on the poly attribute.
  84. new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30))
  85. ns.poly[1] = new_inner
  86. ply[1] = new_inner
  87. self.assertEqual(4326, ns.poly.srid)
  88. ns.save()
  89. self.assertEqual(ply, State.objects.get(name='NullState').poly)
  90. ns.delete()
  91. @skipUnlessDBFeature("supports_transform")
  92. def test_lookup_insert_transform(self):
  93. "Testing automatic transform for lookups and inserts."
  94. # San Antonio in 'WGS84' (SRID 4326)
  95. sa_4326 = 'POINT (-98.493183 29.424170)'
  96. wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84
  97. # Oracle doesn't have SRID 3084, using 41157.
  98. if oracle:
  99. # San Antonio in 'Texas 4205, Southern Zone (1983, meters)' (SRID 41157)
  100. # Used the following Oracle SQL to get this value:
  101. # SELECT SDO_UTIL.TO_WKTGEOMETRY(
  102. # SDO_CS.TRANSFORM(SDO_GEOMETRY('POINT (-98.493183 29.424170)', 4326), 41157))
  103. # )
  104. # FROM DUAL;
  105. nad_wkt = 'POINT (300662.034646583 5416427.45974934)'
  106. nad_srid = 41157
  107. else:
  108. # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084)
  109. # Used ogr.py in gdal 1.4.1 for this transform
  110. nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)'
  111. nad_srid = 3084
  112. # Constructing & querying with a point from a different SRID. Oracle
  113. # `SDO_OVERLAPBDYINTERSECT` operates differently from
  114. # `ST_Intersects`, so contains is used instead.
  115. nad_pnt = fromstr(nad_wkt, srid=nad_srid)
  116. if oracle:
  117. tx = Country.objects.get(mpoly__contains=nad_pnt)
  118. else:
  119. tx = Country.objects.get(mpoly__intersects=nad_pnt)
  120. self.assertEqual('Texas', tx.name)
  121. # Creating San Antonio. Remember the Alamo.
  122. sa = City.objects.create(name='San Antonio', point=nad_pnt)
  123. # Now verifying that San Antonio was transformed correctly
  124. sa = City.objects.get(name='San Antonio')
  125. self.assertAlmostEqual(wgs_pnt.x, sa.point.x, 6)
  126. self.assertAlmostEqual(wgs_pnt.y, sa.point.y, 6)
  127. # If the GeometryField SRID is -1, then we shouldn't perform any
  128. # transformation if the SRID of the input geometry is different.
  129. if spatialite and connection.ops.spatial_version < (3, 0, 0):
  130. # SpatiaLite < 3 does not support missing SRID values.
  131. return
  132. m1 = MinusOneSRID(geom=Point(17, 23, srid=4326))
  133. m1.save()
  134. self.assertEqual(-1, m1.geom.srid)
  135. def test_createnull(self):
  136. "Testing creating a model instance and the geometry being None"
  137. c = City()
  138. self.assertEqual(c.point, None)
  139. def test_geometryfield(self):
  140. "Testing the general GeometryField."
  141. Feature(name='Point', geom=Point(1, 1)).save()
  142. Feature(name='LineString', geom=LineString((0, 0), (1, 1), (5, 5))).save()
  143. Feature(name='Polygon', geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0)))).save()
  144. Feature(name='GeometryCollection',
  145. geom=GeometryCollection(Point(2, 2), LineString((0, 0), (2, 2)),
  146. Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))))).save()
  147. f_1 = Feature.objects.get(name='Point')
  148. self.assertIsInstance(f_1.geom, Point)
  149. self.assertEqual((1.0, 1.0), f_1.geom.tuple)
  150. f_2 = Feature.objects.get(name='LineString')
  151. self.assertIsInstance(f_2.geom, LineString)
  152. self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple)
  153. f_3 = Feature.objects.get(name='Polygon')
  154. self.assertIsInstance(f_3.geom, Polygon)
  155. f_4 = Feature.objects.get(name='GeometryCollection')
  156. self.assertIsInstance(f_4.geom, GeometryCollection)
  157. self.assertEqual(f_3.geom, f_4.geom[2])
  158. @skipUnlessDBFeature("supports_transform")
  159. def test_inherited_geofields(self):
  160. "Test GeoQuerySet methods on inherited Geometry fields."
  161. # Creating a Pennsylvanian city.
  162. PennsylvaniaCity.objects.create(name='Mansfield', county='Tioga', point='POINT(-77.071445 41.823881)')
  163. # All transformation SQL will need to be performed on the
  164. # _parent_ table.
  165. qs = PennsylvaniaCity.objects.transform(32128)
  166. self.assertEqual(1, qs.count())
  167. for pc in qs:
  168. self.assertEqual(32128, pc.point.srid)
  169. def test_raw_sql_query(self):
  170. "Testing raw SQL query."
  171. cities1 = City.objects.all()
  172. # Only PostGIS would support a 'select *' query because of its recognized
  173. # HEXEWKB format for geometry fields
  174. as_text = 'ST_AsText(%s)' if postgis else connection.ops.select
  175. cities2 = City.objects.raw(
  176. 'select id, name, %s from geoapp_city' % as_text % 'point'
  177. )
  178. self.assertEqual(len(cities1), len(list(cities2)))
  179. self.assertIsInstance(cities2[0].point, Point)
  180. def test_dumpdata_loaddata_cycle(self):
  181. """
  182. Test a dumpdata/loaddata cycle with geographic data.
  183. """
  184. out = six.StringIO()
  185. original_data = list(City.objects.all().order_by('name'))
  186. call_command('dumpdata', 'geoapp.City', stdout=out)
  187. result = out.getvalue()
  188. houston = City.objects.get(name='Houston')
  189. self.assertIn('"point": "%s"' % houston.point.ewkt, result)
  190. # Reload now dumped data
  191. with tempfile.NamedTemporaryFile(mode='w', suffix='.json') as tmp:
  192. tmp.write(result)
  193. tmp.seek(0)
  194. call_command('loaddata', tmp.name, verbosity=0)
  195. self.assertListEqual(original_data, list(City.objects.all().order_by('name')))
  196. @skipUnlessDBFeature("gis_enabled")
  197. class GeoLookupTest(TestCase):
  198. fixtures = ['initial']
  199. def test_disjoint_lookup(self):
  200. "Testing the `disjoint` lookup type."
  201. ptown = City.objects.get(name='Pueblo')
  202. qs1 = City.objects.filter(point__disjoint=ptown.point)
  203. self.assertEqual(7, qs1.count())
  204. if connection.features.supports_real_shape_operations:
  205. qs2 = State.objects.filter(poly__disjoint=ptown.point)
  206. self.assertEqual(1, qs2.count())
  207. self.assertEqual('Kansas', qs2[0].name)
  208. def test_contains_contained_lookups(self):
  209. "Testing the 'contained', 'contains', and 'bbcontains' lookup types."
  210. # Getting Texas, yes we were a country -- once ;)
  211. texas = Country.objects.get(name='Texas')
  212. # Seeing what cities are in Texas, should get Houston and Dallas,
  213. # and Oklahoma City because 'contained' only checks on the
  214. # _bounding box_ of the Geometries.
  215. if connection.features.supports_contained_lookup:
  216. qs = City.objects.filter(point__contained=texas.mpoly)
  217. self.assertEqual(3, qs.count())
  218. cities = ['Houston', 'Dallas', 'Oklahoma City']
  219. for c in qs:
  220. self.assertIn(c.name, cities)
  221. # Pulling out some cities.
  222. houston = City.objects.get(name='Houston')
  223. wellington = City.objects.get(name='Wellington')
  224. pueblo = City.objects.get(name='Pueblo')
  225. okcity = City.objects.get(name='Oklahoma City')
  226. lawrence = City.objects.get(name='Lawrence')
  227. # Now testing contains on the countries using the points for
  228. # Houston and Wellington.
  229. tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry
  230. nz = Country.objects.get(mpoly__contains=wellington.point.hex) # Query w/EWKBHEX
  231. self.assertEqual('Texas', tx.name)
  232. self.assertEqual('New Zealand', nz.name)
  233. # Spatialite 2.3 thinks that Lawrence is in Puerto Rico (a NULL geometry).
  234. if not (spatialite and connection.ops.spatial_version < (3, 0, 0)):
  235. ks = State.objects.get(poly__contains=lawrence.point)
  236. self.assertEqual('Kansas', ks.name)
  237. # Pueblo and Oklahoma City (even though OK City is within the bounding box of Texas)
  238. # are not contained in Texas or New Zealand.
  239. self.assertEqual(len(Country.objects.filter(mpoly__contains=pueblo.point)), 0) # Query w/GEOSGeometry object
  240. self.assertEqual(len(Country.objects.filter(mpoly__contains=okcity.point.wkt)),
  241. 0 if connection.features.supports_real_shape_operations else 1) # Query w/WKT
  242. # OK City is contained w/in bounding box of Texas.
  243. if connection.features.supports_bbcontains_lookup:
  244. qs = Country.objects.filter(mpoly__bbcontains=okcity.point)
  245. self.assertEqual(1, len(qs))
  246. self.assertEqual('Texas', qs[0].name)
  247. @skipUnlessDBFeature("supports_crosses_lookup")
  248. def test_crosses_lookup(self):
  249. Track.objects.create(
  250. name='Line1',
  251. line=LineString([(-95, 29), (-60, 0)])
  252. )
  253. self.assertEqual(
  254. Track.objects.filter(line__crosses=LineString([(-95, 0), (-60, 29)])).count(),
  255. 1
  256. )
  257. self.assertEqual(
  258. Track.objects.filter(line__crosses=LineString([(-95, 30), (0, 30)])).count(),
  259. 0
  260. )
  261. @skipUnlessDBFeature("supports_left_right_lookups")
  262. def test_left_right_lookups(self):
  263. "Testing the 'left' and 'right' lookup types."
  264. # Left: A << B => true if xmax(A) < xmin(B)
  265. # Right: A >> B => true if xmin(A) > xmax(B)
  266. # See: BOX2D_left() and BOX2D_right() in lwgeom_box2dfloat4.c in PostGIS source.
  267. # The left/right lookup tests are known failures on PostGIS 2.0/2.0.1
  268. # http://trac.osgeo.org/postgis/ticket/2035
  269. if postgis_bug_version():
  270. self.skipTest("PostGIS 2.0/2.0.1 left and right lookups are known to be buggy.")
  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. def test_equals_lookups(self):
  299. "Testing the 'same_as' and 'equals' lookup types."
  300. pnt = fromstr('POINT (-95.363151 29.763374)', srid=4326)
  301. c1 = City.objects.get(point=pnt)
  302. c2 = City.objects.get(point__same_as=pnt)
  303. c3 = City.objects.get(point__equals=pnt)
  304. for c in [c1, c2, c3]:
  305. self.assertEqual('Houston', c.name)
  306. @skipUnlessDBFeature("supports_null_geometries")
  307. def test_null_geometries(self):
  308. "Testing NULL geometry support, and the `isnull` lookup type."
  309. # Creating a state with a NULL boundary.
  310. State.objects.create(name='Puerto Rico')
  311. # Querying for both NULL and Non-NULL values.
  312. nullqs = State.objects.filter(poly__isnull=True)
  313. validqs = State.objects.filter(poly__isnull=False)
  314. # Puerto Rico should be NULL (it's a commonwealth unincorporated territory)
  315. self.assertEqual(1, len(nullqs))
  316. self.assertEqual('Puerto Rico', nullqs[0].name)
  317. # The valid states should be Colorado & Kansas
  318. self.assertEqual(2, len(validqs))
  319. state_names = [s.name for s in validqs]
  320. self.assertIn('Colorado', state_names)
  321. self.assertIn('Kansas', state_names)
  322. # Saving another commonwealth w/a NULL geometry.
  323. nmi = State.objects.create(name='Northern Mariana Islands', poly=None)
  324. self.assertEqual(nmi.poly, None)
  325. # Assigning a geometry and saving -- then UPDATE back to NULL.
  326. nmi.poly = 'POLYGON((0 0,1 0,1 1,1 0,0 0))'
  327. nmi.save()
  328. State.objects.filter(name='Northern Mariana Islands').update(poly=None)
  329. self.assertIsNone(State.objects.get(name='Northern Mariana Islands').poly)
  330. @skipUnlessDBFeature("supports_relate_lookup")
  331. def test_relate_lookup(self):
  332. "Testing the 'relate' lookup type."
  333. # To make things more interesting, we will have our Texas reference point in
  334. # different SRIDs.
  335. pnt1 = fromstr('POINT (649287.0363174 4177429.4494686)', srid=2847)
  336. pnt2 = fromstr('POINT(-98.4919715741052 29.4333344025053)', srid=4326)
  337. # Not passing in a geometry as first param should
  338. # raise a type error when initializing the GeoQuerySet
  339. self.assertRaises(ValueError, Country.objects.filter, mpoly__relate=(23, 'foo'))
  340. # Making sure the right exception is raised for the given
  341. # bad arguments.
  342. for bad_args, e in [((pnt1, 0), ValueError), ((pnt2, 'T*T***FF*', 0), ValueError)]:
  343. qs = Country.objects.filter(mpoly__relate=bad_args)
  344. self.assertRaises(e, qs.count)
  345. # Relate works differently for the different backends.
  346. if postgis or spatialite:
  347. contains_mask = 'T*T***FF*'
  348. within_mask = 'T*F**F***'
  349. intersects_mask = 'T********'
  350. elif oracle:
  351. contains_mask = 'contains'
  352. within_mask = 'inside'
  353. # TODO: This is not quite the same as the PostGIS mask above
  354. intersects_mask = 'overlapbdyintersect'
  355. # Testing contains relation mask.
  356. self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, contains_mask)).name)
  357. self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, contains_mask)).name)
  358. # Testing within relation mask.
  359. ks = State.objects.get(name='Kansas')
  360. self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, within_mask)).name)
  361. # Testing intersection relation mask.
  362. if not oracle:
  363. self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt1, intersects_mask)).name)
  364. self.assertEqual('Texas', Country.objects.get(mpoly__relate=(pnt2, intersects_mask)).name)
  365. self.assertEqual('Lawrence', City.objects.get(point__relate=(ks.poly, intersects_mask)).name)
  366. @skipUnlessDBFeature("gis_enabled")
  367. @ignore_warnings(category=RemovedInDjango20Warning)
  368. class GeoQuerySetTest(TestCase):
  369. fixtures = ['initial']
  370. # Please keep the tests in GeoQuerySet method's alphabetic order
  371. @skipUnlessDBFeature("has_centroid_method")
  372. def test_centroid(self):
  373. "Testing the `centroid` GeoQuerySet method."
  374. qs = State.objects.exclude(poly__isnull=True).centroid()
  375. if oracle:
  376. tol = 0.1
  377. elif spatialite:
  378. tol = 0.000001
  379. else:
  380. tol = 0.000000001
  381. for s in qs:
  382. self.assertTrue(s.poly.centroid.equals_exact(s.centroid, tol))
  383. @skipUnlessDBFeature(
  384. "has_difference_method", "has_intersection_method",
  385. "has_sym_difference_method", "has_union_method")
  386. def test_diff_intersection_union(self):
  387. "Testing the `difference`, `intersection`, `sym_difference`, and `union` GeoQuerySet methods."
  388. geom = Point(5, 23)
  389. qs = Country.objects.all().difference(geom).sym_difference(geom).union(geom)
  390. # XXX For some reason SpatiaLite does something screwy with the Texas geometry here. Also,
  391. # XXX it doesn't like the null intersection.
  392. if spatialite:
  393. qs = qs.exclude(name='Texas')
  394. else:
  395. qs = qs.intersection(geom)
  396. for c in qs:
  397. if oracle:
  398. # Should be able to execute the queries; however, they won't be the same
  399. # as GEOS (because Oracle doesn't use GEOS internally like PostGIS or
  400. # SpatiaLite).
  401. pass
  402. else:
  403. self.assertEqual(c.mpoly.difference(geom), c.difference)
  404. if not spatialite:
  405. self.assertEqual(c.mpoly.intersection(geom), c.intersection)
  406. # Ordering might differ in collections
  407. self.assertSetEqual(set(g.wkt for g in c.mpoly.sym_difference(geom)),
  408. set(g.wkt for g in c.sym_difference))
  409. self.assertSetEqual(set(g.wkt for g in c.mpoly.union(geom)),
  410. set(g.wkt for g in c.union))
  411. @skipUnlessDBFeature("has_envelope_method")
  412. def test_envelope(self):
  413. "Testing the `envelope` GeoQuerySet method."
  414. countries = Country.objects.all().envelope()
  415. for country in countries:
  416. self.assertIsInstance(country.envelope, Polygon)
  417. @skipUnlessDBFeature("supports_extent_aggr")
  418. @ignore_warnings(category=RemovedInDjango110Warning)
  419. def test_extent(self):
  420. """
  421. Testing the (deprecated) `extent` GeoQuerySet method and the Extent
  422. aggregate.
  423. """
  424. # Reference query:
  425. # `SELECT ST_extent(point) FROM geoapp_city WHERE (name='Houston' or name='Dallas');`
  426. # => BOX(-96.8016128540039 29.7633724212646,-95.3631439208984 32.7820587158203)
  427. expected = (-96.8016128540039, 29.7633724212646, -95.3631439208984, 32.782058715820)
  428. qs = City.objects.filter(name__in=('Houston', 'Dallas'))
  429. extent1 = qs.extent()
  430. extent2 = qs.aggregate(Extent('point'))['point__extent']
  431. for extent in (extent1, extent2):
  432. for val, exp in zip(extent, expected):
  433. self.assertAlmostEqual(exp, val, 4)
  434. self.assertIsNone(City.objects.filter(name=('Smalltown')).extent())
  435. self.assertIsNone(City.objects.filter(name=('Smalltown')).aggregate(Extent('point'))['point__extent'])
  436. @skipUnlessDBFeature("supports_extent_aggr")
  437. def test_extent_with_limit(self):
  438. """
  439. Testing if extent supports limit.
  440. """
  441. extent1 = City.objects.all().aggregate(Extent('point'))['point__extent']
  442. extent2 = City.objects.all()[:3].aggregate(Extent('point'))['point__extent']
  443. self.assertNotEqual(extent1, extent2)
  444. @skipUnlessDBFeature("has_force_rhr_method")
  445. def test_force_rhr(self):
  446. "Testing GeoQuerySet.force_rhr()."
  447. rings = (
  448. ((0, 0), (5, 0), (0, 5), (0, 0)),
  449. ((1, 1), (1, 3), (3, 1), (1, 1)),
  450. )
  451. rhr_rings = (
  452. ((0, 0), (0, 5), (5, 0), (0, 0)),
  453. ((1, 1), (3, 1), (1, 3), (1, 1)),
  454. )
  455. State.objects.create(name='Foo', poly=Polygon(*rings))
  456. s = State.objects.force_rhr().get(name='Foo')
  457. self.assertEqual(rhr_rings, s.force_rhr.coords)
  458. @skipUnlessDBFeature("has_geohash_method")
  459. def test_geohash(self):
  460. "Testing GeoQuerySet.geohash()."
  461. # Reference query:
  462. # SELECT ST_GeoHash(point) FROM geoapp_city WHERE name='Houston';
  463. # SELECT ST_GeoHash(point, 5) FROM geoapp_city WHERE name='Houston';
  464. ref_hash = '9vk1mfq8jx0c8e0386z6'
  465. h1 = City.objects.geohash().get(name='Houston')
  466. h2 = City.objects.geohash(precision=5).get(name='Houston')
  467. self.assertEqual(ref_hash, h1.geohash)
  468. self.assertEqual(ref_hash[:5], h2.geohash)
  469. def test_geojson(self):
  470. "Testing GeoJSON output from the database using GeoQuerySet.geojson()."
  471. # Only PostGIS and SpatiaLite 3.0+ support GeoJSON.
  472. if not connection.ops.geojson:
  473. self.assertRaises(NotImplementedError, Country.objects.all().geojson, field_name='mpoly')
  474. return
  475. pueblo_json = '{"type":"Point","coordinates":[-104.609252,38.255001]}'
  476. houston_json = (
  477. '{"type":"Point","crs":{"type":"name","properties":'
  478. '{"name":"EPSG:4326"}},"coordinates":[-95.363151,29.763374]}'
  479. )
  480. victoria_json = (
  481. '{"type":"Point","bbox":[-123.30519600,48.46261100,-123.30519600,48.46261100],'
  482. '"coordinates":[-123.305196,48.462611]}'
  483. )
  484. chicago_json = (
  485. '{"type":"Point","crs":{"type":"name","properties":{"name":"EPSG:4326"}},'
  486. '"bbox":[-87.65018,41.85039,-87.65018,41.85039],"coordinates":[-87.65018,41.85039]}'
  487. )
  488. if spatialite:
  489. victoria_json = (
  490. '{"type":"Point","bbox":[-123.305196,48.462611,-123.305196,48.462611],'
  491. '"coordinates":[-123.305196,48.462611]}'
  492. )
  493. # Precision argument should only be an integer
  494. self.assertRaises(TypeError, City.objects.geojson, precision='foo')
  495. # Reference queries and values.
  496. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 0)
  497. # FROM "geoapp_city" WHERE "geoapp_city"."name" = 'Pueblo';
  498. self.assertEqual(pueblo_json, City.objects.geojson().get(name='Pueblo').geojson)
  499. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 2) FROM "geoapp_city"
  500. # WHERE "geoapp_city"."name" = 'Houston';
  501. # This time we want to include the CRS by using the `crs` keyword.
  502. self.assertEqual(houston_json, City.objects.geojson(crs=True, model_att='json').get(name='Houston').json)
  503. # SELECT ST_AsGeoJson("geoapp_city"."point", 8, 1) FROM "geoapp_city"
  504. # WHERE "geoapp_city"."name" = 'Houston';
  505. # This time we include the bounding box by using the `bbox` keyword.
  506. self.assertEqual(victoria_json, City.objects.geojson(bbox=True).get(name='Victoria').geojson)
  507. # SELECT ST_AsGeoJson("geoapp_city"."point", 5, 3) FROM "geoapp_city"
  508. # WHERE "geoapp_city"."name" = 'Chicago';
  509. # Finally, we set every available keyword.
  510. self.assertEqual(
  511. chicago_json,
  512. City.objects.geojson(bbox=True, crs=True, precision=5).get(name='Chicago').geojson
  513. )
  514. @skipUnlessDBFeature("has_gml_method")
  515. def test_gml(self):
  516. "Testing GML output from the database using GeoQuerySet.gml()."
  517. # Should throw a TypeError when trying to obtain GML from a
  518. # non-geometry field.
  519. qs = City.objects.all()
  520. self.assertRaises(TypeError, qs.gml, field_name='name')
  521. ptown1 = City.objects.gml(field_name='point', precision=9).get(name='Pueblo')
  522. ptown2 = City.objects.gml(precision=9).get(name='Pueblo')
  523. if oracle:
  524. # No precision parameter for Oracle :-/
  525. gml_regex = re.compile(
  526. r'^<gml:Point srsName="SDO:4326" xmlns:gml="http://www.opengis.net/gml">'
  527. r'<gml:coordinates decimal="\." cs="," ts=" ">-104.60925\d+,38.25500\d+ '
  528. r'</gml:coordinates></gml:Point>'
  529. )
  530. elif spatialite and connection.ops.spatial_version < (3, 0, 0):
  531. # Spatialite before 3.0 has extra colon in SrsName
  532. gml_regex = re.compile(
  533. r'^<gml:Point SrsName="EPSG::4326"><gml:coordinates decimal="\." '
  534. r'cs="," ts=" ">-104.609251\d+,38.255001</gml:coordinates></gml:Point>'
  535. )
  536. else:
  537. gml_regex = re.compile(
  538. r'^<gml:Point srsName="EPSG:4326"><gml:coordinates>'
  539. r'-104\.60925\d+,38\.255001</gml:coordinates></gml:Point>'
  540. )
  541. for ptown in [ptown1, ptown2]:
  542. self.assertTrue(gml_regex.match(ptown.gml))
  543. if postgis:
  544. self.assertIn('<gml:pos srsDimension="2">', City.objects.gml(version=3).get(name='Pueblo').gml)
  545. @skipUnlessDBFeature("has_kml_method")
  546. def test_kml(self):
  547. "Testing KML output from the database using GeoQuerySet.kml()."
  548. # Should throw a TypeError when trying to obtain KML from a
  549. # non-geometry field.
  550. qs = City.objects.all()
  551. self.assertRaises(TypeError, qs.kml, 'name')
  552. # Ensuring the KML is as expected.
  553. ptown1 = City.objects.kml(field_name='point', precision=9).get(name='Pueblo')
  554. ptown2 = City.objects.kml(precision=9).get(name='Pueblo')
  555. for ptown in [ptown1, ptown2]:
  556. self.assertEqual('<Point><coordinates>-104.609252,38.255001</coordinates></Point>', ptown.kml)
  557. @ignore_warnings(category=RemovedInDjango110Warning)
  558. def test_make_line(self):
  559. """
  560. Testing the (deprecated) `make_line` GeoQuerySet method and the MakeLine
  561. aggregate.
  562. """
  563. if not connection.features.supports_make_line_aggr:
  564. # Only PostGIS has support for the MakeLine aggregate. For other
  565. # backends, test that NotImplementedError is raised
  566. self.assertRaises(
  567. NotImplementedError,
  568. City.objects.all().aggregate, MakeLine('point')
  569. )
  570. return
  571. # Ensuring that a `TypeError` is raised on models without PointFields.
  572. self.assertRaises(TypeError, State.objects.make_line)
  573. self.assertRaises(TypeError, Country.objects.make_line)
  574. # MakeLine on an inappropriate field returns simply None
  575. self.assertIsNone(State.objects.aggregate(MakeLine('poly'))['poly__makeline'])
  576. # Reference query:
  577. # SELECT AsText(ST_MakeLine(geoapp_city.point)) FROM geoapp_city;
  578. ref_line = GEOSGeometry(
  579. 'LINESTRING(-95.363151 29.763374,-96.801611 32.782057,'
  580. '-97.521157 34.464642,174.783117 -41.315268,-104.609252 38.255001,'
  581. '-95.23506 38.971823,-87.650175 41.850385,-123.305196 48.462611)',
  582. srid=4326
  583. )
  584. # We check for equality with a tolerance of 10e-5 which is a lower bound
  585. # of the precisions of ref_line coordinates
  586. line1 = City.objects.make_line()
  587. line2 = City.objects.aggregate(MakeLine('point'))['point__makeline']
  588. for line in (line1, line2):
  589. self.assertTrue(ref_line.equals_exact(line, tolerance=10e-5),
  590. "%s != %s" % (ref_line, line))
  591. @skipUnlessDBFeature("has_num_geom_method")
  592. def test_num_geom(self):
  593. "Testing the `num_geom` GeoQuerySet method."
  594. # Both 'countries' only have two geometries.
  595. for c in Country.objects.num_geom():
  596. self.assertEqual(2, c.num_geom)
  597. for c in City.objects.filter(point__isnull=False).num_geom():
  598. # Oracle and PostGIS 2.0+ will return 1 for the number of
  599. # geometries on non-collections.
  600. self.assertEqual(1, c.num_geom)
  601. @skipUnlessDBFeature("supports_num_points_poly")
  602. def test_num_points(self):
  603. "Testing the `num_points` GeoQuerySet method."
  604. for c in Country.objects.num_points():
  605. self.assertEqual(c.mpoly.num_points, c.num_points)
  606. if not oracle:
  607. # Oracle cannot count vertices in Point geometries.
  608. for c in City.objects.num_points():
  609. self.assertEqual(1, c.num_points)
  610. @skipUnlessDBFeature("has_point_on_surface_method")
  611. def test_point_on_surface(self):
  612. "Testing the `point_on_surface` GeoQuerySet method."
  613. # Reference values.
  614. if oracle:
  615. # SELECT SDO_UTIL.TO_WKTGEOMETRY(SDO_GEOM.SDO_POINTONSURFACE(GEOAPP_COUNTRY.MPOLY, 0.05))
  616. # FROM GEOAPP_COUNTRY;
  617. ref = {'New Zealand': fromstr('POINT (174.616364 -36.100861)', srid=4326),
  618. 'Texas': fromstr('POINT (-103.002434 36.500397)', srid=4326),
  619. }
  620. else:
  621. # Using GEOSGeometry to compute the reference point on surface values
  622. # -- since PostGIS also uses GEOS these should be the same.
  623. ref = {'New Zealand': Country.objects.get(name='New Zealand').mpoly.point_on_surface,
  624. 'Texas': Country.objects.get(name='Texas').mpoly.point_on_surface
  625. }
  626. for c in Country.objects.point_on_surface():
  627. if spatialite:
  628. # XXX This seems to be a WKT-translation-related precision issue?
  629. tol = 0.00001
  630. else:
  631. tol = 0.000000001
  632. self.assertTrue(ref[c.name].equals_exact(c.point_on_surface, tol))
  633. @skipUnlessDBFeature("has_reverse_method")
  634. def test_reverse_geom(self):
  635. "Testing GeoQuerySet.reverse_geom()."
  636. coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)]
  637. Track.objects.create(name='Foo', line=LineString(coords))
  638. t = Track.objects.reverse_geom().get(name='Foo')
  639. coords.reverse()
  640. self.assertEqual(tuple(coords), t.reverse_geom.coords)
  641. if oracle:
  642. self.assertRaises(TypeError, State.objects.reverse_geom)
  643. @skipUnlessDBFeature("has_scale_method")
  644. def test_scale(self):
  645. "Testing the `scale` GeoQuerySet method."
  646. xfac, yfac = 2, 3
  647. tol = 5 # XXX The low precision tolerance is for SpatiaLite
  648. qs = Country.objects.scale(xfac, yfac, model_att='scaled')
  649. for c in qs:
  650. for p1, p2 in zip(c.mpoly, c.scaled):
  651. for r1, r2 in zip(p1, p2):
  652. for c1, c2 in zip(r1.coords, r2.coords):
  653. self.assertAlmostEqual(c1[0] * xfac, c2[0], tol)
  654. self.assertAlmostEqual(c1[1] * yfac, c2[1], tol)
  655. @skipUnlessDBFeature("has_snap_to_grid_method")
  656. def test_snap_to_grid(self):
  657. "Testing GeoQuerySet.snap_to_grid()."
  658. # Let's try and break snap_to_grid() with bad combinations of arguments.
  659. for bad_args in ((), range(3), range(5)):
  660. self.assertRaises(ValueError, Country.objects.snap_to_grid, *bad_args)
  661. for bad_args in (('1.0',), (1.0, None), tuple(map(six.text_type, range(4)))):
  662. self.assertRaises(TypeError, Country.objects.snap_to_grid, *bad_args)
  663. # Boundary for San Marino, courtesy of Bjorn Sandvik of thematicmapping.org
  664. # from the world borders dataset he provides.
  665. wkt = ('MULTIPOLYGON(((12.41580 43.95795,12.45055 43.97972,12.45389 43.98167,'
  666. '12.46250 43.98472,12.47167 43.98694,12.49278 43.98917,'
  667. '12.50555 43.98861,12.51000 43.98694,12.51028 43.98277,'
  668. '12.51167 43.94333,12.51056 43.93916,12.49639 43.92333,'
  669. '12.49500 43.91472,12.48778 43.90583,12.47444 43.89722,'
  670. '12.46472 43.89555,12.45917 43.89611,12.41639 43.90472,'
  671. '12.41222 43.90610,12.40782 43.91366,12.40389 43.92667,'
  672. '12.40500 43.94833,12.40889 43.95499,12.41580 43.95795)))')
  673. Country.objects.create(name='San Marino', mpoly=fromstr(wkt))
  674. # Because floating-point arithmetic isn't exact, we set a tolerance
  675. # to pass into GEOS `equals_exact`.
  676. tol = 0.000000001
  677. # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.1)) FROM "geoapp_country"
  678. # WHERE "geoapp_country"."name" = 'San Marino';
  679. ref = fromstr('MULTIPOLYGON(((12.4 44,12.5 44,12.5 43.9,12.4 43.9,12.4 44)))')
  680. self.assertTrue(ref.equals_exact(Country.objects.snap_to_grid(0.1).get(name='San Marino').snap_to_grid, tol))
  681. # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.05, 0.23)) FROM "geoapp_country"
  682. # WHERE "geoapp_country"."name" = 'San Marino';
  683. ref = fromstr('MULTIPOLYGON(((12.4 43.93,12.45 43.93,12.5 43.93,12.45 43.93,12.4 43.93)))')
  684. self.assertTrue(
  685. ref.equals_exact(Country.objects.snap_to_grid(0.05, 0.23).get(name='San Marino').snap_to_grid, tol)
  686. )
  687. # SELECT AsText(ST_SnapToGrid("geoapp_country"."mpoly", 0.5, 0.17, 0.05, 0.23)) FROM "geoapp_country"
  688. # WHERE "geoapp_country"."name" = 'San Marino';
  689. ref = fromstr(
  690. 'MULTIPOLYGON(((12.4 43.87,12.45 43.87,12.45 44.1,12.5 44.1,12.5 43.87,12.45 43.87,12.4 43.87)))'
  691. )
  692. self.assertTrue(
  693. ref.equals_exact(
  694. Country.objects.snap_to_grid(0.05, 0.23, 0.5, 0.17).get(name='San Marino').snap_to_grid,
  695. tol
  696. )
  697. )
  698. @skipUnlessDBFeature("has_svg_method")
  699. def test_svg(self):
  700. "Testing SVG output using GeoQuerySet.svg()."
  701. self.assertRaises(TypeError, City.objects.svg, precision='foo')
  702. # SELECT AsSVG(geoapp_city.point, 0, 8) FROM geoapp_city WHERE name = 'Pueblo';
  703. svg1 = 'cx="-104.609252" cy="-38.255001"'
  704. # Even though relative, only one point so it's practically the same except for
  705. # the 'c' letter prefix on the x,y values.
  706. svg2 = svg1.replace('c', '')
  707. self.assertEqual(svg1, City.objects.svg().get(name='Pueblo').svg)
  708. self.assertEqual(svg2, City.objects.svg(relative=5).get(name='Pueblo').svg)
  709. @skipUnlessDBFeature("has_transform_method")
  710. def test_transform(self):
  711. "Testing the transform() GeoQuerySet method."
  712. # Pre-transformed points for Houston and Pueblo.
  713. htown = fromstr('POINT(1947516.83115183 6322297.06040572)', srid=3084)
  714. ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774)
  715. prec = 3 # Precision is low due to version variations in PROJ and GDAL.
  716. # Asserting the result of the transform operation with the values in
  717. # the pre-transformed points. Oracle does not have the 3084 SRID.
  718. if not oracle:
  719. h = City.objects.transform(htown.srid).get(name='Houston')
  720. self.assertEqual(3084, h.point.srid)
  721. self.assertAlmostEqual(htown.x, h.point.x, prec)
  722. self.assertAlmostEqual(htown.y, h.point.y, prec)
  723. p1 = City.objects.transform(ptown.srid, field_name='point').get(name='Pueblo')
  724. p2 = City.objects.transform(srid=ptown.srid).get(name='Pueblo')
  725. for p in [p1, p2]:
  726. self.assertEqual(2774, p.point.srid)
  727. self.assertAlmostEqual(ptown.x, p.point.x, prec)
  728. self.assertAlmostEqual(ptown.y, p.point.y, prec)
  729. @skipUnlessDBFeature("has_translate_method")
  730. def test_translate(self):
  731. "Testing the `translate` GeoQuerySet method."
  732. xfac, yfac = 5, -23
  733. qs = Country.objects.translate(xfac, yfac, model_att='translated')
  734. for c in qs:
  735. for p1, p2 in zip(c.mpoly, c.translated):
  736. for r1, r2 in zip(p1, p2):
  737. for c1, c2 in zip(r1.coords, r2.coords):
  738. # XXX The low precision is for SpatiaLite
  739. self.assertAlmostEqual(c1[0] + xfac, c2[0], 5)
  740. self.assertAlmostEqual(c1[1] + yfac, c2[1], 5)
  741. # TODO: Oracle can be made to pass if
  742. # union1 = union2 = fromstr('POINT (-97.5211570000000023 34.4646419999999978)')
  743. # but this seems unexpected and should be investigated to determine the cause.
  744. @skipUnlessDBFeature("has_unionagg_method")
  745. @no_oracle
  746. @ignore_warnings(category=RemovedInDjango110Warning)
  747. def test_unionagg(self):
  748. """
  749. Testing the (deprecated) `unionagg` (aggregate union) GeoQuerySet method
  750. and the Union aggregate.
  751. """
  752. tx = Country.objects.get(name='Texas').mpoly
  753. # Houston, Dallas -- Ordering may differ depending on backend or GEOS version.
  754. union1 = fromstr('MULTIPOINT(-96.801611 32.782057,-95.363151 29.763374)')
  755. union2 = fromstr('MULTIPOINT(-95.363151 29.763374,-96.801611 32.782057)')
  756. qs = City.objects.filter(point__within=tx)
  757. self.assertRaises(TypeError, qs.unionagg, 'name')
  758. self.assertRaises(ValueError, qs.aggregate, Union('name'))
  759. # Using `field_name` keyword argument in one query and specifying an
  760. # order in the other (which should not be used because this is
  761. # an aggregate method on a spatial column)
  762. u1 = qs.unionagg(field_name='point')
  763. u2 = qs.order_by('name').unionagg()
  764. u3 = qs.aggregate(Union('point'))['point__union']
  765. u4 = qs.order_by('name').aggregate(Union('point'))['point__union']
  766. tol = 0.00001
  767. self.assertTrue(union1.equals_exact(u1, tol) or union2.equals_exact(u1, tol))
  768. self.assertTrue(union1.equals_exact(u2, tol) or union2.equals_exact(u2, tol))
  769. self.assertTrue(union1.equals_exact(u3, tol) or union2.equals_exact(u3, tol))
  770. self.assertTrue(union1.equals_exact(u4, tol) or union2.equals_exact(u4, tol))
  771. qs = City.objects.filter(name='NotACity')
  772. self.assertIsNone(qs.unionagg(field_name='point'))
  773. self.assertIsNone(qs.aggregate(Union('point'))['point__union'])
  774. def test_within_subquery(self):
  775. """
  776. Test that using a queryset inside a geo lookup is working (using a subquery)
  777. (#14483).
  778. """
  779. tex_cities = City.objects.filter(
  780. point__within=Country.objects.filter(name='Texas').values('mpoly')).order_by('name')
  781. expected = ['Dallas', 'Houston']
  782. if not connection.features.supports_real_shape_operations:
  783. expected.append('Oklahoma City')
  784. self.assertEqual(
  785. list(tex_cities.values_list('name', flat=True)),
  786. expected
  787. )
  788. def test_non_concrete_field(self):
  789. NonConcreteModel.objects.create(point=Point(0, 0), name='name')
  790. list(NonConcreteModel.objects.all())