PageRenderTime 29ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/packages/django/contrib/gis/gdal/tests/test_ds.py

https://gitlab.com/gregtyka/Scryve-Webapp
Python | 233 lines | 146 code | 43 blank | 44 comment | 28 complexity | 414fd06554ea3818b139e83ffbc2e4a0 MD5 | raw file
  1. import os, os.path, unittest
  2. from django.contrib.gis.gdal import DataSource, Envelope, OGRGeometry, OGRException, OGRIndexError
  3. from django.contrib.gis.gdal.field import OFTReal, OFTInteger, OFTString
  4. from django.contrib import gis
  5. # Path for SHP files
  6. data_path = os.path.join(os.path.dirname(gis.__file__), 'tests' + os.sep + 'data')
  7. def get_ds_file(name, ext):
  8. return os.sep.join([data_path, name, name + '.%s' % ext])
  9. # Test SHP data source object
  10. class TestDS:
  11. def __init__(self, name, **kwargs):
  12. ext = kwargs.pop('ext', 'shp')
  13. self.ds = get_ds_file(name, ext)
  14. for key, value in kwargs.items():
  15. setattr(self, key, value)
  16. # List of acceptable data sources.
  17. ds_list = (TestDS('test_point', nfeat=5, nfld=3, geom='POINT', gtype=1, driver='ESRI Shapefile',
  18. fields={'dbl' : OFTReal, 'int' : OFTInteger, 'str' : OFTString,},
  19. extent=(-1.35011,0.166623,-0.524093,0.824508), # Got extent from QGIS
  20. srs_wkt='GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]',
  21. field_values={'dbl' : [float(i) for i in range(1, 6)], 'int' : range(1, 6), 'str' : [str(i) for i in range(1, 6)]},
  22. fids=range(5)),
  23. TestDS('test_vrt', ext='vrt', nfeat=3, nfld=3, geom='POINT', gtype='Point25D', driver='VRT',
  24. fields={'POINT_X' : OFTString, 'POINT_Y' : OFTString, 'NUM' : OFTString}, # VRT uses CSV, which all types are OFTString.
  25. extent=(1.0, 2.0, 100.0, 523.5), # Min/Max from CSV
  26. field_values={'POINT_X' : ['1.0', '5.0', '100.0'], 'POINT_Y' : ['2.0', '23.0', '523.5'], 'NUM' : ['5', '17', '23']},
  27. fids=range(1,4)),
  28. TestDS('test_poly', nfeat=3, nfld=3, geom='POLYGON', gtype=3,
  29. driver='ESRI Shapefile',
  30. fields={'float' : OFTReal, 'int' : OFTInteger, 'str' : OFTString,},
  31. extent=(-1.01513,-0.558245,0.161876,0.839637), # Got extent from QGIS
  32. srs_wkt='GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]'),
  33. )
  34. bad_ds = (TestDS('foo'),
  35. )
  36. class DataSourceTest(unittest.TestCase):
  37. def test01_valid_shp(self):
  38. "Testing valid SHP Data Source files."
  39. for source in ds_list:
  40. # Loading up the data source
  41. ds = DataSource(source.ds)
  42. # Making sure the layer count is what's expected (only 1 layer in a SHP file)
  43. self.assertEqual(1, len(ds))
  44. # Making sure GetName works
  45. self.assertEqual(source.ds, ds.name)
  46. # Making sure the driver name matches up
  47. self.assertEqual(source.driver, str(ds.driver))
  48. # Making sure indexing works
  49. try:
  50. ds[len(ds)]
  51. except OGRIndexError:
  52. pass
  53. else:
  54. self.fail('Expected an IndexError!')
  55. def test02_invalid_shp(self):
  56. "Testing invalid SHP files for the Data Source."
  57. for source in bad_ds:
  58. self.assertRaises(OGRException, DataSource, source.ds)
  59. def test03a_layers(self):
  60. "Testing Data Source Layers."
  61. print "\nBEGIN - expecting out of range feature id error; safe to ignore.\n"
  62. for source in ds_list:
  63. ds = DataSource(source.ds)
  64. # Incrementing through each layer, this tests DataSource.__iter__
  65. for layer in ds:
  66. # Making sure we get the number of features we expect
  67. self.assertEqual(len(layer), source.nfeat)
  68. # Making sure we get the number of fields we expect
  69. self.assertEqual(source.nfld, layer.num_fields)
  70. self.assertEqual(source.nfld, len(layer.fields))
  71. # Testing the layer's extent (an Envelope), and it's properties
  72. self.assertEqual(True, isinstance(layer.extent, Envelope))
  73. self.assertAlmostEqual(source.extent[0], layer.extent.min_x, 5)
  74. self.assertAlmostEqual(source.extent[1], layer.extent.min_y, 5)
  75. self.assertAlmostEqual(source.extent[2], layer.extent.max_x, 5)
  76. self.assertAlmostEqual(source.extent[3], layer.extent.max_y, 5)
  77. # Now checking the field names.
  78. flds = layer.fields
  79. for f in flds: self.assertEqual(True, f in source.fields)
  80. # Negative FIDs are not allowed.
  81. self.assertRaises(OGRIndexError, layer.__getitem__, -1)
  82. self.assertRaises(OGRIndexError, layer.__getitem__, 50000)
  83. if hasattr(source, 'field_values'):
  84. fld_names = source.field_values.keys()
  85. # Testing `Layer.get_fields` (which uses Layer.__iter__)
  86. for fld_name in fld_names:
  87. self.assertEqual(source.field_values[fld_name], layer.get_fields(fld_name))
  88. # Testing `Layer.__getitem__`.
  89. for i, fid in enumerate(source.fids):
  90. feat = layer[fid]
  91. self.assertEqual(fid, feat.fid)
  92. # Maybe this should be in the test below, but we might as well test
  93. # the feature values here while in this loop.
  94. for fld_name in fld_names:
  95. self.assertEqual(source.field_values[fld_name][i], feat.get(fld_name))
  96. print "\nEND - expecting out of range feature id error; safe to ignore."
  97. def test03b_layer_slice(self):
  98. "Test indexing and slicing on Layers."
  99. # Using the first data-source because the same slice
  100. # can be used for both the layer and the control values.
  101. source = ds_list[0]
  102. ds = DataSource(source.ds)
  103. sl = slice(1, 3)
  104. feats = ds[0][sl]
  105. for fld_name in ds[0].fields:
  106. test_vals = [feat.get(fld_name) for feat in feats]
  107. control_vals = source.field_values[fld_name][sl]
  108. self.assertEqual(control_vals, test_vals)
  109. def test03c_layer_references(self):
  110. "Test to make sure Layer access is still available without the DataSource."
  111. source = ds_list[0]
  112. # See ticket #9448.
  113. def get_layer():
  114. # This DataSource object is not accessible outside this
  115. # scope. However, a reference should still be kept alive
  116. # on the `Layer` returned.
  117. ds = DataSource(source.ds)
  118. return ds[0]
  119. # Making sure we can call OGR routines on the Layer returned.
  120. lyr = get_layer()
  121. self.assertEqual(source.nfeat, len(lyr))
  122. self.assertEqual(source.gtype, lyr.geom_type.num)
  123. def test04_features(self):
  124. "Testing Data Source Features."
  125. for source in ds_list:
  126. ds = DataSource(source.ds)
  127. # Incrementing through each layer
  128. for layer in ds:
  129. # Incrementing through each feature in the layer
  130. for feat in layer:
  131. # Making sure the number of fields, and the geometry type
  132. # are what's expected.
  133. self.assertEqual(source.nfld, len(list(feat)))
  134. self.assertEqual(source.gtype, feat.geom_type)
  135. # Making sure the fields match to an appropriate OFT type.
  136. for k, v in source.fields.items():
  137. # Making sure we get the proper OGR Field instance, using
  138. # a string value index for the feature.
  139. self.assertEqual(True, isinstance(feat[k], v))
  140. # Testing Feature.__iter__
  141. for fld in feat: self.assertEqual(True, fld.name in source.fields.keys())
  142. def test05_geometries(self):
  143. "Testing Geometries from Data Source Features."
  144. for source in ds_list:
  145. ds = DataSource(source.ds)
  146. # Incrementing through each layer and feature.
  147. for layer in ds:
  148. for feat in layer:
  149. g = feat.geom
  150. # Making sure we get the right Geometry name & type
  151. self.assertEqual(source.geom, g.geom_name)
  152. self.assertEqual(source.gtype, g.geom_type)
  153. # Making sure the SpatialReference is as expected.
  154. if hasattr(source, 'srs_wkt'):
  155. self.assertEqual(source.srs_wkt, g.srs.wkt)
  156. def test06_spatial_filter(self):
  157. "Testing the Layer.spatial_filter property."
  158. ds = DataSource(get_ds_file('cities', 'shp'))
  159. lyr = ds[0]
  160. # When not set, it should be None.
  161. self.assertEqual(None, lyr.spatial_filter)
  162. # Must be set a/an OGRGeometry or 4-tuple.
  163. self.assertRaises(TypeError, lyr._set_spatial_filter, 'foo')
  164. # Setting the spatial filter with a tuple/list with the extent of
  165. # a buffer centering around Pueblo.
  166. self.assertRaises(ValueError, lyr._set_spatial_filter, range(5))
  167. filter_extent = (-105.609252, 37.255001, -103.609252, 39.255001)
  168. lyr.spatial_filter = (-105.609252, 37.255001, -103.609252, 39.255001)
  169. self.assertEqual(OGRGeometry.from_bbox(filter_extent), lyr.spatial_filter)
  170. feats = [feat for feat in lyr]
  171. self.assertEqual(1, len(feats))
  172. self.assertEqual('Pueblo', feats[0].get('Name'))
  173. # Setting the spatial filter with an OGRGeometry for buffer centering
  174. # around Houston.
  175. filter_geom = OGRGeometry('POLYGON((-96.363151 28.763374,-94.363151 28.763374,-94.363151 30.763374,-96.363151 30.763374,-96.363151 28.763374))')
  176. lyr.spatial_filter = filter_geom
  177. self.assertEqual(filter_geom, lyr.spatial_filter)
  178. feats = [feat for feat in lyr]
  179. self.assertEqual(1, len(feats))
  180. self.assertEqual('Houston', feats[0].get('Name'))
  181. # Clearing the spatial filter by setting it to None. Now
  182. # should indicate that there are 3 features in the Layer.
  183. lyr.spatial_filter = None
  184. self.assertEqual(3, len(lyr))
  185. def suite():
  186. s = unittest.TestSuite()
  187. s.addTest(unittest.makeSuite(DataSourceTest))
  188. return s
  189. def run(verbosity=2):
  190. unittest.TextTestRunner(verbosity=verbosity).run(suite())