Debian Codegraph @

tests/unit/spec_tests/test_load_namespace.py

raw
1 import json
2 import os
3 import ruamel.yaml as yaml
4 from tempfile import gettempdir
5 import warnings
6
7 from hdmf.common import get_type_map
8 from hdmf.spec import AttributeSpec, DatasetSpec, GroupSpec, SpecNamespace, NamespaceCatalog, NamespaceBuilder
9 from hdmf.testing import TestCase, remove_test_file
10
11 from tests.unit.helpers.utils import CustomGroupSpec, CustomDatasetSpec, CustomSpecNamespace
12
13
14 class TestSpecLoad(TestCase):
15 NS_NAME = 'test_ns'
16
17 def setUp(self):
18 self.attributes = [
19 AttributeSpec('attribute1', 'my first attribute', 'text'),
20 AttributeSpec('attribute2', 'my second attribute', 'text')
21 ]
22 self.dset1_attributes = [
23 AttributeSpec('attribute3', 'my third attribute', 'text'),
24 AttributeSpec('attribute4', 'my fourth attribute', 'text')
25 ]
26 self.dset2_attributes = [
27 AttributeSpec('attribute5', 'my fifth attribute', 'text'),
28 AttributeSpec('attribute6', 'my sixth attribute', 'text')
29 ]
30 self.datasets = [
31 DatasetSpec('my first dataset',
32 'int',
33 name='dataset1',
34 attributes=self.dset1_attributes,
35 linkable=True),
36 DatasetSpec('my second dataset',
37 'int',
38 name='dataset2',
39 dims=(None, None),
40 attributes=self.dset2_attributes,
41 linkable=True,
42 data_type_def='VoltageArray')
43 ]
44 self.spec = GroupSpec('A test group',
45 name='root_constructor_datatype',
46 datasets=self.datasets,
47 attributes=self.attributes,
48 linkable=False,
49 data_type_def='EphysData')
50 dset1_attributes_ext = [
51 AttributeSpec('dset1_extra_attribute', 'an extra attribute for the first dataset', 'text')
52 ]
53 self.ext_datasets = [
54 DatasetSpec('my first dataset extension',
55 'int',
56 name='dataset1',
57 attributes=dset1_attributes_ext,
58 linkable=True),
59 ]
60 self.ext_attributes = [
61 AttributeSpec('ext_extra_attribute', 'an extra attribute for the group', 'text'),
62 ]
63 self.ext_spec = GroupSpec('A test group extension',
64 name='root_constructor_datatype',
65 datasets=self.ext_datasets,
66 attributes=self.ext_attributes,
67 linkable=False,
68 data_type_inc='EphysData',
69 data_type_def='SpikeData')
70 to_dump = {'groups': [self.spec, self.ext_spec]}
71 self.specs_path = 'test_load_namespace.specs.yaml'
72 self.namespace_path = 'test_load_namespace.namespace.yaml'
73 with open(self.specs_path, 'w') as tmp:
74 yaml_obj = yaml.YAML(typ='safe', pure=True)
75 yaml_obj.default_flow_style = False
76 yaml_obj.dump(json.loads(json.dumps(to_dump)), tmp)
77 ns_dict = {
78 'doc': 'a test namespace',
79 'name': self.NS_NAME,
80 'schema': [
81 {'source': self.specs_path}
82 ],
83 'version': '0.1.0'
84 }
85 self.namespace = SpecNamespace.build_namespace(**ns_dict)
86 to_dump = {'namespaces': [self.namespace]}
87 with open(self.namespace_path, 'w') as tmp:
88 yaml_obj = yaml.YAML(typ='safe', pure=True)
89 yaml_obj.default_flow_style = False
90 yaml_obj.dump(json.loads(json.dumps(to_dump)), tmp)
91 self.ns_catalog = NamespaceCatalog()
92
93 def tearDown(self):
94 if os.path.exists(self.namespace_path):
95 os.remove(self.namespace_path)
96 if os.path.exists(self.specs_path):
97 os.remove(self.specs_path)
98
99 def test_inherited_attributes(self):
100 self.ns_catalog.load_namespaces(self.namespace_path, resolve=True)
101 ts_spec = self.ns_catalog.get_spec(self.NS_NAME, 'EphysData')
102 es_spec = self.ns_catalog.get_spec(self.NS_NAME, 'SpikeData')
103 ts_attrs = {s.name for s in ts_spec.attributes}
104 es_attrs = {s.name for s in es_spec.attributes}
105 for attr in ts_attrs:
106 with self.subTest(attr=attr):
107 self.assertIn(attr, es_attrs)
108 # self.assertSetEqual(ts_attrs, es_attrs)
109 ts_dsets = {s.name for s in ts_spec.datasets}
110 es_dsets = {s.name for s in es_spec.datasets}
111 for dset in ts_dsets:
112 with self.subTest(dset=dset):
113 self.assertIn(dset, es_dsets)
114 # self.assertSetEqual(ts_dsets, es_dsets)
115
116 def test_inherited_attributes_not_resolved(self):
117 self.ns_catalog.load_namespaces(self.namespace_path, resolve=False)
118 es_spec = self.ns_catalog.get_spec(self.NS_NAME, 'SpikeData')
119 src_attrs = {s.name for s in self.ext_attributes}
120 ext_attrs = {s.name for s in es_spec.attributes}
121 self.assertSetEqual(src_attrs, ext_attrs)
122 src_dsets = {s.name for s in self.ext_datasets}
123 ext_dsets = {s.name for s in es_spec.datasets}
124 self.assertSetEqual(src_dsets, ext_dsets)
125
126
127 class TestSpecLoadEdgeCase(TestCase):
128
129 def setUp(self):
130 self.specs_path = 'test_load_namespace.specs.yaml'
131 self.namespace_path = 'test_load_namespace.namespace.yaml'
132
133 # write basically empty specs file
134 to_dump = {'groups': []}
135 with open(self.specs_path, 'w') as tmp:
136 yaml_obj = yaml.YAML(typ='safe', pure=True)
137 yaml_obj.default_flow_style = False
138 yaml_obj.dump(json.loads(json.dumps(to_dump)), tmp)
139
140 def tearDown(self):
141 remove_test_file(self.namespace_path)
142 remove_test_file(self.specs_path)
143
144 def test_build_namespace_missing_version(self):
145 """Test that building/creating a SpecNamespace without a version works but raises a warning."""
146 # create namespace without version key
147 ns_dict = {
148 'doc': 'a test namespace',
149 'name': 'test_ns',
150 'schema': [
151 {'source': self.specs_path}
152 ],
153 }
154 msg = ("Loaded namespace 'test_ns' is missing the required key 'version'. Version will be set to "
155 "'%s'. Please notify the extension author." % SpecNamespace.UNVERSIONED)
156 with self.assertWarnsWith(UserWarning, msg):
157 namespace = SpecNamespace.build_namespace(**ns_dict)
158
159 self.assertEqual(namespace.version, SpecNamespace.UNVERSIONED)
160
161 def test_load_namespace_none_version(self):
162 """Test that reading a namespace file without a version works but raises a warning."""
163 # create namespace with version key (remove it later)
164 ns_dict = {
165 'doc': 'a test namespace',
166 'name': 'test_ns',
167 'schema': [
168 {'source': self.specs_path}
169 ],
170 'version': '0.0.1'
171 }
172 namespace = SpecNamespace.build_namespace(**ns_dict)
173 namespace['version'] = None # work around lack of setter to remove version key
174
175 # write the namespace to file without version key
176 to_dump = {'namespaces': [namespace]}
177 with open(self.namespace_path, 'w') as tmp:
178 yaml_obj = yaml.YAML(typ='safe', pure=True)
179 yaml_obj.default_flow_style = False
180 yaml_obj.dump(json.loads(json.dumps(to_dump)), tmp)
181
182 # load the namespace from file
183 ns_catalog = NamespaceCatalog()
184 msg = ("Loaded namespace 'test_ns' is missing the required key 'version'. Version will be set to "
185 "'%s'. Please notify the extension author." % SpecNamespace.UNVERSIONED)
186 with self.assertWarnsWith(UserWarning, msg):
187 ns_catalog.load_namespaces(self.namespace_path)
188
189 self.assertEqual(ns_catalog.get_namespace('test_ns').version, SpecNamespace.UNVERSIONED)
190
191 def test_load_namespace_unversioned_version(self):
192 """Test that reading a namespace file with version=unversioned string works but raises a warning."""
193 # create namespace with version key (remove it later)
194 ns_dict = {
195 'doc': 'a test namespace',
196 'name': 'test_ns',
197 'schema': [
198 {'source': self.specs_path}
199 ],
200 'version': '0.0.1'
201 }
202 namespace = SpecNamespace.build_namespace(**ns_dict)
203 namespace['version'] = str(SpecNamespace.UNVERSIONED) # work around lack of setter to remove version key
204
205 # write the namespace to file without version key
206 to_dump = {'namespaces': [namespace]}
207 with open(self.namespace_path, 'w') as tmp:
208 yaml_obj = yaml.YAML(typ='safe', pure=True)
209 yaml_obj.default_flow_style = False
210 yaml_obj.dump(json.loads(json.dumps(to_dump)), tmp)
211
212 # load the namespace from file
213 ns_catalog = NamespaceCatalog()
214 msg = "Loaded namespace 'test_ns' is unversioned. Please notify the extension author."
215 with self.assertWarnsWith(UserWarning, msg):
216 ns_catalog.load_namespaces(self.namespace_path)
217
218 self.assertEqual(ns_catalog.get_namespace('test_ns').version, SpecNamespace.UNVERSIONED)
219
220 def test_missing_version_string(self):
221 """Test that the constant variable representing a missing version has not changed."""
222 self.assertIsNone(SpecNamespace.UNVERSIONED)
223
224 def test_get_namespace_missing_version(self):
225 """Test that SpecNamespace.version returns the constant for a missing version if version gets removed."""
226 # create namespace with version key (remove it later)
227 ns_dict = {
228 'doc': 'a test namespace',
229 'name': 'test_ns',
230 'schema': [
231 {'source': self.specs_path}
232 ],
233 'version': '0.0.1'
234 }
235 namespace = SpecNamespace.build_namespace(**ns_dict)
236 namespace['version'] = None # work around lack of setter to remove version key
237
238 self.assertEqual(namespace.version, SpecNamespace.UNVERSIONED)
239
240
241 class TestCatchDupNS(TestCase):
242
243 def setUp(self):
244 self.tempdir = gettempdir()
245 self.ext_source1 = 'extension1.yaml'
246 self.ns_path1 = 'namespace1.yaml'
247 self.ext_source2 = 'extension2.yaml'
248 self.ns_path2 = 'namespace2.yaml'
249
250 def tearDown(self):
251 for f in (self.ext_source1, self.ns_path1, self.ext_source2, self.ns_path2):
252 remove_test_file(os.path.join(self.tempdir, f))
253
254 def test_catch_dup_name(self):
255 ns_builder1 = NamespaceBuilder('Extension doc', "test_ext", version='0.1.0')
256 ns_builder1.add_spec(self.ext_source1, GroupSpec('doc', data_type_def='MyType'))
257 ns_builder1.export(self.ns_path1, outdir=self.tempdir)
258 ns_builder2 = NamespaceBuilder('Extension doc', "test_ext", version='0.2.0')
259 ns_builder2.add_spec(self.ext_source2, GroupSpec('doc', data_type_def='MyType'))
260 ns_builder2.export(self.ns_path2, outdir=self.tempdir)
261
262 ns_catalog = NamespaceCatalog()
263 ns_catalog.load_namespaces(os.path.join(self.tempdir, self.ns_path1))
264
265 msg = "Ignoring cached namespace 'test_ext' version 0.2.0 because version 0.1.0 is already loaded."
266 with self.assertWarnsRegex(UserWarning, msg):
267 ns_catalog.load_namespaces(os.path.join(self.tempdir, self.ns_path2))
268
269 def test_catch_dup_name_same_version(self):
270 ns_builder1 = NamespaceBuilder('Extension doc', "test_ext", version='0.1.0')
271 ns_builder1.add_spec(self.ext_source1, GroupSpec('doc', data_type_def='MyType'))
272 ns_builder1.export(self.ns_path1, outdir=self.tempdir)
273 ns_builder2 = NamespaceBuilder('Extension doc', "test_ext", version='0.1.0')
274 ns_builder2.add_spec(self.ext_source2, GroupSpec('doc', data_type_def='MyType'))
275 ns_builder2.export(self.ns_path2, outdir=self.tempdir)
276
277 ns_catalog = NamespaceCatalog()
278 ns_catalog.load_namespaces(os.path.join(self.tempdir, self.ns_path1))
279
280 # no warning should be raised (but don't just check for 0 warnings -- warnings can come from other sources)
281 msg = "Ignoring cached namespace 'test_ext' version 0.1.0 because version 0.1.0 is already loaded."
282 with warnings.catch_warnings(record=True) as ws:
283 ns_catalog.load_namespaces(os.path.join(self.tempdir, self.ns_path2))
284 for w in ws:
285 self.assertTrue(str(w) != msg)
286
287
288 class TestCustomSpecClasses(TestCase):
289
290 def setUp(self): # noqa: C901
291 self.ns_catalog = NamespaceCatalog(CustomGroupSpec, CustomDatasetSpec, CustomSpecNamespace)
292 hdmf_typemap = get_type_map()
293 self.ns_catalog.merge(hdmf_typemap.namespace_catalog)
294
295 def test_constructor_getters(self):
296 self.assertEqual(self.ns_catalog.dataset_spec_cls, CustomDatasetSpec)
297 self.assertEqual(self.ns_catalog.group_spec_cls, CustomGroupSpec)
298 self.assertEqual(self.ns_catalog.spec_namespace_cls, CustomSpecNamespace)
299
300 def test_load_namespaces(self):
301 namespace_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test.namespace.yaml')
302 namespace_deps = self.ns_catalog.load_namespaces(namespace_path)
303
304 # test that the dependencies are correct, including dependencies of the dependencies
305 expected = set(['Data', 'Container', 'DynamicTable', 'ElementIdentifiers', 'VectorData'])
306 self.assertSetEqual(set(namespace_deps['test']['hdmf-common']), expected)
307
308 # test that the types are loaded
309 types = self.ns_catalog.get_types('test.base.yaml')
310 expected = ('TestData', 'TestContainer', 'TestTable')
311 self.assertTupleEqual(types, expected)
312
313 # test that the namespace is correct and the types_key is updated for test ns
314 test_namespace = self.ns_catalog.get_namespace('test')
315 expected = {'doc': 'Test namespace',
316 'schema': [{'namespace': 'hdmf-common',
317 'my_data_types': ['Data', 'DynamicTable', 'Container']},
318 {'doc': 'This source module contains base data types.',
319 'source': 'test.base.yaml',
320 'title': 'Base data types'}],
321 'name': 'test',
322 'full_name': 'Test',
323 'version': '0.1.0',
324 'author': ['Test test'],
325 'contact': ['[email protected]']}
326 self.assertDictEqual(test_namespace, expected)
327
328 # test that the def_key is updated for test ns
329 test_data_spec = self.ns_catalog.get_spec('test', 'TestData')
330 self.assertTrue('my_data_type_def' in test_data_spec)
331 self.assertTrue('my_data_type_inc' in test_data_spec)
332
333 # test that the def_key is maintained for hdmf-common
334 data_spec = self.ns_catalog.get_spec('hdmf-common', 'Data')
335 self.assertTrue('data_type_def' in data_spec)
336
337 def test_load_namespaces_ext(self):
338 namespace_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test.namespace.yaml')
339 self.ns_catalog.load_namespaces(namespace_path)
340
341 ext_namespace_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test-ext.namespace.yaml')
342 ext_namespace_deps = self.ns_catalog.load_namespaces(ext_namespace_path)
343
344 # test that the dependencies are correct, including dependencies of the dependencies
345 expected_deps = set(['TestData', 'TestContainer', 'TestTable', 'Container', 'Data', 'DynamicTable',
346 'ElementIdentifiers', 'VectorData'])
347 self.assertSetEqual(set(ext_namespace_deps['test-ext']['test']), expected_deps)
348
349 def test_load_namespaces_bad_path(self):
350 namespace_path = 'test.namespace.yaml'
351 msg = "namespace file 'test.namespace.yaml' not found"
352 with self.assertRaisesWith(IOError, msg):
353 self.ns_catalog.load_namespaces(namespace_path)
354
355 def test_load_namespaces_twice(self):
356 namespace_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test.namespace.yaml')
357 namespace_deps1 = self.ns_catalog.load_namespaces(namespace_path)
358 namespace_deps2 = self.ns_catalog.load_namespaces(namespace_path)
359 self.assertDictEqual(namespace_deps1, namespace_deps2)