2
0

tests.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. import os
  4. import unittest
  5. from copy import copy
  6. from decimal import Decimal
  7. from unittest import skipUnless
  8. from django.conf import settings
  9. from django.contrib.gis.gdal import HAS_GDAL
  10. from django.contrib.gis.geos import HAS_GEOS
  11. from django.db import connection
  12. from django.test import TestCase, override_settings, skipUnlessDBFeature
  13. from django.utils._os import upath
  14. if HAS_GEOS and HAS_GDAL:
  15. from django.contrib.gis.utils.layermapping import (LayerMapping,
  16. LayerMapError, InvalidDecimal, InvalidString, MissingForeignKey)
  17. from django.contrib.gis.gdal import DataSource
  18. from .models import (
  19. City, County, CountyFeat, Interstate, ICity1, ICity2, Invalid, State,
  20. city_mapping, co_mapping, cofeat_mapping, inter_mapping)
  21. shp_path = os.path.realpath(os.path.join(os.path.dirname(upath(__file__)), os.pardir, 'data'))
  22. city_shp = os.path.join(shp_path, 'cities', 'cities.shp')
  23. co_shp = os.path.join(shp_path, 'counties', 'counties.shp')
  24. inter_shp = os.path.join(shp_path, 'interstates', 'interstates.shp')
  25. invalid_shp = os.path.join(shp_path, 'invalid', 'emptypoints.shp')
  26. # Dictionaries to hold what's expected in the county shapefile.
  27. NAMES = ['Bexar', 'Galveston', 'Harris', 'Honolulu', 'Pueblo']
  28. NUMS = [1, 2, 1, 19, 1] # Number of polygons for each.
  29. STATES = ['Texas', 'Texas', 'Texas', 'Hawaii', 'Colorado']
  30. @skipUnless(HAS_GDAL, "LayerMapTest needs GDAL support")
  31. @skipUnlessDBFeature("gis_enabled")
  32. class LayerMapTest(TestCase):
  33. def test_init(self):
  34. "Testing LayerMapping initialization."
  35. # Model field that does not exist.
  36. bad1 = copy(city_mapping)
  37. bad1['foobar'] = 'FooField'
  38. # Shapefile field that does not exist.
  39. bad2 = copy(city_mapping)
  40. bad2['name'] = 'Nombre'
  41. # Nonexistent geographic field type.
  42. bad3 = copy(city_mapping)
  43. bad3['point'] = 'CURVE'
  44. # Incrementing through the bad mapping dictionaries and
  45. # ensuring that a LayerMapError is raised.
  46. for bad_map in (bad1, bad2, bad3):
  47. with self.assertRaises(LayerMapError):
  48. LayerMapping(City, city_shp, bad_map)
  49. # A LookupError should be thrown for bogus encodings.
  50. with self.assertRaises(LookupError):
  51. LayerMapping(City, city_shp, city_mapping, encoding='foobar')
  52. def test_simple_layermap(self):
  53. "Test LayerMapping import of a simple point shapefile."
  54. # Setting up for the LayerMapping.
  55. lm = LayerMapping(City, city_shp, city_mapping)
  56. lm.save()
  57. # There should be three cities in the shape file.
  58. self.assertEqual(3, City.objects.count())
  59. # Opening up the shapefile, and verifying the values in each
  60. # of the features made it to the model.
  61. ds = DataSource(city_shp)
  62. layer = ds[0]
  63. for feat in layer:
  64. city = City.objects.get(name=feat['Name'].value)
  65. self.assertEqual(feat['Population'].value, city.population)
  66. self.assertEqual(Decimal(str(feat['Density'])), city.density)
  67. self.assertEqual(feat['Created'].value, city.dt)
  68. # Comparing the geometries.
  69. pnt1, pnt2 = feat.geom, city.point
  70. self.assertAlmostEqual(pnt1.x, pnt2.x, 5)
  71. self.assertAlmostEqual(pnt1.y, pnt2.y, 5)
  72. def test_layermap_strict(self):
  73. "Testing the `strict` keyword, and import of a LineString shapefile."
  74. # When the `strict` keyword is set an error encountered will force
  75. # the importation to stop.
  76. with self.assertRaises(InvalidDecimal):
  77. lm = LayerMapping(Interstate, inter_shp, inter_mapping)
  78. lm.save(silent=True, strict=True)
  79. Interstate.objects.all().delete()
  80. # This LayerMapping should work b/c `strict` is not set.
  81. lm = LayerMapping(Interstate, inter_shp, inter_mapping)
  82. lm.save(silent=True)
  83. # Two interstate should have imported correctly.
  84. self.assertEqual(2, Interstate.objects.count())
  85. # Verifying the values in the layer w/the model.
  86. ds = DataSource(inter_shp)
  87. # Only the first two features of this shapefile are valid.
  88. valid_feats = ds[0][:2]
  89. for feat in valid_feats:
  90. istate = Interstate.objects.get(name=feat['Name'].value)
  91. if feat.fid == 0:
  92. self.assertEqual(Decimal(str(feat['Length'])), istate.length)
  93. elif feat.fid == 1:
  94. # Everything but the first two decimal digits were truncated,
  95. # because the Interstate model's `length` field has decimal_places=2.
  96. self.assertAlmostEqual(feat.get('Length'), float(istate.length), 2)
  97. for p1, p2 in zip(feat.geom, istate.path):
  98. self.assertAlmostEqual(p1[0], p2[0], 6)
  99. self.assertAlmostEqual(p1[1], p2[1], 6)
  100. def county_helper(self, county_feat=True):
  101. "Helper function for ensuring the integrity of the mapped County models."
  102. for name, n, st in zip(NAMES, NUMS, STATES):
  103. # Should only be one record b/c of `unique` keyword.
  104. c = County.objects.get(name=name)
  105. self.assertEqual(n, len(c.mpoly))
  106. self.assertEqual(st, c.state.name) # Checking ForeignKey mapping.
  107. # Multiple records because `unique` was not set.
  108. if county_feat:
  109. qs = CountyFeat.objects.filter(name=name)
  110. self.assertEqual(n, qs.count())
  111. def test_layermap_unique_multigeometry_fk(self):
  112. "Testing the `unique`, and `transform`, geometry collection conversion, and ForeignKey mappings."
  113. # All the following should work.
  114. try:
  115. # Telling LayerMapping that we want no transformations performed on the data.
  116. lm = LayerMapping(County, co_shp, co_mapping, transform=False)
  117. # Specifying the source spatial reference system via the `source_srs` keyword.
  118. lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269)
  119. lm = LayerMapping(County, co_shp, co_mapping, source_srs='NAD83')
  120. # Unique may take tuple or string parameters.
  121. for arg in ('name', ('name', 'mpoly')):
  122. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg)
  123. except Exception:
  124. self.fail('No exception should be raised for proper use of keywords.')
  125. # Testing invalid params for the `unique` keyword.
  126. for e, arg in ((TypeError, 5.0), (ValueError, 'foobar'), (ValueError, ('name', 'mpolygon'))):
  127. self.assertRaises(e, LayerMapping, County, co_shp, co_mapping, transform=False, unique=arg)
  128. # No source reference system defined in the shapefile, should raise an error.
  129. if connection.features.supports_transform:
  130. self.assertRaises(LayerMapError, LayerMapping, County, co_shp, co_mapping)
  131. # Passing in invalid ForeignKey mapping parameters -- must be a dictionary
  132. # mapping for the model the ForeignKey points to.
  133. bad_fk_map1 = copy(co_mapping)
  134. bad_fk_map1['state'] = 'name'
  135. bad_fk_map2 = copy(co_mapping)
  136. bad_fk_map2['state'] = {'nombre': 'State'}
  137. self.assertRaises(TypeError, LayerMapping, County, co_shp, bad_fk_map1, transform=False)
  138. self.assertRaises(LayerMapError, LayerMapping, County, co_shp, bad_fk_map2, transform=False)
  139. # There exist no State models for the ForeignKey mapping to work -- should raise
  140. # a MissingForeignKey exception (this error would be ignored if the `strict`
  141. # keyword is not set).
  142. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name')
  143. self.assertRaises(MissingForeignKey, lm.save, silent=True, strict=True)
  144. # Now creating the state models so the ForeignKey mapping may work.
  145. State.objects.bulk_create([
  146. State(name='Colorado'), State(name='Hawaii'), State(name='Texas')
  147. ])
  148. # If a mapping is specified as a collection, all OGR fields that
  149. # are not collections will be converted into them. For example,
  150. # a Point column would be converted to MultiPoint. Other things being done
  151. # w/the keyword args:
  152. # `transform=False`: Specifies that no transform is to be done; this
  153. # has the effect of ignoring the spatial reference check (because the
  154. # county shapefile does not have implicit spatial reference info).
  155. #
  156. # `unique='name'`: Creates models on the condition that they have
  157. # unique county names; geometries from each feature however will be
  158. # appended to the geometry collection of the unique model. Thus,
  159. # all of the various islands in Honolulu county will be in in one
  160. # database record with a MULTIPOLYGON type.
  161. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name')
  162. lm.save(silent=True, strict=True)
  163. # A reference that doesn't use the unique keyword; a new database record will
  164. # created for each polygon.
  165. lm = LayerMapping(CountyFeat, co_shp, cofeat_mapping, transform=False)
  166. lm.save(silent=True, strict=True)
  167. # The county helper is called to ensure integrity of County models.
  168. self.county_helper()
  169. def test_test_fid_range_step(self):
  170. "Tests the `fid_range` keyword and the `step` keyword of .save()."
  171. # Function for clearing out all the counties before testing.
  172. def clear_counties():
  173. County.objects.all().delete()
  174. State.objects.bulk_create([
  175. State(name='Colorado'), State(name='Hawaii'), State(name='Texas')
  176. ])
  177. # Initializing the LayerMapping object to use in these tests.
  178. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name')
  179. # Bad feature id ranges should raise a type error.
  180. bad_ranges = (5.0, 'foo', co_shp)
  181. for bad in bad_ranges:
  182. self.assertRaises(TypeError, lm.save, fid_range=bad)
  183. # Step keyword should not be allowed w/`fid_range`.
  184. fr = (3, 5) # layer[3:5]
  185. self.assertRaises(LayerMapError, lm.save, fid_range=fr, step=10)
  186. lm.save(fid_range=fr)
  187. # Features IDs 3 & 4 are for Galveston County, Texas -- only
  188. # one model is returned because the `unique` keyword was set.
  189. qs = County.objects.all()
  190. self.assertEqual(1, qs.count())
  191. self.assertEqual('Galveston', qs[0].name)
  192. # Features IDs 5 and beyond for Honolulu County, Hawaii, and
  193. # FID 0 is for Pueblo County, Colorado.
  194. clear_counties()
  195. lm.save(fid_range=slice(5, None), silent=True, strict=True) # layer[5:]
  196. lm.save(fid_range=slice(None, 1), silent=True, strict=True) # layer[:1]
  197. # Only Pueblo & Honolulu counties should be present because of
  198. # the `unique` keyword. Have to set `order_by` on this QuerySet
  199. # or else MySQL will return a different ordering than the other dbs.
  200. qs = County.objects.order_by('name')
  201. self.assertEqual(2, qs.count())
  202. hi, co = tuple(qs)
  203. hi_idx, co_idx = tuple(map(NAMES.index, ('Honolulu', 'Pueblo')))
  204. self.assertEqual('Pueblo', co.name)
  205. self.assertEqual(NUMS[co_idx], len(co.mpoly))
  206. self.assertEqual('Honolulu', hi.name)
  207. self.assertEqual(NUMS[hi_idx], len(hi.mpoly))
  208. # Testing the `step` keyword -- should get the same counties
  209. # regardless of we use a step that divides equally, that is odd,
  210. # or that is larger than the dataset.
  211. for st in (4, 7, 1000):
  212. clear_counties()
  213. lm.save(step=st, strict=True)
  214. self.county_helper(county_feat=False)
  215. def test_model_inheritance(self):
  216. "Tests LayerMapping on inherited models. See #12093."
  217. icity_mapping = {'name': 'Name',
  218. 'population': 'Population',
  219. 'density': 'Density',
  220. 'point': 'POINT',
  221. 'dt': 'Created',
  222. }
  223. # Parent model has geometry field.
  224. lm1 = LayerMapping(ICity1, city_shp, icity_mapping)
  225. lm1.save()
  226. # Grandparent has geometry field.
  227. lm2 = LayerMapping(ICity2, city_shp, icity_mapping)
  228. lm2.save()
  229. self.assertEqual(6, ICity1.objects.count())
  230. self.assertEqual(3, ICity2.objects.count())
  231. def test_invalid_layer(self):
  232. "Tests LayerMapping on invalid geometries. See #15378."
  233. invalid_mapping = {'point': 'POINT'}
  234. lm = LayerMapping(Invalid, invalid_shp, invalid_mapping,
  235. source_srs=4326)
  236. lm.save(silent=True)
  237. def test_charfield_too_short(self):
  238. mapping = copy(city_mapping)
  239. mapping['name_short'] = 'Name'
  240. lm = LayerMapping(City, city_shp, mapping)
  241. with self.assertRaises(InvalidString):
  242. lm.save(silent=True, strict=True)
  243. def test_textfield(self):
  244. "Tests that String content fits also in a TextField"
  245. mapping = copy(city_mapping)
  246. mapping['name_txt'] = 'Name'
  247. lm = LayerMapping(City, city_shp, mapping)
  248. lm.save(silent=True, strict=True)
  249. self.assertEqual(City.objects.count(), 3)
  250. self.assertEqual(City.objects.get(name='Houston').name_txt, "Houston")
  251. def test_encoded_name(self):
  252. """ Test a layer containing utf-8-encoded name """
  253. city_shp = os.path.join(shp_path, 'ch-city', 'ch-city.shp')
  254. lm = LayerMapping(City, city_shp, city_mapping)
  255. lm.save(silent=True, strict=True)
  256. self.assertEqual(City.objects.count(), 1)
  257. self.assertEqual(City.objects.all()[0].name, "Zürich")
  258. class OtherRouter(object):
  259. def db_for_read(self, model, **hints):
  260. return 'other'
  261. def db_for_write(self, model, **hints):
  262. return self.db_for_read(model, **hints)
  263. def allow_relation(self, obj1, obj2, **hints):
  264. return None
  265. def allow_migrate(self, db, app_label, **hints):
  266. return True
  267. @skipUnless(HAS_GDAL, "LayerMapRouterTest needs GDAL support")
  268. @skipUnlessDBFeature("gis_enabled")
  269. @override_settings(DATABASE_ROUTERS=[OtherRouter()])
  270. class LayerMapRouterTest(TestCase):
  271. @unittest.skipUnless(len(settings.DATABASES) > 1, 'multiple databases required')
  272. def test_layermapping_default_db(self):
  273. lm = LayerMapping(City, city_shp, city_mapping)
  274. self.assertEqual(lm.using, 'other')