Debian Codegraph @

tests/unit/build_tests/test_io_map.py

raw
1 from hdmf.utils import StrDataset, docval, getargs
2 from hdmf import Container, Data
3 from hdmf.backends.hdf5 import H5DataIO
4 from hdmf.build import (GroupBuilder, DatasetBuilder, ObjectMapper, BuildManager, TypeMap, LinkBuilder,
5 ReferenceBuilder, MissingRequiredBuildWarning, OrphanContainerBuildError,
6 ContainerConfigurationError)
7 from hdmf.spec import (GroupSpec, AttributeSpec, DatasetSpec, SpecCatalog, SpecNamespace, NamespaceCatalog, RefSpec,
8 LinkSpec)
9 from hdmf.testing import TestCase
10 import h5py
11 from abc import ABCMeta, abstractmethod
12 import unittest
13 import numpy as np
14
15 from tests.unit.helpers.utils import CORE_NAMESPACE, create_test_type_map
16
17 H5PY_3 = h5py.__version__.startswith('3')
18
19
20 class Bar(Container):
21
22 @docval({'name': 'name', 'type': str, 'doc': 'the name of this Bar'},
23 {'name': 'data', 'type': ('data', 'array_data'), 'doc': 'some data'},
24 {'name': 'attr1', 'type': str, 'doc': 'an attribute'},
25 {'name': 'attr2', 'type': int, 'doc': 'another attribute'},
26 {'name': 'attr3', 'type': float, 'doc': 'a third attribute', 'default': 3.14},
27 {'name': 'attr_array', 'type': 'array_data', 'doc': 'another attribute', 'default': (1, 2, 3)},
28 {'name': 'foo', 'type': 'Foo', 'doc': 'a group', 'default': None})
29 def __init__(self, **kwargs):
30 name, data, attr1, attr2, attr3, attr_array, foo = getargs('name', 'data', 'attr1', 'attr2', 'attr3',
31 'attr_array', 'foo', kwargs)
32 super().__init__(name=name)
33 self.__data = data
34 self.__attr1 = attr1
35 self.__attr2 = attr2
36 self.__attr3 = attr3
37 self.__attr_array = attr_array
38 self.__foo = foo
39 if self.__foo is not None and self.__foo.parent is None:
40 self.__foo.parent = self
41
42 def __eq__(self, other):
43 attrs = ('name', 'data', 'attr1', 'attr2', 'attr3', 'attr_array', 'foo')
44 return all(getattr(self, a) == getattr(other, a) for a in attrs)
45
46 def __str__(self):
47 attrs = ('name', 'data', 'attr1', 'attr2', 'attr3', 'attr_array', 'foo')
48 return ','.join('%s=%s' % (a, getattr(self, a)) for a in attrs)
49
50 @property
51 def data_type(self):
52 return 'Bar'
53
54 @property
55 def data(self):
56 return self.__data
57
58 @property
59 def attr1(self):
60 return self.__attr1
61
62 @property
63 def attr2(self):
64 return self.__attr2
65
66 @property
67 def attr3(self):
68 return self.__attr3
69
70 @property
71 def attr_array(self):
72 return self.__attr_array
73
74 @property
75 def foo(self):
76 return self.__foo
77
78 def remove_foo(self):
79 if self is self.__foo.parent:
80 self._remove_child(self.__foo)
81
82
83 class SubBar(Bar):
84 pass
85
86
87 class Foo(Container):
88
89 @property
90 def data_type(self):
91 return 'Foo'
92
93
94 class FooData(Data):
95
96 @property
97 def data_type(self):
98 return 'FooData'
99
100
101 class TestGetSubSpec(TestCase):
102
103 def setUp(self):
104 self.bar_spec = GroupSpec(doc='A test group specification with a data type', data_type_def='Bar')
105 self.sub_bar_spec = GroupSpec(
106 doc='A test group specification with a data type',
107 data_type_def='SubBar',
108 data_type_inc='Bar'
109 )
110 self.type_map = create_test_type_map([self.bar_spec, self.sub_bar_spec], {'Bar': Bar, 'SubBar': SubBar})
111
112 def test_bad_name(self):
113 """Test get_subspec on a builder that doesn't map to the spec."""
114 parent_spec = GroupSpec(doc='Empty group', name='bar_bucket')
115 sub_builder = GroupBuilder(
116 name='my_bar',
117 attributes={
118 'data_type': 'Bar',
119 'namespace': CORE_NAMESPACE,
120 'object_id': -1
121 }
122 )
123 GroupBuilder(name='bar_bucket', groups={'my_bar': sub_builder}) # add sub_builder as a child to bar_bucket
124 result = self.type_map.get_subspec(parent_spec, sub_builder)
125 self.assertIsNone(result)
126
127 def test_bad_name_no_data_type(self):
128 """Test get_subspec on a builder without a data type that doesn't map to the spec."""
129 parent_spec = GroupSpec(doc='Empty group', name='bar_bucket')
130 sub_builder = GroupBuilder(name='my_bar')
131 GroupBuilder(name='bar_bucket', groups={'my_bar': sub_builder}) # add sub_builder as a child to bar_bucket
132 result = self.type_map.get_subspec(parent_spec, sub_builder)
133 self.assertIsNone(result)
134
135 def test_unnamed_group_data_type_def(self):
136 """Test get_subspec on a builder that maps to an unnamed subgroup of the given spec using data_type_def."""
137 parent_spec = GroupSpec(
138 doc='Something to hold a Bar',
139 name='bar_bucket',
140 groups=[self.bar_spec] # using data_type_def, no name
141 )
142 sub_builder = GroupBuilder(
143 name='my_bar',
144 attributes={
145 'data_type': 'Bar',
146 'namespace': CORE_NAMESPACE,
147 'object_id': -1
148 }
149 )
150 GroupBuilder(name='bar_bucket', groups={'my_bar': sub_builder}) # add sub_builder as a child to bar_bucket
151 result = self.type_map.get_subspec(parent_spec, sub_builder)
152 self.assertIs(result, self.bar_spec)
153
154 def test_unnamed_group_data_type_inc(self):
155 """Test get_subspec on a builder that maps to an unnamed subgroup of the given spec using data_type_inc."""
156 inc_spec = GroupSpec(
157 doc='This Bar',
158 data_type_inc='Bar'
159 )
160 parent_spec = GroupSpec(
161 doc='Something to hold a Bar',
162 name='bar_bucket',
163 groups=[inc_spec] # using data_type_inc
164 )
165 sub_builder = GroupBuilder(
166 name='my_bar',
167 attributes={
168 'data_type': 'Bar',
169 'namespace': CORE_NAMESPACE,
170 'object_id': -1
171 }
172 )
173 GroupBuilder(name='bar_bucket', groups={'my_bar': sub_builder}) # add sub_builder as a child to bar_bucket
174 result = self.type_map.get_subspec(parent_spec, sub_builder)
175 self.assertIs(result, inc_spec)
176
177 def test_named_group(self):
178 """Test get_subspec on a builder that maps to a named subgroup of the given spec."""
179 # NOTE this works despite the fact that child_spec has no data type but the builder has a data type because
180 # get_subspec acts on the name and not necessarily the data type
181 child_spec = GroupSpec(doc='A test group specification', name='my_subgroup')
182 parent_spec = GroupSpec(doc='Something to hold a Bar', name='my_group', groups=[child_spec])
183 sub_builder = GroupBuilder(
184 name='my_subgroup',
185 attributes={
186 'data_type': 'Bar',
187 'namespace': CORE_NAMESPACE,
188 'object_id': -1
189 }
190 )
191 GroupBuilder(name='my_group', groups={'my_bar': sub_builder}) # add sub_builder as a child to my_group
192 result = self.type_map.get_subspec(parent_spec, sub_builder)
193 self.assertIs(result, child_spec)
194
195 def test_named_dataset(self):
196 """Test get_subspec on a builder that maps to a named dataset of the given spec."""
197 # NOTE this works despite the fact that child_spec has no data type but the builder has a data type because
198 # get_subspec acts on the name and not necessarily the data type
199 child_spec = DatasetSpec(doc='A test dataset specification', name='my_dataset')
200 parent_spec = GroupSpec(doc='Something to hold a Bar', name='my_group', datasets=[child_spec])
201 sub_builder = DatasetBuilder(
202 name='my_dataset',
203 data=[],
204 attributes={
205 'data_type': 'FooData',
206 'namespace': CORE_NAMESPACE,
207 'object_id': -1
208 }
209 )
210 GroupBuilder(name='my_group', datasets={'my_dataset': sub_builder}) # add sub_builder as a child to my_group
211 result = self.type_map.get_subspec(parent_spec, sub_builder)
212 self.assertIs(result, child_spec)
213
214 def test_unnamed_link_data_type_inc(self):
215 """Test get_subspec on a builder that maps to an unnamed link."""
216 link_spec = LinkSpec(doc='This Bar', target_type='Bar')
217 parent_spec = GroupSpec(
218 doc='Something to hold a Bar',
219 name='bar_bucket',
220 links=[link_spec]
221 )
222 bar_builder = GroupBuilder(
223 name='my_bar',
224 attributes={
225 'data_type': 'Bar',
226 'namespace': CORE_NAMESPACE,
227 'object_id': -1
228 }
229 )
230 sub_builder = LinkBuilder(builder=bar_builder, name='my_link')
231 GroupBuilder(name='bar_bucket', links={'my_bar': sub_builder})
232 result = self.type_map.get_subspec(parent_spec, sub_builder)
233 self.assertIs(result, link_spec)
234
235 def test_named_link_data_type_inc(self):
236 """Test get_subspec on a builder that maps to an named link."""
237 link_spec = LinkSpec(doc='This Bar', target_type='Bar', name='bar_link')
238 parent_spec = GroupSpec(
239 doc='Something to hold a Bar',
240 name='bar_bucket',
241 links=[link_spec]
242 )
243 bar_builder = GroupBuilder(
244 name='my_bar',
245 attributes={
246 'data_type': 'Bar',
247 'namespace': CORE_NAMESPACE,
248 'object_id': -1
249 }
250 )
251 sub_builder = LinkBuilder(builder=bar_builder, name='bar_link')
252 GroupBuilder(name='bar_bucket', links={'my_bar': sub_builder})
253 result = self.type_map.get_subspec(parent_spec, sub_builder)
254 self.assertIs(result, link_spec)
255
256 def test_named_link_hierarchy_data_type_inc(self):
257 """Test get_subspec on a builder that maps to an named link."""
258 link_spec = LinkSpec(doc='This Bar', target_type='Bar', name='bar_link')
259 parent_spec = GroupSpec(
260 doc='Something to hold a Bar',
261 name='bar_bucket',
262 links=[link_spec]
263 )
264 bar_builder = GroupBuilder(
265 name='my_bar',
266 attributes={
267 'data_type': 'SubBar',
268 'namespace': CORE_NAMESPACE,
269 'object_id': -1
270 }
271 )
272 sub_builder = LinkBuilder(builder=bar_builder, name='bar_link')
273 GroupBuilder(name='bar_bucket', links={'my_bar': sub_builder})
274 result = self.type_map.get_subspec(parent_spec, sub_builder)
275 self.assertIs(result, link_spec)
276
277
278 class TestTypeMap(TestCase):
279
280 def setUp(self):
281 self.bar_spec = GroupSpec('A test group specification with a data type', data_type_def='Bar')
282 self.foo_spec = GroupSpec('A test group specification with data type Foo', data_type_def='Foo')
283 self.spec_catalog = SpecCatalog()
284 self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
285 self.spec_catalog.register_spec(self.foo_spec, 'test.yaml')
286 self.namespace = SpecNamespace('a test namespace', CORE_NAMESPACE, [{'source': 'test.yaml'}],
287 version='0.1.0',
288 catalog=self.spec_catalog)
289 self.namespace_catalog = NamespaceCatalog()
290 self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
291 self.type_map = TypeMap(self.namespace_catalog)
292 self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
293 self.type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo)
294
295 def test_get_map_unique_mappers(self):
296 bar_inst = Bar('my_bar', list(range(10)), 'value1', 10)
297 foo_inst = Foo(name='my_foo')
298 bar_mapper = self.type_map.get_map(bar_inst)
299 foo_mapper = self.type_map.get_map(foo_inst)
300 self.assertIsNot(bar_mapper, foo_mapper)
301
302 def test_get_map(self):
303 container_inst = Bar('my_bar', list(range(10)), 'value1', 10)
304 mapper = self.type_map.get_map(container_inst)
305 self.assertIsInstance(mapper, ObjectMapper)
306 self.assertIs(mapper.spec, self.bar_spec)
307 mapper2 = self.type_map.get_map(container_inst)
308 self.assertIs(mapper, mapper2)
309
310 def test_get_map_register(self):
311 class MyMap(ObjectMapper):
312 pass
313 self.type_map.register_map(Bar, MyMap)
314
315 container_inst = Bar('my_bar', list(range(10)), 'value1', 10)
316 mapper = self.type_map.get_map(container_inst)
317 self.assertIs(mapper.spec, self.bar_spec)
318 self.assertIsInstance(mapper, MyMap)
319
320
321 class BarMapper(ObjectMapper):
322 def __init__(self, spec):
323 super().__init__(spec)
324 data_spec = spec.get_dataset('data')
325 self.map_spec('attr2', data_spec.get_attribute('attr2'))
326
327
328 class TestMapStrings(TestCase):
329
330 def customSetUp(self, bar_spec):
331 spec_catalog = SpecCatalog()
332 spec_catalog.register_spec(bar_spec, 'test.yaml')
333 namespace = SpecNamespace('a test namespace', CORE_NAMESPACE, [{'source': 'test.yaml'}], version='0.1.0',
334 catalog=spec_catalog)
335 namespace_catalog = NamespaceCatalog()
336 namespace_catalog.add_namespace(CORE_NAMESPACE, namespace)
337 type_map = TypeMap(namespace_catalog)
338 type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
339 return type_map
340
341 def test_build_1d(self):
342 bar_spec = GroupSpec('A test group specification with a data type',
343 data_type_def='Bar',
344 datasets=[DatasetSpec('an example dataset', 'text', name='data', shape=(None,),
345 attributes=[AttributeSpec(
346 'attr2', 'an example integer attribute', 'int')])],
347 attributes=[AttributeSpec('attr1', 'an example string attribute', 'text'),
348 AttributeSpec('attr_array', 'an example array attribute', 'text',
349 shape=(None,))])
350 type_map = self.customSetUp(bar_spec)
351 type_map.register_map(Bar, BarMapper)
352 bar_inst = Bar('my_bar', ['a', 'b', 'c', 'd'], 'value1', 10, attr_array=['a', 'b', 'c', 'd'])
353 builder = type_map.build(bar_inst)
354 np.testing.assert_array_equal(builder.get('data').data, np.array(['a', 'b', 'c', 'd']))
355 np.testing.assert_array_equal(builder.get('attr_array'), np.array(['a', 'b', 'c', 'd']))
356
357 def test_build_scalar(self):
358 bar_spec = GroupSpec('A test group specification with a data type',
359 data_type_def='Bar',
360 datasets=[DatasetSpec('an example dataset', 'text', name='data',
361 attributes=[AttributeSpec(
362 'attr2', 'an example integer attribute', 'int')])],
363 attributes=[AttributeSpec('attr1', 'an example string attribute', 'text')])
364 type_map = self.customSetUp(bar_spec)
365 type_map.register_map(Bar, BarMapper)
366 bar_inst = Bar('my_bar', ['a', 'b', 'c', 'd'], 'value1', 10)
367 builder = type_map.build(bar_inst)
368 self.assertEqual(builder.get('data').data, "['a', 'b', 'c', 'd']")
369
370 def test_build_2d_lol(self):
371 bar_spec = GroupSpec(
372 doc='A test group specification with a data type',
373 data_type_def='Bar',
374 datasets=[
375 DatasetSpec(
376 doc='an example dataset',
377 dtype='text',
378 name='data',
379 shape=(None, None),
380 attributes=[AttributeSpec(name='attr2', doc='an example integer attribute', dtype='int')],
381 )
382 ],
383 attributes=[AttributeSpec(name='attr_array', doc='an example array attribute', dtype='text',
384 shape=(None, None))],
385 )
386 type_map = self.customSetUp(bar_spec)
387 type_map.register_map(Bar, BarMapper)
388 str_lol_2d = [['aa', 'bb'], ['cc', 'dd']]
389 bar_inst = Bar('my_bar', str_lol_2d, 'value1', 10, attr_array=str_lol_2d)
390 builder = type_map.build(bar_inst)
391 self.assertEqual(builder.get('data').data, str_lol_2d)
392 self.assertEqual(builder.get('attr_array'), str_lol_2d)
393
394 def test_build_2d_ndarray(self):
395 bar_spec = GroupSpec(
396 doc='A test group specification with a data type',
397 data_type_def='Bar',
398 datasets=[
399 DatasetSpec(
400 doc='an example dataset',
401 dtype='text',
402 name='data',
403 shape=(None, None),
404 attributes=[AttributeSpec(name='attr2', doc='an example integer attribute', dtype='int')],
405 )
406 ],
407 attributes=[AttributeSpec(name='attr_array', doc='an example array attribute', dtype='text',
408 shape=(None, None))],
409 )
410 type_map = self.customSetUp(bar_spec)
411 type_map.register_map(Bar, BarMapper)
412 str_array_2d = np.array([['aa', 'bb'], ['cc', 'dd']])
413 bar_inst = Bar('my_bar', str_array_2d, 'value1', 10, attr_array=str_array_2d)
414 builder = type_map.build(bar_inst)
415 np.testing.assert_array_equal(builder.get('data').data, str_array_2d)
416 np.testing.assert_array_equal(builder.get('attr_array'), str_array_2d)
417
418 def test_build_3d_lol(self):
419 bar_spec = GroupSpec(
420 doc='A test group specification with a data type',
421 data_type_def='Bar',
422 datasets=[
423 DatasetSpec(
424 doc='an example dataset',
425 dtype='text',
426 name='data',
427 shape=(None, None, None),
428 attributes=[AttributeSpec(name='attr2', doc='an example integer attribute', dtype='int')],
429 )
430 ],
431 attributes=[AttributeSpec(name='attr_array', doc='an example array attribute', dtype='text',
432 shape=(None, None, None))],
433 )
434 type_map = self.customSetUp(bar_spec)
435 type_map.register_map(Bar, BarMapper)
436 str_lol_3d = [[['aa', 'bb'], ['cc', 'dd']], [['ee', 'ff'], ['gg', 'hh']]]
437 bar_inst = Bar('my_bar', str_lol_3d, 'value1', 10, attr_array=str_lol_3d)
438 builder = type_map.build(bar_inst)
439 self.assertEqual(builder.get('data').data, str_lol_3d)
440 self.assertEqual(builder.get('attr_array'), str_lol_3d)
441
442 def test_build_3d_ndarray(self):
443 bar_spec = GroupSpec(
444 doc='A test group specification with a data type',
445 data_type_def='Bar',
446 datasets=[
447 DatasetSpec(
448 doc='an example dataset',
449 dtype='text',
450 name='data',
451 shape=(None, None, None),
452 attributes=[AttributeSpec(name='attr2', doc='an example integer attribute', dtype='int')],
453 )
454 ],
455 attributes=[AttributeSpec(name='attr_array', doc='an example array attribute', dtype='text',
456 shape=(None, None, None))],
457 )
458 type_map = self.customSetUp(bar_spec)
459 type_map.register_map(Bar, BarMapper)
460 str_array_3d = np.array([[['aa', 'bb'], ['cc', 'dd']], [['ee', 'ff'], ['gg', 'hh']]])
461 bar_inst = Bar('my_bar', str_array_3d, 'value1', 10, attr_array=str_array_3d)
462 builder = type_map.build(bar_inst)
463 np.testing.assert_array_equal(builder.get('data').data, str_array_3d)
464 np.testing.assert_array_equal(builder.get('attr_array'), str_array_3d)
465
466 @unittest.skipIf(not H5PY_3, "Use StrDataset only for h5py 3+")
467 def test_build_1d_h5py_3_dataset(self):
468 bar_spec = GroupSpec(
469 doc='A test group specification with a data type',
470 data_type_def='Bar',
471 datasets=[
472 DatasetSpec(
473 doc='an example dataset',
474 dtype='text',
475 name='data',
476 shape=(None, ),
477 attributes=[AttributeSpec(name='attr2', doc='an example integer attribute', dtype='int')],
478 )
479 ],
480 attributes=[AttributeSpec(name='attr_array', doc='an example array attribute', dtype='text',
481 shape=(None, ))],
482 )
483 type_map = self.customSetUp(bar_spec)
484 type_map.register_map(Bar, BarMapper)
485 # create in-memory hdf5 file that is discarded after closing
486 with h5py.File("test.h5", "w", driver="core", backing_store=False) as f:
487 str_array_1d = np.array(
488 ['aa', 'bb', 'cc', 'dd'],
489 dtype=h5py.special_dtype(vlen=str)
490 )
491 # wrap the dataset in a StrDataset to mimic how HDF5IO would read this dataset with h5py 3+
492 dataset = StrDataset(f.create_dataset('data', data=str_array_1d), None)
493 bar_inst = Bar('my_bar', dataset, 'value1', 10, attr_array=dataset)
494 builder = type_map.build(bar_inst)
495 np.testing.assert_array_equal(builder.get('data').data, dataset[:])
496 np.testing.assert_array_equal(builder.get('attr_array'), dataset[:])
497
498 @unittest.skipIf(not H5PY_3, "Use StrDataset only for h5py 3+")
499 def test_build_3d_h5py_3_dataset(self):
500 bar_spec = GroupSpec(
501 doc='A test group specification with a data type',
502 data_type_def='Bar',
503 datasets=[
504 DatasetSpec(
505 doc='an example dataset',
506 dtype='text',
507 name='data',
508 shape=(None, None, None),
509 attributes=[AttributeSpec(name='attr2', doc='an example integer attribute', dtype='int')],
510 )
511 ],
512 attributes=[AttributeSpec(name='attr_array', doc='an example array attribute', dtype='text',
513 shape=(None, None, None))],
514 )
515 type_map = self.customSetUp(bar_spec)
516 type_map.register_map(Bar, BarMapper)
517 # create in-memory hdf5 file that is discarded after closing
518 with h5py.File("test.h5", "w", driver="core", backing_store=False) as f:
519 str_array_3d = np.array(
520 [[['aa', 'bb'], ['cc', 'dd']], [['ee', 'ff'], ['gg', 'hh']]],
521 dtype=h5py.special_dtype(vlen=str)
522 )
523 # wrap the dataset in a StrDataset to mimic how HDF5IO would read this dataset with h5py 3+
524 dataset = StrDataset(f.create_dataset('data', data=str_array_3d), None)
525 bar_inst = Bar('my_bar', dataset, 'value1', 10, attr_array=dataset)
526 builder = type_map.build(bar_inst)
527 np.testing.assert_array_equal(builder.get('data').data, dataset[:])
528 np.testing.assert_array_equal(builder.get('attr_array'), dataset[:])
529
530 @unittest.skipIf(H5PY_3, "Create dataset differently for h5py < 3")
531 def test_build_1d_h5py_2_dataset(self):
532 bar_spec = GroupSpec(
533 doc='A test group specification with a data type',
534 data_type_def='Bar',
535 datasets=[
536 DatasetSpec(
537 doc='an example dataset',
538 dtype='text',
539 name='data',
540 shape=(None, ),
541 attributes=[AttributeSpec(name='attr2', doc='an example integer attribute', dtype='int')],
542 )
543 ],
544 attributes=[AttributeSpec(name='attr_array', doc='an example array attribute', dtype='text',
545 shape=(None, ))],
546 )
547 type_map = self.customSetUp(bar_spec)
548 type_map.register_map(Bar, BarMapper)
549 # create in-memory hdf5 file that is discarded after closing
550 with h5py.File("test.h5", "w", driver="core", backing_store=False) as f:
551 str_array_1d = np.array(
552 ['aa', 'bb', 'cc', 'dd'],
553 dtype=h5py.special_dtype(vlen=str)
554 )
555 dataset = f.create_dataset('data', data=str_array_1d)
556 bar_inst = Bar('my_bar', dataset, 'value1', 10, attr_array=dataset)
557 builder = type_map.build(bar_inst)
558 np.testing.assert_array_equal(builder.get('data').data, dataset[:])
559 np.testing.assert_array_equal(builder.get('attr_array'), dataset[:])
560
561 @unittest.skipIf(H5PY_3, "Create dataset differently for h5py < 3")
562 def test_build_3d_h5py_2_dataset(self):
563 bar_spec = GroupSpec(
564 doc='A test group specification with a data type',
565 data_type_def='Bar',
566 datasets=[
567 DatasetSpec(
568 doc='an example dataset',
569 dtype='text',
570 name='data',
571 shape=(None, None, None),
572 attributes=[AttributeSpec(name='attr2', doc='an example integer attribute', dtype='int')],
573 )
574 ],
575 attributes=[AttributeSpec(name='attr_array', doc='an example array attribute', dtype='text',
576 shape=(None, None, None))],
577 )
578 type_map = self.customSetUp(bar_spec)
579 type_map.register_map(Bar, BarMapper)
580 # create in-memory hdf5 file that is discarded after closing
581 with h5py.File("test.h5", "w", driver="core", backing_store=False) as f:
582 str_array_3d = np.array(
583 [[['aa', 'bb'], ['cc', 'dd']], [['ee', 'ff'], ['gg', 'hh']]],
584 dtype=h5py.special_dtype(vlen=str)
585 )
586 dataset = f.create_dataset('data', data=str_array_3d)
587 bar_inst = Bar('my_bar', dataset, 'value1', 10, attr_array=dataset)
588 builder = type_map.build(bar_inst)
589 np.testing.assert_array_equal(builder.get('data').data, dataset[:])
590 np.testing.assert_array_equal(builder.get('attr_array'), dataset[:])
591
592 def test_build_dataio(self):
593 bar_spec = GroupSpec('A test group specification with a data type',
594 data_type_def='Bar',
595 datasets=[DatasetSpec('an example dataset', 'text', name='data', shape=(None,),
596 attributes=[AttributeSpec(
597 'attr2', 'an example integer attribute', 'int')])],
598 attributes=[AttributeSpec('attr1', 'an example string attribute', 'text')])
599 type_map = self.customSetUp(bar_spec)
600 type_map.register_map(Bar, BarMapper)
601 bar_inst = Bar('my_bar', H5DataIO(['a', 'b', 'c', 'd'], chunks=True), 'value1', 10)
602 builder = type_map.build(bar_inst)
603 self.assertIsInstance(builder.get('data').data, H5DataIO)
604
605
606 class ObjectMapperMixin(metaclass=ABCMeta):
607
608 def setUp(self):
609 self.setUpBarSpec()
610 self.spec_catalog = SpecCatalog()
611 self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
612 self.namespace = SpecNamespace('a test namespace', CORE_NAMESPACE,
613 [{'source': 'test.yaml'}],
614 version='0.1.0',
615 catalog=self.spec_catalog)
616 self.namespace_catalog = NamespaceCatalog()
617 self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
618 self.type_map = TypeMap(self.namespace_catalog)
619 self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
620 self.manager = BuildManager(self.type_map)
621 self.mapper = ObjectMapper(self.bar_spec)
622
623 @abstractmethod
624 def setUpBarSpec(self):
625 raise NotImplementedError('Cannot run test unless setUpBarSpec is implemented')
626
627 def test_default_mapping(self):
628 attr_map = self.mapper.get_attr_names(self.bar_spec)
629 keys = set(attr_map.keys())
630 for key in keys:
631 with self.subTest(key=key):
632 self.assertIs(attr_map[key], self.mapper.get_attr_spec(key))
633 self.assertIs(attr_map[key], self.mapper.get_carg_spec(key))
634
635
636 class TestObjectMapperNested(ObjectMapperMixin, TestCase):
637
638 def setUpBarSpec(self):
639 self.bar_spec = GroupSpec('A test group specification with a data type',
640 data_type_def='Bar',
641 datasets=[DatasetSpec('an example dataset', 'int', name='data',
642 attributes=[AttributeSpec(
643 'attr2', 'an example integer attribute', 'int')])],
644 attributes=[AttributeSpec('attr1', 'an example string attribute', 'text')])
645
646 def test_build(self):
647 ''' Test default mapping functionality when object attributes map to an attribute deeper
648 than top-level Builder '''
649 container_inst = Bar('my_bar', list(range(10)), 'value1', 10)
650 expected = GroupBuilder(
651 name='my_bar',
652 datasets={'data': DatasetBuilder(
653 name='data',
654 data=list(range(10)),
655 attributes={'attr2': 10}
656 )},
657 attributes={'attr1': 'value1'}
658 )
659 self._remap_nested_attr()
660 builder = self.mapper.build(container_inst, self.manager)
661 self.assertBuilderEqual(builder, expected)
662
663 def test_construct(self):
664 ''' Test default mapping functionality when object attributes map to an attribute
665 deeper than top-level Builder '''
666 expected = Bar('my_bar', list(range(10)), 'value1', 10)
667 builder = GroupBuilder(
668 name='my_bar',
669 datasets={'data': DatasetBuilder(
670 name='data',
671 data=list(range(10)),
672 attributes={'attr2': 10}
673 )},
674 attributes={'attr1': 'value1',
675 'data_type': 'Bar',
676 'namespace': CORE_NAMESPACE,
677 'object_id': expected.object_id}
678 )
679 self._remap_nested_attr()
680 container = self.mapper.construct(builder, self.manager)
681 self.assertEqual(container, expected)
682
683 def test_default_mapping_keys(self):
684 attr_map = self.mapper.get_attr_names(self.bar_spec)
685 keys = set(attr_map.keys())
686 expected = {'attr1', 'data', 'data__attr2'}
687 self.assertSetEqual(keys, expected)
688
689 def test_remap_keys(self):
690 self._remap_nested_attr()
691 self.assertEqual(self.mapper.get_attr_spec('attr2'),
692 self.mapper.spec.get_dataset('data').get_attribute('attr2'))
693 self.assertEqual(self.mapper.get_attr_spec('attr1'), self.mapper.spec.get_attribute('attr1'))
694 self.assertEqual(self.mapper.get_attr_spec('data'), self.mapper.spec.get_dataset('data'))
695
696 def _remap_nested_attr(self):
697 data_spec = self.mapper.spec.get_dataset('data')
698 self.mapper.map_spec('attr2', data_spec.get_attribute('attr2'))
699
700
701 class TestObjectMapperNoNesting(ObjectMapperMixin, TestCase):
702
703 def setUpBarSpec(self):
704 self.bar_spec = GroupSpec('A test group specification with a data type',
705 data_type_def='Bar',
706 datasets=[DatasetSpec('an example dataset', 'int', name='data')],
707 attributes=[AttributeSpec('attr1', 'an example string attribute', 'text'),
708 AttributeSpec('attr2', 'an example integer attribute', 'int')])
709
710 def test_build(self):
711 ''' Test default mapping functionality when no attributes are nested '''
712 container = Bar('my_bar', list(range(10)), 'value1', 10)
713 builder = self.mapper.build(container, self.manager)
714 expected = GroupBuilder('my_bar', datasets={'data': DatasetBuilder('data', list(range(10)))},
715 attributes={'attr1': 'value1', 'attr2': 10})
716 self.assertBuilderEqual(builder, expected)
717
718 def test_build_empty(self):
719 ''' Test default mapping functionality when no attributes are nested '''
720 container = Bar('my_bar', [], 'value1', 10)
721 builder = self.mapper.build(container, self.manager)
722 expected = GroupBuilder('my_bar', datasets={'data': DatasetBuilder('data', [])},
723 attributes={'attr1': 'value1', 'attr2': 10})
724 self.assertBuilderEqual(builder, expected)
725
726 def test_construct(self):
727 expected = Bar('my_bar', list(range(10)), 'value1', 10)
728 builder = GroupBuilder('my_bar', datasets={'data': DatasetBuilder('data', list(range(10)))},
729 attributes={'attr1': 'value1', 'attr2': 10, 'data_type': 'Bar',
730 'namespace': CORE_NAMESPACE, 'object_id': expected.object_id})
731 container = self.mapper.construct(builder, self.manager)
732 self.assertEqual(container, expected)
733
734 def test_default_mapping_keys(self):
735 attr_map = self.mapper.get_attr_names(self.bar_spec)
736 keys = set(attr_map.keys())
737 expected = {'attr1', 'data', 'attr2'}
738 self.assertSetEqual(keys, expected)
739
740
741 class TestObjectMapperContainer(ObjectMapperMixin, TestCase):
742
743 def setUpBarSpec(self):
744 self.bar_spec = GroupSpec('A test group specification with a data type',
745 data_type_def='Bar',
746 groups=[GroupSpec('an example group', data_type_def='Foo')],
747 attributes=[AttributeSpec('attr1', 'an example string attribute', 'text'),
748 AttributeSpec('attr2', 'an example integer attribute', 'int')])
749
750 def test_default_mapping_keys(self):
751 attr_map = self.mapper.get_attr_names(self.bar_spec)
752 keys = set(attr_map.keys())
753 expected = {'attr1', 'foo', 'attr2'}
754 self.assertSetEqual(keys, expected)
755
756
757 class TestLinkedContainer(TestCase):
758
759 def setUp(self):
760 self.foo_spec = GroupSpec('A test group specification with data type Foo', data_type_def='Foo')
761 self.bar_spec = GroupSpec('A test group specification with a data type Bar',
762 data_type_def='Bar',
763 groups=[self.foo_spec],
764 datasets=[DatasetSpec('an example dataset', 'int', name='data')],
765 attributes=[AttributeSpec('attr1', 'an example string attribute', 'text'),
766 AttributeSpec('attr2', 'an example integer attribute', 'int')])
767
768 self.spec_catalog = SpecCatalog()
769 self.spec_catalog.register_spec(self.foo_spec, 'test.yaml')
770 self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
771 self.namespace = SpecNamespace('a test namespace', CORE_NAMESPACE,
772 [{'source': 'test.yaml'}],
773 version='0.1.0',
774 catalog=self.spec_catalog)
775 self.namespace_catalog = NamespaceCatalog()
776 self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
777 self.type_map = TypeMap(self.namespace_catalog)
778 self.type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo)
779 self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
780 self.manager = BuildManager(self.type_map)
781 self.foo_mapper = ObjectMapper(self.foo_spec)
782 self.bar_mapper = ObjectMapper(self.bar_spec)
783
784 def test_build_child_link(self):
785 ''' Test default mapping functionality when one container contains a child link to another container '''
786 foo_inst = Foo('my_foo')
787 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10, foo=foo_inst)
788 # bar_inst2.foo should link to bar_inst1.foo
789 bar_inst2 = Bar('my_bar2', list(range(10)), 'value1', 10, foo=foo_inst)
790
791 foo_builder = self.foo_mapper.build(foo_inst, self.manager)
792 bar1_builder = self.bar_mapper.build(bar_inst1, self.manager)
793 bar2_builder = self.bar_mapper.build(bar_inst2, self.manager)
794
795 foo_expected = GroupBuilder('my_foo')
796
797 inner_foo_builder = GroupBuilder('my_foo',
798 attributes={'data_type': 'Foo',
799 'namespace': CORE_NAMESPACE,
800 'object_id': foo_inst.object_id})
801 bar1_expected = GroupBuilder('my_bar1',
802 datasets={'data': DatasetBuilder('data', list(range(10)))},
803 groups={'foo': inner_foo_builder},
804 attributes={'attr1': 'value1', 'attr2': 10})
805 link_foo_builder = LinkBuilder(builder=inner_foo_builder)
806 bar2_expected = GroupBuilder('my_bar2',
807 datasets={'data': DatasetBuilder('data', list(range(10)))},
808 links={'foo': link_foo_builder},
809 attributes={'attr1': 'value1', 'attr2': 10})
810 self.assertBuilderEqual(foo_builder, foo_expected)
811 self.assertBuilderEqual(bar1_builder, bar1_expected)
812 self.assertBuilderEqual(bar2_builder, bar2_expected)
813
814 @unittest.expectedFailure
815 def test_build_broken_link_parent(self):
816 ''' Test that building a container with a broken link that has a parent raises an error. '''
817 foo_inst = Foo('my_foo')
818 Bar('my_bar1', list(range(10)), 'value1', 10, foo=foo_inst) # foo_inst.parent is this bar
819 # bar_inst2.foo should link to bar_inst1.foo
820 bar_inst2 = Bar('my_bar2', list(range(10)), 'value1', 10, foo=foo_inst)
821
822 # TODO bar_inst.foo.parent exists but is never built - this is a tricky edge case that should raise an error
823 with self.assertRaises(OrphanContainerBuildError):
824 self.bar_mapper.build(bar_inst2, self.manager)
825
826 def test_build_broken_link_no_parent(self):
827 ''' Test that building a container with a broken link that has no parent raises an error. '''
828 foo_inst = Foo('my_foo')
829 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10, foo=foo_inst) # foo_inst.parent is this bar
830 # bar_inst2.foo should link to bar_inst1.foo
831 bar_inst2 = Bar('my_bar2', list(range(10)), 'value1', 10, foo=foo_inst)
832 bar_inst1.remove_foo()
833
834 msg = ("my_bar2 (my_bar2): Linked Foo 'my_foo' has no parent. Remove the link or ensure the linked container "
835 "is added properly.")
836 with self.assertRaisesWith(OrphanContainerBuildError, msg):
837 self.bar_mapper.build(bar_inst2, self.manager)
838
839
840 class TestReference(TestCase):
841
842 def setUp(self):
843 self.foo_spec = GroupSpec('A test group specification with data type Foo', data_type_def='Foo')
844 self.bar_spec = GroupSpec('A test group specification with a data type Bar',
845 data_type_def='Bar',
846 datasets=[DatasetSpec('an example dataset', 'int', name='data')],
847 attributes=[AttributeSpec('attr1', 'an example string attribute', 'text'),
848 AttributeSpec('attr2', 'an example integer attribute', 'int'),
849 AttributeSpec('foo', 'a referenced foo', RefSpec('Foo', 'object'),
850 required=False)])
851
852 self.spec_catalog = SpecCatalog()
853 self.spec_catalog.register_spec(self.foo_spec, 'test.yaml')
854 self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
855 self.namespace = SpecNamespace('a test namespace', CORE_NAMESPACE,
856 [{'source': 'test.yaml'}],
857 version='0.1.0',
858 catalog=self.spec_catalog)
859 self.namespace_catalog = NamespaceCatalog()
860 self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
861 self.type_map = TypeMap(self.namespace_catalog)
862 self.type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo)
863 self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
864 self.manager = BuildManager(self.type_map)
865 self.foo_mapper = ObjectMapper(self.foo_spec)
866 self.bar_mapper = ObjectMapper(self.bar_spec)
867
868 def test_build_attr_ref(self):
869 ''' Test default mapping functionality when one container contains an attribute reference to another container.
870 '''
871 foo_inst = Foo('my_foo')
872 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10, foo=foo_inst)
873 bar_inst2 = Bar('my_bar2', list(range(10)), 'value1', 10)
874
875 foo_builder = self.manager.build(foo_inst, root=True)
876 bar1_builder = self.manager.build(bar_inst1, root=True) # adds refs
877 bar2_builder = self.manager.build(bar_inst2, root=True)
878
879 foo_expected = GroupBuilder('my_foo',
880 attributes={'data_type': 'Foo',
881 'namespace': CORE_NAMESPACE,
882 'object_id': foo_inst.object_id})
883 bar1_expected = GroupBuilder('n/a', # name doesn't matter
884 datasets={'data': DatasetBuilder('data', list(range(10)))},
885 attributes={'attr1': 'value1',
886 'attr2': 10,
887 'foo': ReferenceBuilder(foo_expected),
888 'data_type': 'Bar',
889 'namespace': CORE_NAMESPACE,
890 'object_id': bar_inst1.object_id})
891 bar2_expected = GroupBuilder('n/a', # name doesn't matter
892 datasets={'data': DatasetBuilder('data', list(range(10)))},
893 attributes={'attr1': 'value1',
894 'attr2': 10,
895 'data_type': 'Bar',
896 'namespace': CORE_NAMESPACE,
897 'object_id': bar_inst2.object_id})
898 self.assertDictEqual(foo_builder, foo_expected)
899 self.assertDictEqual(bar1_builder, bar1_expected)
900 self.assertDictEqual(bar2_builder, bar2_expected)
901
902 def test_build_attr_ref_invalid(self):
903 ''' Test default mapping functionality when one container contains an attribute reference to another container.
904 '''
905 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10)
906 bar_inst1._Bar__foo = object() # make foo object a non-container type
907
908 msg = "invalid type for reference 'foo' (<class 'object'>) - must be AbstractContainer"
909 with self.assertRaisesWith(ValueError, msg):
910 self.bar_mapper.build(bar_inst1, self.manager)
911
912
913 class TestMissingRequiredAttribute(ObjectMapperMixin, TestCase):
914
915 def setUpBarSpec(self):
916 self.bar_spec = GroupSpec(
917 doc='A test group specification with a data type Bar',
918 data_type_def='Bar',
919 attributes=[AttributeSpec('attr1', 'an example string attribute', 'text'),
920 AttributeSpec('attr2', 'an example integer attribute', 'int')]
921 )
922
923 def test_required_attr_missing(self):
924 """Test mapping when one container is missing a required attribute."""
925
926 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10)
927 bar_inst1._Bar__attr1 = None # make attr1 attribute None
928
929 msg = "Bar 'my_bar1' is missing required value for attribute 'attr1'."
930 with self.assertWarnsWith(MissingRequiredBuildWarning, msg):
931 builder = self.mapper.build(bar_inst1, self.manager)
932
933 expected = GroupBuilder(
934 name='my_bar1',
935 attributes={'attr2': 10}
936 )
937 self.assertBuilderEqual(expected, builder)
938
939
940 class TestMissingRequiredAttributeRef(ObjectMapperMixin, TestCase):
941
942 def setUpBarSpec(self):
943 self.bar_spec = GroupSpec(
944 doc='A test group specification with a data type Bar',
945 data_type_def='Bar',
946 attributes=[AttributeSpec('foo', 'a referenced foo', RefSpec('Foo', 'object'))]
947 )
948
949 def test_required_attr_ref_missing(self):
950 """Test mapping when one container is missing a required attribute reference."""
951
952 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10)
953
954 msg = "Bar 'my_bar1' is missing required value for attribute 'foo'."
955 with self.assertWarnsWith(MissingRequiredBuildWarning, msg):
956 builder = self.mapper.build(bar_inst1, self.manager)
957
958 expected = GroupBuilder(
959 name='my_bar1',
960 )
961 self.assertBuilderEqual(expected, builder)
962
963
964 class TestMissingRequiredDataset(ObjectMapperMixin, TestCase):
965
966 def setUpBarSpec(self):
967 self.bar_spec = GroupSpec(
968 doc='A test group specification with a data type Bar',
969 data_type_def='Bar',
970 datasets=[DatasetSpec('an example dataset', 'int', name='data')]
971 )
972
973 def test_required_dataset_missing(self):
974 """Test mapping when one container is missing a required dataset."""
975
976 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10)
977 bar_inst1._Bar__data = None # make data dataset None
978
979 msg = "Bar 'my_bar1' is missing required value for attribute 'data'."
980 with self.assertWarnsWith(MissingRequiredBuildWarning, msg):
981 builder = self.mapper.build(bar_inst1, self.manager)
982
983 expected = GroupBuilder(
984 name='my_bar1',
985 )
986 self.assertBuilderEqual(expected, builder)
987
988
989 class TestMissingRequiredGroup(ObjectMapperMixin, TestCase):
990
991 def setUpBarSpec(self):
992 self.bar_spec = GroupSpec(
993 doc='A test group specification with a data type Bar',
994 data_type_def='Bar',
995 groups=[GroupSpec('foo', data_type_inc='Foo')]
996 )
997
998 def test_required_group_missing(self):
999 """Test mapping when one container is missing a required group."""
1000
1001 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10)
1002 msg = "Bar 'my_bar1' is missing required value for attribute 'foo'."
1003 with self.assertWarnsWith(MissingRequiredBuildWarning, msg):
1004 builder = self.mapper.build(bar_inst1, self.manager)
1005
1006 expected = GroupBuilder(
1007 name='my_bar1',
1008 )
1009 self.assertBuilderEqual(expected, builder)
1010
1011
1012 class TestRequiredEmptyGroup(ObjectMapperMixin, TestCase):
1013
1014 def setUpBarSpec(self):
1015 self.bar_spec = GroupSpec(
1016 doc='A test group specification with a data type Bar',
1017 data_type_def='Bar',
1018 groups=[GroupSpec(name='empty', doc='empty group')],
1019 )
1020
1021 def test_required_group_empty(self):
1022 """Test mapping when one container has a required empty group."""
1023
1024 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10)
1025 builder = self.mapper.build(bar_inst1, self.manager)
1026
1027 expected = GroupBuilder(
1028 name='my_bar1',
1029 groups={'empty': GroupBuilder('empty')},
1030 )
1031 self.assertBuilderEqual(expected, builder)
1032
1033
1034 class TestOptionalEmptyGroup(ObjectMapperMixin, TestCase):
1035
1036 def setUpBarSpec(self):
1037 self.bar_spec = GroupSpec(
1038 doc='A test group specification with a data type Bar',
1039 data_type_def='Bar',
1040 groups=[GroupSpec(
1041 name='empty',
1042 doc='empty group',
1043 quantity='?',
1044 attributes=[AttributeSpec('attr3', 'an optional float attribute', 'float', required=False)]
1045 )]
1046 )
1047
1048 def test_optional_group_empty(self):
1049 """Test mapping when one container has an optional empty group."""
1050
1051 self.mapper.map_spec('attr3', self.mapper.spec.get_group('empty').get_attribute('attr3'))
1052
1053 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10)
1054 bar_inst1._Bar__attr3 = None # force attr3 to be None
1055 builder = self.mapper.build(bar_inst1, self.manager)
1056
1057 expected = GroupBuilder(
1058 name='my_bar1',
1059 )
1060 self.assertBuilderEqual(expected, builder)
1061
1062 def test_optional_group_not_empty(self):
1063 """Test mapping when one container has an optional not empty group."""
1064
1065 self.mapper.map_spec('attr3', self.mapper.spec.get_group('empty').get_attribute('attr3'))
1066
1067 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10, attr3=1.23)
1068 builder = self.mapper.build(bar_inst1, self.manager)
1069
1070 expected = GroupBuilder(
1071 name='my_bar1',
1072 groups={'empty': GroupBuilder(
1073 name='empty',
1074 attributes={'attr3': 1.23},
1075 )},
1076 )
1077 self.assertBuilderEqual(expected, builder)
1078
1079
1080 class TestFixedAttributeValue(ObjectMapperMixin, TestCase):
1081
1082 def setUpBarSpec(self):
1083 self.bar_spec = GroupSpec(
1084 doc='A test group specification with a data type Bar',
1085 data_type_def='Bar',
1086 attributes=[AttributeSpec('attr1', 'an example string attribute', 'text', value='hi'),
1087 AttributeSpec('attr2', 'an example integer attribute', 'int')]
1088 )
1089
1090 def test_required_attr_missing(self):
1091 """Test mapping when one container has a required attribute with a fixed value."""
1092
1093 bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10) # attr1=value1 is not processed
1094 builder = self.mapper.build(bar_inst1, self.manager)
1095
1096 expected = GroupBuilder(
1097 name='my_bar1',
1098 attributes={'attr1': 'hi', 'attr2': 10}
1099 )
1100 self.assertBuilderEqual(builder, expected)
1101
1102
1103 class TestObjectMapperBadValue(TestCase):
1104
1105 def test_bad_value(self):
1106 """Test that an error is raised if the container attribute value for a spec with a data type is not a container
1107 or collection of containers.
1108 """
1109 class Qux(Container):
1110 @docval({'name': 'name', 'type': str, 'doc': 'the name of this Qux'},
1111 {'name': 'foo', 'type': int, 'doc': 'a group'})
1112 def __init__(self, **kwargs):
1113 name, foo = getargs('name', 'foo', kwargs)
1114 super().__init__(name=name)
1115 self.__foo = foo
1116 if isinstance(foo, Foo):
1117 self.__foo.parent = self
1118
1119 @property
1120 def foo(self):
1121 return self.__foo
1122
1123 self.qux_spec = GroupSpec(
1124 doc='A test group specification with data type Qux',
1125 data_type_def='Qux',
1126 groups=[GroupSpec('an example dataset', data_type_inc='Foo')]
1127 )
1128 self.foo_spec = GroupSpec('A test group specification with data type Foo', data_type_def='Foo')
1129 self.spec_catalog = SpecCatalog()
1130 self.spec_catalog.register_spec(self.qux_spec, 'test.yaml')
1131 self.spec_catalog.register_spec(self.foo_spec, 'test.yaml')
1132 self.namespace = SpecNamespace('a test namespace', CORE_NAMESPACE, [{'source': 'test.yaml'}],
1133 version='0.1.0',
1134 catalog=self.spec_catalog)
1135 self.namespace_catalog = NamespaceCatalog()
1136 self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
1137 self.type_map = TypeMap(self.namespace_catalog)
1138 self.type_map.register_container_type(CORE_NAMESPACE, 'Qux', Qux)
1139 self.type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo)
1140 self.manager = BuildManager(self.type_map)
1141 self.mapper = ObjectMapper(self.qux_spec)
1142
1143 container = Qux('my_qux', foo=1)
1144 msg = "Qux 'my_qux' attribute 'foo' has unexpected type."
1145 with self.assertRaisesWith(ContainerConfigurationError, msg):
1146 self.mapper.build(container, self.manager)
1147
1148 # TODO test passing a Container/Data/other object for a non-container/data array spec