PageRenderTime 104ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/codigo/Django-1.1.3/django/contrib/gis/tests/relatedapp/tests.py

https://github.com/alexleninn/sssssssssssssssssssssss
Python | 299 lines | 192 code | 42 blank | 65 comment | 15 complexity | dc2752dd927cec5605d2a1c55afae358 MD5 | raw file
Possible License(s): BSD-3-Clause, GPL-3.0
  1. import os, unittest
  2. from django.contrib.gis.geos import *
  3. from django.contrib.gis.db.backend import SpatialBackend
  4. from django.contrib.gis.db.models import Collect, Count, Extent, F, Union
  5. from django.contrib.gis.tests.utils import no_mysql, no_oracle, no_spatialite
  6. from django.conf import settings
  7. from models import City, Location, DirectoryEntry, Parcel, Book, Author
  8. cities = (('Aurora', 'TX', -97.516111, 33.058333),
  9. ('Roswell', 'NM', -104.528056, 33.387222),
  10. ('Kecksburg', 'PA', -79.460734, 40.18476),
  11. )
  12. class RelatedGeoModelTest(unittest.TestCase):
  13. def test01_setup(self):
  14. "Setting up for related model tests."
  15. for name, state, lon, lat in cities:
  16. loc = Location.objects.create(point=Point(lon, lat))
  17. c = City.objects.create(name=name, state=state, location=loc)
  18. def test02_select_related(self):
  19. "Testing `select_related` on geographic models (see #7126)."
  20. qs1 = City.objects.all()
  21. qs2 = City.objects.select_related()
  22. qs3 = City.objects.select_related('location')
  23. for qs in (qs1, qs2, qs3):
  24. for ref, c in zip(cities, qs):
  25. nm, st, lon, lat = ref
  26. self.assertEqual(nm, c.name)
  27. self.assertEqual(st, c.state)
  28. self.assertEqual(Point(lon, lat), c.location.point)
  29. @no_mysql
  30. def test03_transform_related(self):
  31. "Testing the `transform` GeoQuerySet method on related geographic models."
  32. # All the transformations are to state plane coordinate systems using
  33. # US Survey Feet (thus a tolerance of 0 implies error w/in 1 survey foot).
  34. tol = 0
  35. def check_pnt(ref, pnt):
  36. self.assertAlmostEqual(ref.x, pnt.x, tol)
  37. self.assertAlmostEqual(ref.y, pnt.y, tol)
  38. self.assertEqual(ref.srid, pnt.srid)
  39. # Each city transformed to the SRID of their state plane coordinate system.
  40. transformed = (('Kecksburg', 2272, 'POINT(1490553.98959621 314792.131023984)'),
  41. ('Roswell', 2257, 'POINT(481902.189077221 868477.766629735)'),
  42. ('Aurora', 2276, 'POINT(2269923.2484839 7069381.28722222)'),
  43. )
  44. for name, srid, wkt in transformed:
  45. # Doing this implicitly sets `select_related` select the location.
  46. # TODO: Fix why this breaks on Oracle.
  47. qs = list(City.objects.filter(name=name).transform(srid, field_name='location__point'))
  48. check_pnt(GEOSGeometry(wkt, srid), qs[0].location.point)
  49. @no_mysql
  50. @no_spatialite
  51. def test04a_related_extent_aggregate(self):
  52. "Testing the `extent` GeoQuerySet aggregates on related geographic models."
  53. # This combines the Extent and Union aggregates into one query
  54. aggs = City.objects.aggregate(Extent('location__point'))
  55. # One for all locations, one that excludes Roswell.
  56. all_extent = (-104.528060913086, 33.0583305358887,-79.4607315063477, 40.1847610473633)
  57. txpa_extent = (-97.51611328125, 33.0583305358887,-79.4607315063477, 40.1847610473633)
  58. e1 = City.objects.extent(field_name='location__point')
  59. e2 = City.objects.exclude(name='Roswell').extent(field_name='location__point')
  60. e3 = aggs['location__point__extent']
  61. # The tolerance value is to four decimal places because of differences
  62. # between the Oracle and PostGIS spatial backends on the extent calculation.
  63. tol = 4
  64. for ref, e in [(all_extent, e1), (txpa_extent, e2), (all_extent, e3)]:
  65. for ref_val, e_val in zip(ref, e): self.assertAlmostEqual(ref_val, e_val, tol)
  66. @no_mysql
  67. def test04b_related_union_aggregate(self):
  68. "Testing the `unionagg` GeoQuerySet aggregates on related geographic models."
  69. # This combines the Extent and Union aggregates into one query
  70. aggs = City.objects.aggregate(Union('location__point'))
  71. # These are the points that are components of the aggregate geographic
  72. # union that is returned.
  73. p1 = Point(-104.528056, 33.387222)
  74. p2 = Point(-97.516111, 33.058333)
  75. p3 = Point(-79.460734, 40.18476)
  76. # Creating the reference union geometry depending on the spatial backend,
  77. # as Oracle will have a different internal ordering of the component
  78. # geometries than PostGIS. The second union aggregate is for a union
  79. # query that includes limiting information in the WHERE clause (in other
  80. # words a `.filter()` precedes the call to `.unionagg()`).
  81. if SpatialBackend.oracle:
  82. ref_u1 = MultiPoint(p3, p1, p2, srid=4326)
  83. ref_u2 = MultiPoint(p3, p2, srid=4326)
  84. else:
  85. ref_u1 = MultiPoint(p1, p2, p3, srid=4326)
  86. ref_u2 = MultiPoint(p2, p3, srid=4326)
  87. u1 = City.objects.unionagg(field_name='location__point')
  88. u2 = City.objects.exclude(name='Roswell').unionagg(field_name='location__point')
  89. u3 = aggs['location__point__union']
  90. self.assertEqual(ref_u1, u1)
  91. self.assertEqual(ref_u2, u2)
  92. self.assertEqual(ref_u1, u3)
  93. def test05_select_related_fk_to_subclass(self):
  94. "Testing that calling select_related on a query over a model with an FK to a model subclass works"
  95. # Regression test for #9752.
  96. l = list(DirectoryEntry.objects.all().select_related())
  97. def test06_f_expressions(self):
  98. "Testing F() expressions on GeometryFields."
  99. # Constructing a dummy parcel border and getting the City instance for
  100. # assigning the FK.
  101. b1 = GEOSGeometry('POLYGON((-97.501205 33.052520,-97.501205 33.052576,-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))', srid=4326)
  102. pcity = City.objects.get(name='Aurora')
  103. # First parcel has incorrect center point that is equal to the City;
  104. # it also has a second border that is different from the first as a
  105. # 100ft buffer around the City.
  106. c1 = pcity.location.point
  107. c2 = c1.transform(2276, clone=True)
  108. b2 = c2.buffer(100)
  109. p1 = Parcel.objects.create(name='P1', city=pcity, center1=c1, center2=c2, border1=b1, border2=b2)
  110. # Now creating a second Parcel where the borders are the same, just
  111. # in different coordinate systems. The center points are also the
  112. # the same (but in different coordinate systems), and this time they
  113. # actually correspond to the centroid of the border.
  114. c1 = b1.centroid
  115. c2 = c1.transform(2276, clone=True)
  116. p2 = Parcel.objects.create(name='P2', city=pcity, center1=c1, center2=c2, border1=b1, border2=b1)
  117. # Should return the second Parcel, which has the center within the
  118. # border.
  119. qs = Parcel.objects.filter(center1__within=F('border1'))
  120. self.assertEqual(1, len(qs))
  121. self.assertEqual('P2', qs[0].name)
  122. if not SpatialBackend.mysql:
  123. # This time center2 is in a different coordinate system and needs
  124. # to be wrapped in transformation SQL.
  125. qs = Parcel.objects.filter(center2__within=F('border1'))
  126. self.assertEqual(1, len(qs))
  127. self.assertEqual('P2', qs[0].name)
  128. # Should return the first Parcel, which has the center point equal
  129. # to the point in the City ForeignKey.
  130. qs = Parcel.objects.filter(center1=F('city__location__point'))
  131. self.assertEqual(1, len(qs))
  132. self.assertEqual('P1', qs[0].name)
  133. if not SpatialBackend.mysql:
  134. # This time the city column should be wrapped in transformation SQL.
  135. qs = Parcel.objects.filter(border2__contains=F('city__location__point'))
  136. self.assertEqual(1, len(qs))
  137. self.assertEqual('P1', qs[0].name)
  138. def test07_values(self):
  139. "Testing values() and values_list() and GeoQuerySets."
  140. # GeoQuerySet and GeoValuesQuerySet, and GeoValuesListQuerySet respectively.
  141. gqs = Location.objects.all()
  142. gvqs = Location.objects.values()
  143. gvlqs = Location.objects.values_list()
  144. # Incrementing through each of the models, dictionaries, and tuples
  145. # returned by the different types of GeoQuerySets.
  146. for m, d, t in zip(gqs, gvqs, gvlqs):
  147. # The values should be Geometry objects and not raw strings returned
  148. # by the spatial database.
  149. self.failUnless(isinstance(d['point'], SpatialBackend.Geometry))
  150. self.failUnless(isinstance(t[1], SpatialBackend.Geometry))
  151. self.assertEqual(m.point, d['point'])
  152. self.assertEqual(m.point, t[1])
  153. def test08_defer_only(self):
  154. "Testing defer() and only() on Geographic models."
  155. qs = Location.objects.all()
  156. def_qs = Location.objects.defer('point')
  157. for loc, def_loc in zip(qs, def_qs):
  158. self.assertEqual(loc.point, def_loc.point)
  159. def test09_pk_relations(self):
  160. "Ensuring correct primary key column is selected across relations. See #10757."
  161. # Adding two more cities, but this time making sure that their location
  162. # ID values do not match their City ID values.
  163. loc1 = Location.objects.create(point='POINT (-95.363151 29.763374)')
  164. loc2 = Location.objects.create(point='POINT (-96.801611 32.782057)')
  165. dallas = City.objects.create(name='Dallas', state='TX', location=loc2)
  166. houston = City.objects.create(name='Houston', state='TX', location=loc1)
  167. # The expected ID values -- notice the last two location IDs
  168. # are out of order. We want to make sure that the related
  169. # location ID column is selected instead of ID column for
  170. # the city.
  171. city_ids = (1, 2, 3, 4, 5)
  172. loc_ids = (1, 2, 3, 5, 4)
  173. ids_qs = City.objects.order_by('id').values('id', 'location__id')
  174. for val_dict, c_id, l_id in zip(ids_qs, city_ids, loc_ids):
  175. self.assertEqual(val_dict['id'], c_id)
  176. self.assertEqual(val_dict['location__id'], l_id)
  177. def test10_combine(self):
  178. "Testing the combination of two GeoQuerySets. See #10807."
  179. buf1 = City.objects.get(name='Aurora').location.point.buffer(0.1)
  180. buf2 = City.objects.get(name='Kecksburg').location.point.buffer(0.1)
  181. qs1 = City.objects.filter(location__point__within=buf1)
  182. qs2 = City.objects.filter(location__point__within=buf2)
  183. combined = qs1 | qs2
  184. names = [c.name for c in combined]
  185. self.assertEqual(2, len(names))
  186. self.failUnless('Aurora' in names)
  187. self.failUnless('Kecksburg' in names)
  188. def test11_geoquery_pickle(self):
  189. "Ensuring GeoQuery objects are unpickled correctly. See #10839."
  190. import pickle
  191. from django.contrib.gis.db.models.sql import GeoQuery
  192. qs = City.objects.all()
  193. q_str = pickle.dumps(qs.query)
  194. q = pickle.loads(q_str)
  195. self.assertEqual(GeoQuery, q.__class__)
  196. # TODO: fix on Oracle -- get the following error because the SQL is ordered
  197. # by a geometry object, which Oracle apparently doesn't like:
  198. # ORA-22901: cannot compare nested table or VARRAY or LOB attributes of an object type
  199. @no_oracle
  200. def test12a_count(self):
  201. "Testing `Count` aggregate use with the `GeoManager` on geo-fields."
  202. # Creating a new City, 'Fort Worth', that uses the same location
  203. # as Dallas.
  204. dallas = City.objects.get(name='Dallas')
  205. ftworth = City.objects.create(name='Fort Worth', state='TX', location=dallas.location)
  206. # Count annotation should be 2 for the Dallas location now.
  207. loc = Location.objects.annotate(num_cities=Count('city')).get(id=dallas.location.id)
  208. self.assertEqual(2, loc.num_cities)
  209. def test12b_count(self):
  210. "Testing `Count` aggregate use with the `GeoManager` on non geo-fields. See #11087."
  211. # Creating some data for the Book/Author non-geo models that
  212. # use GeoManager. See #11087.
  213. tp = Author.objects.create(name='Trevor Paglen')
  214. Book.objects.create(title='Torture Taxi', author=tp)
  215. Book.objects.create(title='I Could Tell You But Then You Would Have to be Destroyed by Me', author=tp)
  216. Book.objects.create(title='Blank Spots on the Map', author=tp)
  217. wp = Author.objects.create(name='William Patry')
  218. Book.objects.create(title='Patry on Copyright', author=wp)
  219. # Should only be one author (Trevor Paglen) returned by this query, and
  220. # the annotation should have 3 for the number of books. Also testing
  221. # with a `GeoValuesQuerySet` (see #11489).
  222. qs = Author.objects.annotate(num_books=Count('books')).filter(num_books__gt=1)
  223. vqs = Author.objects.values('name').annotate(num_books=Count('books')).filter(num_books__gt=1)
  224. self.assertEqual(1, len(qs))
  225. self.assertEqual(3, qs[0].num_books)
  226. self.assertEqual(1, len(vqs))
  227. self.assertEqual(3, vqs[0]['num_books'])
  228. # TODO: The phantom model does appear on Oracle.
  229. @no_oracle
  230. def test13_select_related_null_fk(self):
  231. "Testing `select_related` on a nullable ForeignKey via `GeoManager`. See #11381."
  232. no_author = Book.objects.create(title='Without Author')
  233. b = Book.objects.select_related('author').get(title='Without Author')
  234. # Should be `None`, and not a 'dummy' model.
  235. self.assertEqual(None, b.author)
  236. @no_mysql
  237. @no_oracle
  238. @no_spatialite
  239. def test14_collect(self):
  240. "Testing the `collect` GeoQuerySet method and `Collect` aggregate."
  241. # Reference query:
  242. # SELECT AsText(ST_Collect("relatedapp_location"."point")) FROM "relatedapp_city" LEFT OUTER JOIN
  243. # "relatedapp_location" ON ("relatedapp_city"."location_id" = "relatedapp_location"."id")
  244. # WHERE "relatedapp_city"."state" = 'TX';
  245. ref_geom = fromstr('MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057,-95.363151 29.763374,-96.801611 32.782057)')
  246. c1 = City.objects.filter(state='TX').collect(field_name='location__point')
  247. c2 = City.objects.filter(state='TX').aggregate(Collect('location__point'))['location__point__collect']
  248. for coll in (c1, c2):
  249. # Even though Dallas and Ft. Worth share same point, Collect doesn't
  250. # consolidate -- that's why 4 points in MultiPoint.
  251. self.assertEqual(4, len(coll))
  252. self.assertEqual(ref_geom, coll)
  253. # TODO: Related tests for KML, GML, and distance lookups.
  254. def suite():
  255. s = unittest.TestSuite()
  256. s.addTest(unittest.makeSuite(RelatedGeoModelTest))
  257. return s