tests.py 37 KB

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