tests.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. from __future__ import unicode_literals
  2. from django.contrib.gis.db.models.functions import (
  3. Area, Distance, Length, Perimeter, Transform,
  4. )
  5. from django.contrib.gis.geos import GEOSGeometry, LineString, Point
  6. from django.contrib.gis.measure import D # alias for Distance
  7. from django.db import connection
  8. from django.db.models import F, Q
  9. from django.test import TestCase, skipUnlessDBFeature
  10. from ..utils import no_oracle, oracle, postgis, spatialite
  11. from .models import (
  12. AustraliaCity, CensusZipcode, Interstate, SouthTexasCity, SouthTexasCityFt,
  13. SouthTexasInterstate, SouthTexasZipcode,
  14. )
  15. @skipUnlessDBFeature("gis_enabled")
  16. class DistanceTest(TestCase):
  17. fixtures = ['initial']
  18. def setUp(self):
  19. # A point we are testing distances with -- using a WGS84
  20. # coordinate that'll be implicitly transformed to that to
  21. # the coordinate system of the field, EPSG:32140 (Texas South Central
  22. # w/units in meters)
  23. self.stx_pnt = GEOSGeometry('POINT (-95.370401017314293 29.704867409475465)', 4326)
  24. # Another one for Australia
  25. self.au_pnt = GEOSGeometry('POINT (150.791 -34.4919)', 4326)
  26. def get_names(self, qs):
  27. cities = [c.name for c in qs]
  28. cities.sort()
  29. return cities
  30. def test_init(self):
  31. """
  32. Test initialization of distance models.
  33. """
  34. self.assertEqual(9, SouthTexasCity.objects.count())
  35. self.assertEqual(9, SouthTexasCityFt.objects.count())
  36. self.assertEqual(11, AustraliaCity.objects.count())
  37. self.assertEqual(4, SouthTexasZipcode.objects.count())
  38. self.assertEqual(4, CensusZipcode.objects.count())
  39. self.assertEqual(1, Interstate.objects.count())
  40. self.assertEqual(1, SouthTexasInterstate.objects.count())
  41. @skipUnlessDBFeature("supports_dwithin_lookup")
  42. def test_dwithin(self):
  43. """
  44. Test the `dwithin` lookup type.
  45. """
  46. # Distances -- all should be equal (except for the
  47. # degree/meter pair in au_cities, that's somewhat
  48. # approximate).
  49. tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)]
  50. au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)]
  51. # Expected cities for Australia and Texas.
  52. tx_cities = ['Downtown Houston', 'Southside Place']
  53. au_cities = ['Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong']
  54. # Performing distance queries on two projected coordinate systems one
  55. # with units in meters and the other in units of U.S. survey feet.
  56. for dist in tx_dists:
  57. if isinstance(dist, tuple):
  58. dist1, dist2 = dist
  59. else:
  60. dist1 = dist2 = dist
  61. qs1 = SouthTexasCity.objects.filter(point__dwithin=(self.stx_pnt, dist1))
  62. qs2 = SouthTexasCityFt.objects.filter(point__dwithin=(self.stx_pnt, dist2))
  63. for qs in qs1, qs2:
  64. self.assertEqual(tx_cities, self.get_names(qs))
  65. # Now performing the `dwithin` queries on a geodetic coordinate system.
  66. for dist in au_dists:
  67. if isinstance(dist, D) and not oracle:
  68. type_error = True
  69. else:
  70. type_error = False
  71. if isinstance(dist, tuple):
  72. if oracle or spatialite:
  73. # Result in meters
  74. dist = dist[1]
  75. else:
  76. # Result in units of the field
  77. dist = dist[0]
  78. # Creating the query set.
  79. qs = AustraliaCity.objects.order_by('name')
  80. if type_error:
  81. # A ValueError should be raised on PostGIS when trying to pass
  82. # Distance objects into a DWithin query using a geodetic field.
  83. with self.assertRaises(ValueError):
  84. AustraliaCity.objects.filter(point__dwithin=(self.au_pnt, dist)).count()
  85. else:
  86. self.assertListEqual(au_cities, self.get_names(qs.filter(point__dwithin=(self.au_pnt, dist))))
  87. @skipUnlessDBFeature("supports_distances_lookups")
  88. def test_distance_lookups(self):
  89. """
  90. Test the `distance_lt`, `distance_gt`, `distance_lte`, and `distance_gte` lookup types.
  91. """
  92. # Retrieving the cities within a 20km 'donut' w/a 7km radius 'hole'
  93. # (thus, Houston and Southside place will be excluded as tested in
  94. # the `test02_dwithin` above).
  95. qs1 = SouthTexasCity.objects.filter(point__distance_gte=(self.stx_pnt, D(km=7))).filter(
  96. point__distance_lte=(self.stx_pnt, D(km=20)),
  97. )
  98. # Oracle 11 incorrectly thinks it is not projected.
  99. if oracle:
  100. dist_qs = (qs1,)
  101. else:
  102. qs2 = SouthTexasCityFt.objects.filter(point__distance_gte=(self.stx_pnt, D(km=7))).filter(
  103. point__distance_lte=(self.stx_pnt, D(km=20)),
  104. )
  105. dist_qs = (qs1, qs2)
  106. for qs in dist_qs:
  107. cities = self.get_names(qs)
  108. self.assertEqual(cities, ['Bellaire', 'Pearland', 'West University Place'])
  109. # Doing a distance query using Polygons instead of a Point.
  110. z = SouthTexasZipcode.objects.get(name='77005')
  111. qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=275)))
  112. self.assertEqual(['77025', '77401'], self.get_names(qs))
  113. # If we add a little more distance 77002 should be included.
  114. qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=300)))
  115. self.assertEqual(['77002', '77025', '77401'], self.get_names(qs))
  116. @skipUnlessDBFeature("supports_distances_lookups", "supports_distance_geodetic")
  117. def test_geodetic_distance_lookups(self):
  118. """
  119. Test distance lookups on geodetic coordinate systems.
  120. """
  121. # Line is from Canberra to Sydney. Query is for all other cities within
  122. # a 100km of that line (which should exclude only Hobart & Adelaide).
  123. line = GEOSGeometry('LINESTRING(144.9630 -37.8143,151.2607 -33.8870)', 4326)
  124. dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line, D(km=100)))
  125. expected_cities = [
  126. 'Batemans Bay', 'Canberra', 'Hillsdale',
  127. 'Melbourne', 'Mittagong', 'Shellharbour',
  128. 'Sydney', 'Thirroul', 'Wollongong',
  129. ]
  130. if spatialite:
  131. # SpatiaLite is less accurate and returns 102.8km for Batemans Bay.
  132. expected_cities.pop(0)
  133. self.assertEqual(expected_cities, self.get_names(dist_qs))
  134. # Too many params (4 in this case) should raise a ValueError.
  135. queryset = AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4'))
  136. with self.assertRaises(ValueError):
  137. len(queryset)
  138. # Not enough params should raise a ValueError.
  139. with self.assertRaises(ValueError):
  140. len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',)))
  141. # Getting all cities w/in 550 miles of Hobart.
  142. hobart = AustraliaCity.objects.get(name='Hobart')
  143. qs = AustraliaCity.objects.exclude(name='Hobart').filter(point__distance_lte=(hobart.point, D(mi=550)))
  144. cities = self.get_names(qs)
  145. self.assertEqual(cities, ['Batemans Bay', 'Canberra', 'Melbourne'])
  146. # Cities that are either really close or really far from Wollongong --
  147. # and using different units of distance.
  148. wollongong = AustraliaCity.objects.get(name='Wollongong')
  149. d1, d2 = D(yd=19500), D(nm=400) # Yards (~17km) & Nautical miles.
  150. # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS.
  151. gq1 = Q(point__distance_lte=(wollongong.point, d1))
  152. gq2 = Q(point__distance_gte=(wollongong.point, d2))
  153. qs1 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq1 | gq2)
  154. # Geodetic distance lookup but telling GeoDjango to use `distance_spheroid`
  155. # instead (we should get the same results b/c accuracy variance won't matter
  156. # in this test case).
  157. querysets = [qs1]
  158. if connection.features.has_DistanceSpheroid_function:
  159. gq3 = Q(point__distance_lte=(wollongong.point, d1, 'spheroid'))
  160. gq4 = Q(point__distance_gte=(wollongong.point, d2, 'spheroid'))
  161. qs2 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq3 | gq4)
  162. querysets.append(qs2)
  163. for qs in querysets:
  164. cities = self.get_names(qs)
  165. self.assertEqual(cities, ['Adelaide', 'Hobart', 'Shellharbour', 'Thirroul'])
  166. @skipUnlessDBFeature("supports_distances_lookups")
  167. def test_distance_lookups_with_expression_rhs(self):
  168. qs = SouthTexasCity.objects.filter(
  169. point__distance_lte=(self.stx_pnt, F('radius')),
  170. ).order_by('name')
  171. self.assertEqual(
  172. self.get_names(qs),
  173. ['Bellaire', 'Downtown Houston', 'Southside Place', 'West University Place']
  174. )
  175. # With a combined expression
  176. qs = SouthTexasCity.objects.filter(
  177. point__distance_lte=(self.stx_pnt, F('radius') * 2),
  178. ).order_by('name')
  179. self.assertEqual(len(qs), 5)
  180. self.assertIn('Pearland', self.get_names(qs))
  181. # With spheroid param
  182. if connection.features.supports_distance_geodetic:
  183. hobart = AustraliaCity.objects.get(name='Hobart')
  184. qs = AustraliaCity.objects.filter(
  185. point__distance_lte=(hobart.point, F('radius') * 70, 'spheroid'),
  186. ).order_by('name')
  187. self.assertEqual(self.get_names(qs), ['Canberra', 'Hobart', 'Melbourne'])
  188. '''
  189. =============================
  190. Distance functions on PostGIS
  191. =============================
  192. | Projected Geometry | Lon/lat Geometry | Geography (4326)
  193. ST_Distance(geom1, geom2) | OK (meters) | :-( (degrees) | OK (meters)
  194. ST_Distance(geom1, geom2, use_spheroid=False) | N/A | N/A | OK (meters), less accurate, quick
  195. Distance_Sphere(geom1, geom2) | N/A | OK (meters) | N/A
  196. Distance_Spheroid(geom1, geom2, spheroid) | N/A | OK (meters) | N/A
  197. ST_Perimeter(geom1) | OK | :-( (degrees) | OK
  198. ================================
  199. Distance functions on SpatiaLite
  200. ================================
  201. | Projected Geometry | Lon/lat Geometry
  202. ST_Distance(geom1, geom2) | OK (meters) | N/A
  203. ST_Distance(geom1, geom2, use_ellipsoid=True) | N/A | OK (meters)
  204. ST_Distance(geom1, geom2, use_ellipsoid=False) | N/A | OK (meters), less accurate, quick
  205. Perimeter(geom1) | OK | :-( (degrees)
  206. ''' # NOQA
  207. @skipUnlessDBFeature("gis_enabled")
  208. class DistanceFunctionsTests(TestCase):
  209. fixtures = ['initial']
  210. @skipUnlessDBFeature("has_Area_function")
  211. def test_area(self):
  212. # Reference queries:
  213. # SELECT ST_Area(poly) FROM distapp_southtexaszipcode;
  214. area_sq_m = [5437908.90234375, 10183031.4389648, 11254471.0073242, 9881708.91772461]
  215. # Tolerance has to be lower for Oracle
  216. tol = 2
  217. for i, z in enumerate(SouthTexasZipcode.objects.annotate(area=Area('poly')).order_by('name')):
  218. self.assertAlmostEqual(area_sq_m[i], z.area.sq_m, tol)
  219. @skipUnlessDBFeature("has_Distance_function")
  220. def test_distance_simple(self):
  221. """
  222. Test a simple distance query, with projected coordinates and without
  223. transformation.
  224. """
  225. lagrange = GEOSGeometry('POINT(805066.295722839 4231496.29461335)', 32140)
  226. houston = SouthTexasCity.objects.annotate(dist=Distance('point', lagrange)).order_by('id').first()
  227. tol = 2 if oracle else 5
  228. self.assertAlmostEqual(
  229. houston.dist.m,
  230. 147075.069813,
  231. tol
  232. )
  233. @skipUnlessDBFeature("has_Distance_function", "has_Transform_function")
  234. def test_distance_projected(self):
  235. """
  236. Test the `Distance` function on projected coordinate systems.
  237. """
  238. # The point for La Grange, TX
  239. lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326)
  240. # Reference distances in feet and in meters. Got these values from
  241. # using the provided raw SQL statements.
  242. # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140))
  243. # FROM distapp_southtexascity;
  244. m_distances = [147075.069813, 139630.198056, 140888.552826,
  245. 138809.684197, 158309.246259, 212183.594374,
  246. 70870.188967, 165337.758878, 139196.085105]
  247. # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278))
  248. # FROM distapp_southtexascityft;
  249. # Oracle 11 thinks this is not a projected coordinate system, so it's
  250. # not tested.
  251. ft_distances = [482528.79154625, 458103.408123001, 462231.860397575,
  252. 455411.438904354, 519386.252102563, 696139.009211594,
  253. 232513.278304279, 542445.630586414, 456679.155883207]
  254. # Testing using different variations of parameters and using models
  255. # with different projected coordinate systems.
  256. dist1 = SouthTexasCity.objects.annotate(distance=Distance('point', lagrange)).order_by('id')
  257. if oracle:
  258. dist_qs = [dist1]
  259. else:
  260. dist2 = SouthTexasCityFt.objects.annotate(distance=Distance('point', lagrange)).order_by('id')
  261. dist_qs = [dist1, dist2]
  262. # Original query done on PostGIS, have to adjust AlmostEqual tolerance
  263. # for Oracle.
  264. tol = 2 if oracle else 5
  265. # Ensuring expected distances are returned for each distance queryset.
  266. for qs in dist_qs:
  267. for i, c in enumerate(qs):
  268. self.assertAlmostEqual(m_distances[i], c.distance.m, tol)
  269. self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft, tol)
  270. @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic")
  271. def test_distance_geodetic(self):
  272. """
  273. Test the `Distance` function on geodetic coordinate systems.
  274. """
  275. # Testing geodetic distance calculation with a non-point geometry
  276. # (a LineString of Wollongong and Shellharbour coords).
  277. ls = LineString(((150.902, -34.4245), (150.87, -34.5789)), srid=4326)
  278. # Reference query:
  279. # SELECT ST_distance_sphere(point, ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326))
  280. # FROM distapp_australiacity ORDER BY name;
  281. distances = [1120954.92533513, 140575.720018241, 640396.662906304,
  282. 60580.9693849269, 972807.955955075, 568451.8357838,
  283. 40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0]
  284. qs = AustraliaCity.objects.annotate(distance=Distance('point', ls)).order_by('name')
  285. for city, distance in zip(qs, distances):
  286. # Testing equivalence to within a meter (kilometer on SpatiaLite).
  287. tol = -3 if spatialite else 0
  288. self.assertAlmostEqual(distance, city.distance.m, tol)
  289. @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic")
  290. def test_distance_geodetic_spheroid(self):
  291. tol = 2 if oracle else 4
  292. # Got the reference distances using the raw SQL statements:
  293. # SELECT ST_distance_spheroid(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326),
  294. # 'SPHEROID["WGS 84",6378137.0,298.257223563]') FROM distapp_australiacity WHERE (NOT (id = 11));
  295. # SELECT ST_distance_sphere(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326))
  296. # FROM distapp_australiacity WHERE (NOT (id = 11)); st_distance_sphere
  297. spheroid_distances = [
  298. 60504.0628957201, 77023.9489850262, 49154.8867574404,
  299. 90847.4358768573, 217402.811919332, 709599.234564757,
  300. 640011.483550888, 7772.00667991925, 1047861.78619339,
  301. 1165126.55236034,
  302. ]
  303. sphere_distances = [
  304. 60580.9693849267, 77144.0435286473, 49199.4415344719,
  305. 90804.7533823494, 217713.384600405, 709134.127242793,
  306. 639828.157159169, 7786.82949717788, 1049204.06569028,
  307. 1162623.7238134,
  308. ]
  309. # Testing with spheroid distances first.
  310. hillsdale = AustraliaCity.objects.get(name='Hillsdale')
  311. qs = AustraliaCity.objects.exclude(id=hillsdale.id).annotate(
  312. distance=Distance('point', hillsdale.point, spheroid=True)
  313. ).order_by('id')
  314. for i, c in enumerate(qs):
  315. self.assertAlmostEqual(spheroid_distances[i], c.distance.m, tol)
  316. if postgis or spatialite:
  317. # PostGIS uses sphere-only distances by default, testing these as well.
  318. qs = AustraliaCity.objects.exclude(id=hillsdale.id).annotate(
  319. distance=Distance('point', hillsdale.point)
  320. ).order_by('id')
  321. for i, c in enumerate(qs):
  322. self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)
  323. @no_oracle # Oracle already handles geographic distance calculation.
  324. @skipUnlessDBFeature("has_Distance_function", 'has_Transform_function')
  325. def test_distance_transform(self):
  326. """
  327. Test the `Distance` function used with `Transform` on a geographic field.
  328. """
  329. # We'll be using a Polygon (created by buffering the centroid
  330. # of 77005 to 100m) -- which aren't allowed in geographic distance
  331. # queries normally, however our field has been transformed to
  332. # a non-geographic system.
  333. z = SouthTexasZipcode.objects.get(name='77005')
  334. # Reference query:
  335. # SELECT ST_Distance(ST_Transform("distapp_censuszipcode"."poly", 32140),
  336. # ST_GeomFromText('<buffer_wkt>', 32140))
  337. # FROM "distapp_censuszipcode";
  338. dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242]
  339. # Having our buffer in the SRID of the transformation and of the field
  340. # -- should get the same results. The first buffer has no need for
  341. # transformation SQL because it is the same SRID as what was given
  342. # to `transform()`. The second buffer will need to be transformed,
  343. # however.
  344. buf1 = z.poly.centroid.buffer(100)
  345. buf2 = buf1.transform(4269, clone=True)
  346. ref_zips = ['77002', '77025', '77401']
  347. for buf in [buf1, buf2]:
  348. qs = CensusZipcode.objects.exclude(name='77005').annotate(
  349. distance=Distance(Transform('poly', 32140), buf)
  350. ).order_by('name')
  351. self.assertEqual(ref_zips, sorted([c.name for c in qs]))
  352. for i, z in enumerate(qs):
  353. self.assertAlmostEqual(z.distance.m, dists_m[i], 5)
  354. @skipUnlessDBFeature("has_Distance_function")
  355. def test_distance_order_by(self):
  356. qs = SouthTexasCity.objects.annotate(distance=Distance('point', Point(3, 3, srid=32140))).order_by(
  357. 'distance'
  358. ).values_list('name', flat=True).filter(name__in=('San Antonio', 'Pearland'))
  359. self.assertSequenceEqual(qs, ['San Antonio', 'Pearland'])
  360. @skipUnlessDBFeature("has_Length_function")
  361. def test_length(self):
  362. """
  363. Test the `Length` function.
  364. """
  365. # Reference query (should use `length_spheroid`).
  366. # SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563,
  367. # AUTHORITY["EPSG","7030"]]');
  368. len_m1 = 473504.769553813
  369. len_m2 = 4617.668
  370. if connection.features.supports_length_geodetic:
  371. qs = Interstate.objects.annotate(length=Length('path'))
  372. tol = 2 if oracle else 3
  373. self.assertAlmostEqual(len_m1, qs[0].length.m, tol)
  374. # TODO: test with spheroid argument (True and False)
  375. else:
  376. # Does not support geodetic coordinate systems.
  377. with self.assertRaises(NotImplementedError):
  378. list(Interstate.objects.annotate(length=Length('path')))
  379. # Now doing length on a projected coordinate system.
  380. i10 = SouthTexasInterstate.objects.annotate(length=Length('path')).get(name='I-10')
  381. self.assertAlmostEqual(len_m2, i10.length.m, 2)
  382. self.assertTrue(
  383. SouthTexasInterstate.objects.annotate(length=Length('path')).filter(length__gt=4000).exists()
  384. )
  385. @skipUnlessDBFeature("has_Perimeter_function")
  386. def test_perimeter(self):
  387. """
  388. Test the `Perimeter` function.
  389. """
  390. # Reference query:
  391. # SELECT ST_Perimeter(distapp_southtexaszipcode.poly) FROM distapp_southtexaszipcode;
  392. perim_m = [18404.3550889361, 15627.2108551001, 20632.5588368978, 17094.5996143697]
  393. tol = 2 if oracle else 7
  394. qs = SouthTexasZipcode.objects.annotate(perimeter=Perimeter('poly')).order_by('name')
  395. for i, z in enumerate(qs):
  396. self.assertAlmostEqual(perim_m[i], z.perimeter.m, tol)
  397. # Running on points; should return 0.
  398. qs = SouthTexasCity.objects.annotate(perim=Perimeter('point'))
  399. for city in qs:
  400. self.assertEqual(0, city.perim.m)
  401. @skipUnlessDBFeature("has_Perimeter_function")
  402. def test_perimeter_geodetic(self):
  403. # Currently only Oracle supports calculating the perimeter on geodetic
  404. # geometries (without being transformed).
  405. qs1 = CensusZipcode.objects.annotate(perim=Perimeter('poly'))
  406. if connection.features.supports_perimeter_geodetic:
  407. self.assertAlmostEqual(qs1[0].perim.m, 18406.3818954314, 3)
  408. else:
  409. with self.assertRaises(NotImplementedError):
  410. list(qs1)
  411. # But should work fine when transformed to projected coordinates
  412. qs2 = CensusZipcode.objects.annotate(perim=Perimeter(Transform('poly', 32140))).filter(name='77002')
  413. self.assertAlmostEqual(qs2[0].perim.m, 18404.355, 3)
  414. @skipUnlessDBFeature("supports_null_geometries", "has_Area_function", "has_Distance_function")
  415. def test_measurement_null_fields(self):
  416. """
  417. Test the measurement functions on fields with NULL values.
  418. """
  419. # Creating SouthTexasZipcode w/NULL value.
  420. SouthTexasZipcode.objects.create(name='78212')
  421. # Performing distance/area queries against the NULL PolygonField,
  422. # and ensuring the result of the operations is None.
  423. htown = SouthTexasCity.objects.get(name='Downtown Houston')
  424. z = SouthTexasZipcode.objects.annotate(
  425. distance=Distance('poly', htown.point), area=Area('poly')
  426. ).get(name='78212')
  427. self.assertIsNone(z.distance)
  428. self.assertIsNone(z.area)