PageRenderTime 143ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/gis/tests/geoapp/tests.py

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