Debian Codegraph @

tests/gis_tests/test_data.py

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