test_data.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. """
  2. This module has the mock object definitions used to hold reference geometry
  3. for the GEOS and GDAL tests.
  4. """
  5. import json
  6. import os
  7. from django.utils.functional import cached_property
  8. # Path where reference test data is located.
  9. TEST_DATA = os.path.join(os.path.dirname(__file__), 'data')
  10. def tuplize(seq):
  11. "Turn all nested sequences to tuples in given sequence."
  12. if isinstance(seq, (list, tuple)):
  13. return tuple(tuplize(i) for i in seq)
  14. return seq
  15. def strconvert(d):
  16. "Converts all keys in dictionary to str type."
  17. return {str(k): v for k, v in d.items()}
  18. def get_ds_file(name, ext):
  19. return os.path.join(TEST_DATA,
  20. name,
  21. name + '.%s' % ext
  22. )
  23. class TestObj:
  24. """
  25. Base testing object, turns keyword args into attributes.
  26. """
  27. def __init__(self, **kwargs):
  28. for key, value in kwargs.items():
  29. setattr(self, key, value)
  30. class TestDS(TestObj):
  31. """
  32. Object for testing GDAL data sources.
  33. """
  34. def __init__(self, name, *, ext='shp', **kwargs):
  35. # Shapefile is default extension, unless specified otherwise.
  36. self.ds = get_ds_file(name, ext)
  37. super().__init__(**kwargs)
  38. class TestGeom(TestObj):
  39. """
  40. Testing object used for wrapping reference geometry data
  41. in GEOS/GDAL tests.
  42. """
  43. def __init__(self, *, coords=None, centroid=None, ext_ring_cs=None, **kwargs):
  44. # Converting lists to tuples of certain keyword args
  45. # so coordinate test cases will match (JSON has no
  46. # concept of tuple).
  47. if coords:
  48. self.coords = tuplize(coords)
  49. if centroid:
  50. self.centroid = tuple(centroid)
  51. if ext_ring_cs:
  52. ext_ring_cs = tuplize(ext_ring_cs)
  53. self.ext_ring_cs = ext_ring_cs
  54. super().__init__(**kwargs)
  55. class TestGeomSet:
  56. """
  57. Each attribute of this object is a list of `TestGeom` instances.
  58. """
  59. def __init__(self, **kwargs):
  60. for key, value in kwargs.items():
  61. setattr(self, key, [TestGeom(**strconvert(kw)) for kw in value])
  62. class TestDataMixin:
  63. """
  64. Mixin used for GEOS/GDAL test cases that defines a `geometries`
  65. property, which returns and/or loads the reference geometry data.
  66. """
  67. @cached_property
  68. def geometries(self):
  69. # Load up the test geometry data from fixture into global.
  70. with open(os.path.join(TEST_DATA, 'geometries.json')) as f:
  71. geometries = json.load(f)
  72. return TestGeomSet(**strconvert(geometries))