tests.py 41 KB

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