Debian Codegraph @

tests/unit/build_tests/test_classgenerator.py

raw
1 import numpy as np
2 import os
3 import shutil
4 import tempfile
5 from warnings import warn
6
7 from hdmf.build import TypeMap, CustomClassGenerator
8 from hdmf.build.classgenerator import ClassGenerator, MCIClassGenerator
9 from hdmf.container import Container, Data, MultiContainerInterface, AbstractContainer
10 from hdmf.spec import (
11 GroupSpec, AttributeSpec, DatasetSpec, SpecCatalog, SpecNamespace, NamespaceCatalog, LinkSpec, RefSpec
12 )
13 from hdmf.testing import TestCase
14 from hdmf.utils import get_docval, docval
15
16 from .test_io_map import Bar
17 from tests.unit.helpers.utils import CORE_NAMESPACE, create_test_type_map, create_load_namespace_yaml
18
19
20 class TestClassGenerator(TestCase):
21
22 def test_register_generator(self):
23 """Test TypeMap.register_generator and ClassGenerator.register_generator."""
24
25 class MyClassGenerator(CustomClassGenerator):
26
27 @classmethod
28 def apply_generator_to_field(cls, field_spec, bases, type_map):
29 return True
30
31 @classmethod
32 def process_field_spec(cls, classdict, docval_args, parent_cls, attr_name, not_inherited_fields, type_map,
33 spec):
34 # append attr_name to classdict['__custom_fields__'] list
35 classdict.setdefault('process_field_spec', list()).append(attr_name)
36
37 @classmethod
38 def post_process(cls, classdict, bases, docval_args, spec):
39 classdict['post_process'] = True
40
41 spec = GroupSpec(
42 doc='A test group specification with a data type',
43 data_type_def='Baz',
44 attributes=[
45 AttributeSpec(name='attr1', doc='a string attribute', dtype='text')
46 ]
47 )
48
49 spec_catalog = SpecCatalog()
50 spec_catalog.register_spec(spec, 'test.yaml')
51 namespace = SpecNamespace(
52 doc='a test namespace',
53 name=CORE_NAMESPACE,
54 schema=[{'source': 'test.yaml'}],
55 version='0.1.0',
56 catalog=spec_catalog
57 )
58 namespace_catalog = NamespaceCatalog()
59 namespace_catalog.add_namespace(CORE_NAMESPACE, namespace)
60 type_map = TypeMap(namespace_catalog)
61 type_map.register_generator(MyClassGenerator)
62 cls = type_map.get_dt_container_cls('Baz', CORE_NAMESPACE)
63
64 self.assertEqual(cls.process_field_spec, ['attr1'])
65 self.assertTrue(cls.post_process)
66
67 def test_bad_generator(self):
68 """Test that register_generator raises an error if the generator is not an instance of CustomClassGenerator."""
69
70 class NotACustomClassGenerator:
71 pass
72
73 type_map = TypeMap()
74
75 msg = 'Generator <.*> must be a subclass of CustomClassGenerator.'
76 with self.assertRaisesRegex(ValueError, msg):
77 type_map.register_generator(NotACustomClassGenerator)
78
79 def test_no_generators(self):
80 """Test that a ClassGenerator without registered generators does nothing."""
81 cg = ClassGenerator()
82 spec = GroupSpec(doc='A test group spec with a data type', data_type_def='Baz')
83 cls = cg.generate_class(data_type='Baz', spec=spec, parent_cls=Container, attr_names={}, type_map=TypeMap())
84 self.assertEqual(cls.__mro__, (cls, Container, AbstractContainer, object))
85 self.assertTrue(hasattr(cls, '__init__'))
86
87
88 class TestPostInitGetClass(TestCase):
89 def setUp(self):
90 def post_init_method(self, **kwargs):
91 attr1 = kwargs['attr1']
92 if attr1<10:
93 msg = "attr1 should be >=10"
94 warn(msg)
95 self.post_init=post_init_method
96
97 def test_post_init(self):
98 spec = GroupSpec(
99 doc='A test group specification with a data type',
100 data_type_def='Baz',
101 attributes=[
102 AttributeSpec(name='attr1', doc='a int attribute', dtype='int')
103 ]
104 )
105
106 spec_catalog = SpecCatalog()
107 spec_catalog.register_spec(spec, 'test.yaml')
108 namespace = SpecNamespace(
109 doc='a test namespace',
110 name=CORE_NAMESPACE,
111 schema=[{'source': 'test.yaml'}],
112 version='0.1.0',
113 catalog=spec_catalog
114 )
115 namespace_catalog = NamespaceCatalog()
116 namespace_catalog.add_namespace(CORE_NAMESPACE, namespace)
117 type_map = TypeMap(namespace_catalog)
118
119 cls = type_map.get_dt_container_cls('Baz', CORE_NAMESPACE, self.post_init)
120
121 with self.assertWarns(Warning):
122 cls(name='instance', attr1=9)
123
124 def test_multi_container_post_init(self):
125 bar_spec = GroupSpec(
126 doc='A test group specification with a data type',
127 data_type_def='Bar',
128 datasets=[
129 DatasetSpec(
130 doc='a dataset',
131 dtype='int',
132 name='data',
133 attributes=[AttributeSpec(name='attr2', doc='an integer attribute', dtype='int')]
134 )
135 ],
136 attributes=[AttributeSpec(name='attr1', doc='a string attribute', dtype='text')])
137
138 multi_spec = GroupSpec(doc='A test extension that contains a multi',
139 data_type_def='Multi',
140 groups=[GroupSpec(data_type_inc=bar_spec, doc='test multi', quantity='*')],
141 attributes=[AttributeSpec(name='attr1', doc='a float attribute', dtype='float')])
142
143 spec_catalog = SpecCatalog()
144 spec_catalog.register_spec(bar_spec, 'test.yaml')
145 spec_catalog.register_spec(multi_spec, 'test.yaml')
146 namespace = SpecNamespace(
147 doc='a test namespace',
148 name=CORE_NAMESPACE,
149 schema=[{'source': 'test.yaml'}],
150 version='0.1.0',
151 catalog=spec_catalog
152 )
153 namespace_catalog = NamespaceCatalog()
154 namespace_catalog.add_namespace(CORE_NAMESPACE, namespace)
155 type_map = TypeMap(namespace_catalog)
156 Multi = type_map.get_dt_container_cls('Multi', CORE_NAMESPACE, self.post_init)
157
158 with self.assertWarns(Warning):
159 Multi(name='instance', attr1=9.1)
160
161 class TestDynamicContainer(TestCase):
162
163 def setUp(self):
164 self.bar_spec = GroupSpec(
165 doc='A test group specification with a data type',
166 data_type_def='Bar',
167 datasets=[
168 DatasetSpec(
169 doc='a dataset',
170 dtype='int',
171 name='data',
172 attributes=[AttributeSpec(name='attr2', doc='an integer attribute', dtype='int')]
173 )
174 ],
175 attributes=[AttributeSpec(name='attr1', doc='a string attribute', dtype='text')])
176 specs = [self.bar_spec]
177 containers = {'Bar': Bar}
178 self.type_map = create_test_type_map(specs, containers)
179 self.spec_catalog = self.type_map.namespace_catalog.get_namespace(CORE_NAMESPACE).catalog
180
181 def test_dynamic_container_creation(self):
182 baz_spec = GroupSpec('A test extension with no Container class',
183 data_type_def='Baz', data_type_inc=self.bar_spec,
184 attributes=[AttributeSpec('attr3', 'a float attribute', 'float'),
185 AttributeSpec('attr4', 'another float attribute', 'float'),
186 AttributeSpec('attr_array', 'an array attribute', 'text', shape=(None,)),])
187 self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
188 cls = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE)
189 expected_args = {'name', 'data', 'attr1', 'attr2', 'attr3', 'attr4', 'attr_array', 'skip_post_init'}
190 received_args = set()
191
192 for x in get_docval(cls.__init__):
193 if x['name'] != 'foo':
194 received_args.add(x['name'])
195 with self.subTest(name=x['name']):
196 if x['name'] != 'skip_post_init':
197 self.assertNotIn('default', x)
198 self.assertSetEqual(expected_args, received_args)
199 self.assertEqual(cls.__name__, 'Baz')
200 self.assertTrue(issubclass(cls, Bar))
201
202 def test_dynamic_container_default_name(self):
203 baz_spec = GroupSpec('doc', default_name='bingo', data_type_def='Baz',
204 attributes=[AttributeSpec('attr4', 'another float attribute', 'float')])
205 self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
206 cls = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE)
207 inst = cls(attr4=10.)
208 self.assertEqual(inst.name, 'bingo')
209
210 def test_dynamic_container_creation_defaults(self):
211 baz_spec = GroupSpec('A test extension with no Container class',
212 data_type_def='Baz', data_type_inc=self.bar_spec,
213 attributes=[AttributeSpec('attr3', 'a float attribute', 'float'),
214 AttributeSpec('attr4', 'another float attribute', 'float')])
215 self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
216 cls = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE)
217 expected_args = {'name', 'data', 'attr1', 'attr2', 'attr3', 'attr4', 'attr_array', 'foo', 'skip_post_init'}
218 received_args = set(map(lambda x: x['name'], get_docval(cls.__init__)))
219 self.assertSetEqual(expected_args, received_args)
220 self.assertEqual(cls.__name__, 'Baz')
221 self.assertTrue(issubclass(cls, Bar))
222
223 def test_dynamic_container_constructor(self):
224 baz_spec = GroupSpec('A test extension with no Container class',
225 data_type_def='Baz', data_type_inc=self.bar_spec,
226 attributes=[AttributeSpec('attr3', 'a float attribute', 'float'),
227 AttributeSpec('attr4', 'another float attribute', 'float')])
228 self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
229 cls = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE)
230 # TODO: test that constructor works!
231 inst = cls(name='My Baz', data=[1, 2, 3, 4], attr1='string attribute', attr2=1000, attr3=98.6, attr4=1.0)
232 self.assertEqual(inst.name, 'My Baz')
233 self.assertEqual(inst.data, [1, 2, 3, 4])
234 self.assertEqual(inst.attr1, 'string attribute')
235 self.assertEqual(inst.attr2, 1000)
236 self.assertEqual(inst.attr3, 98.6)
237 self.assertEqual(inst.attr4, 1.0)
238
239 def test_dynamic_container_constructor_name(self):
240 # name is specified in spec and cannot be changed
241 baz_spec = GroupSpec('A test extension with no Container class',
242 data_type_def='Baz', data_type_inc=self.bar_spec,
243 name='A fixed name',
244 attributes=[AttributeSpec('attr3', 'a float attribute', 'float'),
245 AttributeSpec('attr4', 'another float attribute', 'float')])
246 self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
247 cls = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE)
248
249 with self.assertRaises(TypeError):
250 inst = cls(name='My Baz', data=[1, 2, 3, 4], attr1='string attribute', attr2=1000, attr3=98.6, attr4=1.0)
251
252 inst = cls(data=[1, 2, 3, 4], attr1='string attribute', attr2=1000, attr3=98.6, attr4=1.0)
253 self.assertEqual(inst.name, 'A fixed name')
254 self.assertEqual(inst.data, [1, 2, 3, 4])
255 self.assertEqual(inst.attr1, 'string attribute')
256 self.assertEqual(inst.attr2, 1000)
257 self.assertEqual(inst.attr3, 98.6)
258 self.assertEqual(inst.attr4, 1.0)
259
260 def test_dynamic_container_constructor_name_default_name(self):
261 # if both name and default_name are specified, name should be used
262 with self.assertWarns(Warning):
263 baz_spec = GroupSpec('A test extension with no Container class',
264 data_type_def='Baz', data_type_inc=self.bar_spec,
265 name='A fixed name',
266 default_name='A default name',
267 attributes=[AttributeSpec('attr3', 'a float attribute', 'float'),
268 AttributeSpec('attr4', 'another float attribute', 'float')])
269 self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
270 cls = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE)
271
272 inst = cls(data=[1, 2, 3, 4], attr1='string attribute', attr2=1000, attr3=98.6, attr4=1.0)
273 self.assertEqual(inst.name, 'A fixed name')
274
275 def test_dynamic_container_composition(self):
276 baz_spec2 = GroupSpec('A composition inside', data_type_def='Baz2',
277 data_type_inc=self.bar_spec,
278 attributes=[
279 AttributeSpec('attr3', 'a float attribute', 'float'),
280 AttributeSpec('attr4', 'another float attribute', 'float')])
281
282 baz_spec1 = GroupSpec('A composition test outside', data_type_def='Baz1', data_type_inc=self.bar_spec,
283 attributes=[AttributeSpec('attr3', 'a float attribute', 'float'),
284 AttributeSpec('attr4', 'another float attribute', 'float')],
285 groups=[GroupSpec('A composition inside', data_type_inc='Baz2')])
286 self.spec_catalog.register_spec(baz_spec1, 'extension.yaml')
287 self.spec_catalog.register_spec(baz_spec2, 'extension.yaml')
288 Baz2 = self.type_map.get_dt_container_cls('Baz2', CORE_NAMESPACE)
289 Baz1 = self.type_map.get_dt_container_cls('Baz1', CORE_NAMESPACE)
290 Baz1(name='My Baz', data=[1, 2, 3, 4], attr1='string attribute', attr2=1000, attr3=98.6, attr4=1.0,
291 baz2=Baz2(name='My Baz', data=[1, 2, 3, 4], attr1='string attribute', attr2=1000, attr3=98.6, attr4=1.0))
292
293 Bar = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
294 bar = Bar(name='My Bar', data=[1, 2, 3, 4], attr1='string attribute', attr2=1000)
295
296 with self.assertRaises(TypeError):
297 Baz1(name='My Baz', data=[1, 2, 3, 4], attr1='string attribute', attr2=1000, attr3=98.6, attr4=1.0,
298 baz2=bar)
299
300 def test_dynamic_container_composition_reverse_order(self):
301 baz_spec2 = GroupSpec('A composition inside', data_type_def='Baz2',
302 data_type_inc=self.bar_spec,
303 attributes=[
304 AttributeSpec('attr3', 'a float attribute', 'float'),
305 AttributeSpec('attr4', 'another float attribute', 'float')])
306
307 baz_spec1 = GroupSpec('A composition test outside', data_type_def='Baz1', data_type_inc=self.bar_spec,
308 attributes=[AttributeSpec('attr3', 'a float attribute', 'float'),
309 AttributeSpec('attr4', 'another float attribute', 'float')],
310 groups=[GroupSpec('A composition inside', data_type_inc='Baz2')])
311 self.spec_catalog.register_spec(baz_spec1, 'extension.yaml')
312 self.spec_catalog.register_spec(baz_spec2, 'extension.yaml')
313 Baz1 = self.type_map.get_dt_container_cls('Baz1', CORE_NAMESPACE)
314 Baz2 = self.type_map.get_dt_container_cls('Baz2', CORE_NAMESPACE)
315 Baz1(name='My Baz', data=[1, 2, 3, 4], attr1='string attribute', attr2=1000, attr3=98.6, attr4=1.0,
316 baz2=Baz2(name='My Baz', data=[1, 2, 3, 4], attr1='string attribute', attr2=1000, attr3=98.6, attr4=1.0))
317
318 Bar = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
319 bar = Bar(name='My Bar', data=[1, 2, 3, 4], attr1='string attribute', attr2=1000)
320
321 with self.assertRaises(TypeError):
322 Baz1(name='My Baz', data=[1, 2, 3, 4], attr1='string attribute',
323 attr2=1000, attr3=98.6, attr4=1.0, baz2=bar)
324
325 def test_dynamic_container_composition_missing_type(self):
326 baz_spec1 = GroupSpec('A composition test outside', data_type_def='Baz1', data_type_inc=self.bar_spec,
327 attributes=[AttributeSpec('attr3', 'a float attribute', 'float'),
328 AttributeSpec('attr4', 'another float attribute', 'float')],
329 groups=[GroupSpec('A composition inside', data_type_inc='Baz2')])
330 self.spec_catalog.register_spec(baz_spec1, 'extension.yaml')
331
332 msg = "No specification for 'Baz2' in namespace 'test_core'"
333 with self.assertRaisesWith(ValueError, msg):
334 self.type_map.get_dt_container_cls('Baz1', CORE_NAMESPACE)
335
336 def test_dynamic_container_fixed_name(self):
337 """Test that dynamic class generation for an extended type with a fixed name works."""
338 baz_spec = GroupSpec('A test extension with no Container class',
339 data_type_def='Baz', data_type_inc=self.bar_spec, name='Baz')
340 self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
341 Baz = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE)
342 obj = Baz(data=[1, 2, 3, 4], attr1='string attribute', attr2=1000)
343 self.assertEqual(obj.name, 'Baz')
344
345 def test_dynamic_container_super_init_fixed_value(self):
346 """Test that dynamic class generation when the superclass init does not include all fields works"""
347
348 class FixedAttrBar(Bar):
349 @docval({'name': 'name', 'type': str, 'doc': 'the name of this Bar'},
350 {'name': 'data', 'type': ('data', 'array_data'), 'doc': 'some data'},
351 {'name': 'attr2', 'type': int, 'doc': 'another attribute'},
352 {'name': 'attr3', 'type': float, 'doc': 'a third attribute', 'default': 3.14},
353 {'name': 'foo', 'type': 'Foo', 'doc': 'a group', 'default': None})
354 def __init__(self, **kwargs):
355 kwargs["attr1"] = "fixed_attr1"
356 super().__init__(**kwargs)
357
358 # overwrite the "Bar" to Bar class mapping from setUp()
359 self.type_map.register_container_type(CORE_NAMESPACE, "Bar", FixedAttrBar)
360
361 baz_spec = GroupSpec('A test extension with no Container class',
362 data_type_def='Baz', data_type_inc=self.bar_spec,
363 attributes=[AttributeSpec('attr3', 'a float attribute', 'float'),
364 AttributeSpec('attr4', 'another float attribute', 'float')])
365 self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
366 cls = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE)
367 expected_args = {'name', 'data', 'attr2', 'attr3', 'attr4', 'skip_post_init'}
368 received_args = set()
369 for x in get_docval(cls.__init__):
370 if x['name'] != 'foo':
371 received_args.add(x['name'])
372 with self.subTest(name=x['name']):
373 if x['name'] != 'skip_post_init':
374 self.assertNotIn('default', x)
375 self.assertSetEqual(expected_args, received_args)
376 self.assertTrue(issubclass(cls, FixedAttrBar))
377 inst = cls(name="My Baz", data=[1, 2, 3, 4], attr2=1000, attr3=98.6, attr4=1.0)
378 self.assertEqual(inst.attr1, "fixed_attr1")
379
380 def test_multi_container_spec(self):
381 multi_spec = GroupSpec(
382 doc='A test extension that contains a multi',
383 data_type_def='Multi',
384 groups=[
385 GroupSpec(data_type_inc=self.bar_spec, doc='test multi', quantity='*')
386 ],
387 attributes=[
388 AttributeSpec(name='attr3', doc='a float attribute', dtype='float')
389 ]
390 )
391 self.spec_catalog.register_spec(multi_spec, 'extension.yaml')
392 Bar = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
393 Multi = self.type_map.get_dt_container_cls('Multi', CORE_NAMESPACE)
394 assert issubclass(Multi, MultiContainerInterface)
395 assert Multi.__clsconf__ == [
396 dict(
397 attr='bars',
398 type=Bar,
399 add='add_bars',
400 get='get_bars',
401 create='create_bars'
402 )
403 ]
404
405 multi = Multi(
406 name='my_multi',
407 bars=[Bar(name='my_bar', data=list(range(10)), attr1='value1', attr2=10)],
408 attr3=5.
409 )
410 assert multi.bars['my_bar'] == Bar(name='my_bar', data=list(range(10)), attr1='value1', attr2=10)
411 assert multi.attr3 == 5.
412
413 def test_multi_container_spec_with_inc(self):
414 multi_spec = GroupSpec(
415 doc='A test extension that contains a multi',
416 data_type_def='Multi',
417 data_type_inc=self.bar_spec,
418 groups=[
419 GroupSpec(data_type_inc=self.bar_spec, doc='test multi', quantity='*')
420 ],
421 attributes=[
422 AttributeSpec(name='attr3', doc='a float attribute', dtype='float')
423 ]
424 )
425 self.spec_catalog.register_spec(multi_spec, 'extension.yaml')
426 Bar = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
427 Multi = self.type_map.get_dt_container_cls('Multi', CORE_NAMESPACE)
428 assert issubclass(Multi, MultiContainerInterface)
429 assert issubclass(Multi, Bar)
430 assert Multi.__mro__ == (Multi, Bar, MultiContainerInterface, Container, AbstractContainer, object)
431 assert Multi.__clsconf__ == [
432 dict(
433 attr='bars',
434 type=Bar,
435 add='add_bars',
436 get='get_bars',
437 create='create_bars'
438 )
439 ]
440
441 multi = Multi(
442 name='my_multi',
443 bars=[Bar(name='my_bar', data=list(range(10)), attr1='value1', attr2=10)],
444 data=list(range(10)), # from data_type_inc: Bar
445 attr1='value1', # from data_type_inc: Bar
446 attr2=10, # from data_type_inc: Bar
447 attr3=5.
448 )
449 assert multi.data == list(range(10))
450 assert multi.attr1 == 'value1'
451 assert multi.attr2 == 10
452 assert multi.bars['my_bar'] == Bar(name='my_bar', data=list(range(10)), attr1='value1', attr2=10)
453 assert multi.attr3 == 5.
454
455 def test_multi_container_spec_zero_or_more(self):
456 multi_spec = GroupSpec(
457 doc='A test extension that contains a multi',
458 data_type_def='Multi',
459 groups=[
460 GroupSpec(data_type_inc=self.bar_spec, doc='test multi', quantity='*')
461 ],
462 attributes=[
463 AttributeSpec(name='attr3', doc='a float attribute', dtype='float')
464 ]
465 )
466 self.spec_catalog.register_spec(multi_spec, 'extension.yaml')
467 Multi = self.type_map.get_dt_container_cls('Multi', CORE_NAMESPACE)
468 multi = Multi(
469 name='my_multi',
470 attr3=5.
471 )
472 assert len(multi.bars) == 0
473
474 def test_multi_container_spec_one_or_more_missing(self):
475 multi_spec = GroupSpec(
476 doc='A test extension that contains a multi',
477 data_type_def='Multi',
478 groups=[
479 GroupSpec(data_type_inc=self.bar_spec, doc='test multi', quantity='+')
480 ],
481 attributes=[
482 AttributeSpec(name='attr3', doc='a float attribute', dtype='float')
483 ]
484 )
485 self.spec_catalog.register_spec(multi_spec, 'extension.yaml')
486 Multi = self.type_map.get_dt_container_cls('Multi', CORE_NAMESPACE)
487 with self.assertRaisesWith(TypeError, "MCIClassGenerator.set_init.<locals>.__init__: missing argument 'bars'"):
488 Multi(
489 name='my_multi',
490 attr3=5.
491 )
492
493 def test_multi_container_spec_one_or_more_ok(self):
494 multi_spec = GroupSpec(
495 doc='A test extension that contains a multi',
496 data_type_def='Multi',
497 groups=[
498 GroupSpec(data_type_inc=self.bar_spec, doc='test multi', quantity='+')
499 ],
500 attributes=[
501 AttributeSpec(name='attr3', doc='a float attribute', dtype='float')
502 ]
503 )
504 self.spec_catalog.register_spec(multi_spec, 'extension.yaml')
505 Multi = self.type_map.get_dt_container_cls('Multi', CORE_NAMESPACE)
506 multi = Multi(
507 name='my_multi',
508 bars=[Bar(name='my_bar', data=list(range(10)), attr1='value1', attr2=10)],
509 attr3=5.
510 )
511 assert len(multi.bars) == 1
512
513
514 class TestDynamicContainerFixedValue(TestCase):
515
516 def setUp(self):
517 self.baz_spec = GroupSpec(
518 doc='A test group specification with a data type',
519 data_type_def='Baz',
520 attributes=[AttributeSpec(name='attr1', doc='a string attribute', dtype='text', value="fixed")]
521 )
522 self.type_map = create_test_type_map([], {}) # empty typemap
523 self.spec_catalog = self.type_map.namespace_catalog.get_namespace(CORE_NAMESPACE).catalog
524 self.spec_catalog.register_spec(self.baz_spec, 'extension.yaml')
525
526 def test_init_docval(self):
527 cls = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE) # generate the class
528 expected_args = {'name', 'skip_post_init'} # 'attr1' should not be included
529 received_args = set()
530 for x in get_docval(cls.__init__):
531 received_args.add(x['name'])
532 self.assertSetEqual(expected_args, received_args)
533
534 def test_init_fields(self):
535 cls = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE) # generate the class
536 self.assertEqual(cls.get_fields_conf(), ({'name': 'attr1', 'doc': 'a string attribute', 'settable': False},))
537
538 def test_init_object(self):
539 cls = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE) # generate the class
540 obj = cls(name="test")
541 self.assertEqual(obj.attr1, "fixed")
542
543 def test_set_value(self):
544 cls = self.type_map.get_dt_container_cls('Baz', CORE_NAMESPACE) # generate the class
545 obj = cls(name="test")
546 with self.assertRaises(AttributeError):
547 obj.attr1 = "new"
548
549
550 class TestDynamicContainerIncludingFixedName(TestCase):
551
552 def setUp(self):
553 self.baz_spec1 = GroupSpec(
554 doc='A test group specification with a data type',
555 data_type_def='Baz1',
556 )
557 self.baz_spec2 = GroupSpec(
558 doc='A test dataset specification with a data type',
559 data_type_def='Baz2',
560 )
561 self.baz_spec3 = GroupSpec(
562 doc='A test group specification with a data type',
563 data_type_def='Baz3',
564 groups=[
565 GroupSpec(
566 doc='A composition inside with a fixed name',
567 name="my_baz1",
568 data_type_inc='Baz1'
569 ),
570 ],
571 datasets=[
572 DatasetSpec(
573 doc='A composition inside with a fixed name',
574 name="my_baz2",
575 data_type_inc='Baz2'
576 ),
577 ],
578 links=[
579 LinkSpec(
580 doc='A composition inside without a fixed name',
581 name="my_baz1_link",
582 target_type='Baz1'
583 ),
584 ],
585 )
586 self.type_map = create_test_type_map([], {}) # empty typemap
587 self.spec_catalog = self.type_map.namespace_catalog.get_namespace(CORE_NAMESPACE).catalog
588 self.spec_catalog.register_spec(self.baz_spec1, 'extension.yaml')
589 self.spec_catalog.register_spec(self.baz_spec2, 'extension.yaml')
590 self.spec_catalog.register_spec(self.baz_spec3, 'extension.yaml')
591
592 def test_gen_parent_class(self):
593 baz1_cls = self.type_map.get_dt_container_cls('Baz1', CORE_NAMESPACE) # generate the class
594 baz2_cls = self.type_map.get_dt_container_cls('Baz2', CORE_NAMESPACE)
595 baz3_cls = self.type_map.get_dt_container_cls('Baz3', CORE_NAMESPACE)
596 self.assertEqual(get_docval(baz3_cls.__init__), (
597 {'name': 'name', 'type': str, 'doc': 'the name of this container'},
598 {'name': 'my_baz1', 'doc': 'A composition inside with a fixed name', 'type': baz1_cls},
599 {'name': 'my_baz2', 'doc': 'A composition inside with a fixed name', 'type': baz2_cls},
600 {'name': 'my_baz1_link', 'doc': 'A composition inside without a fixed name', 'type': baz1_cls},
601 {'name': 'skip_post_init', 'type': bool, 'default': False,
602 'doc': 'bool to skip post_init'}
603 ))
604
605 def test_init_fields(self):
606 cls = self.type_map.get_dt_container_cls('Baz3', CORE_NAMESPACE) # generate the class
607 self.assertEqual(cls.get_fields_conf(), (
608 {
609 'name': 'my_baz1',
610 'doc': 'A composition inside with a fixed name',
611 'child': True,
612 'required_name': 'my_baz1'
613 },
614 {
615 'name': 'my_baz2',
616 'doc': 'A composition inside with a fixed name',
617 'child': True,
618 'required_name': 'my_baz2'
619 },
620 {
621 'name': 'my_baz1_link',
622 'doc': 'A composition inside without a fixed name',
623 },
624 ))
625
626 def test_set_field(self):
627 baz1_cls = self.type_map.get_dt_container_cls('Baz1', CORE_NAMESPACE) # generate the class
628 baz2_cls = self.type_map.get_dt_container_cls('Baz2', CORE_NAMESPACE)
629 baz3_cls = self.type_map.get_dt_container_cls('Baz3', CORE_NAMESPACE)
630 baz1 = baz1_cls(name="my_baz1")
631 baz2 = baz2_cls(name="my_baz2")
632 baz1_link = baz1_cls(name="any_name")
633 baz3 = baz3_cls(name="test", my_baz1=baz1, my_baz2=baz2, my_baz1_link=baz1_link)
634 self.assertEqual(baz3.my_baz1, baz1)
635 self.assertEqual(baz3.my_baz2, baz2)
636 self.assertEqual(baz3.my_baz1_link, baz1_link)
637
638 def test_set_field_bad(self):
639 baz1_cls = self.type_map.get_dt_container_cls('Baz1', CORE_NAMESPACE) # generate the class
640 baz2_cls = self.type_map.get_dt_container_cls('Baz2', CORE_NAMESPACE)
641 baz3_cls = self.type_map.get_dt_container_cls('Baz3', CORE_NAMESPACE)
642
643 baz1 = baz1_cls(name="test")
644 baz2 = baz2_cls(name="my_baz2")
645 baz1_link = baz1_cls(name="my_baz1_link")
646 msg = "Field 'my_baz1' on Baz3 must be named 'my_baz1'."
647 with self.assertRaisesWith(ValueError, msg):
648 baz3_cls(name="test", my_baz1=baz1, my_baz2=baz2, my_baz1_link=baz1_link)
649
650 baz1 = baz1_cls(name="my_baz1")
651 baz2 = baz2_cls(name="test")
652 baz1_link = baz1_cls(name="my_baz1_link")
653 msg = "Field 'my_baz2' on Baz3 must be named 'my_baz2'."
654 with self.assertRaisesWith(ValueError, msg):
655 baz3_cls(name="test", my_baz1=baz1, my_baz2=baz2, my_baz1_link=baz1_link)
656
657
658 class TestGetClassSeparateNamespace(TestCase):
659
660 def setUp(self):
661 self.test_dir = tempfile.mkdtemp()
662 if os.path.exists(self.test_dir): # start clean
663 self.tearDown()
664 os.mkdir(self.test_dir)
665
666 self.bar_spec = GroupSpec(
667 doc='A test group specification with a data type',
668 data_type_def='Bar',
669 datasets=[
670 DatasetSpec(name='data', doc='a dataset', dtype='int')
671 ],
672 attributes=[
673 AttributeSpec(name='attr1', doc='a string attribute', dtype='text'),
674 AttributeSpec(name='attr2', doc='an integer attribute', dtype='int')
675 ]
676 )
677 self.type_map = TypeMap()
678 create_load_namespace_yaml(
679 namespace_name=CORE_NAMESPACE,
680 specs=[self.bar_spec],
681 output_dir=self.test_dir,
682 incl_types=dict(),
683 type_map=self.type_map
684 )
685
686 def tearDown(self):
687 shutil.rmtree(self.test_dir)
688
689 def test_get_class_separate_ns(self):
690 """Test that get_class correctly sets the name and type hierarchy across namespaces."""
691 self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
692 baz_spec = GroupSpec(
693 doc='A test extension',
694 data_type_def='Baz',
695 data_type_inc='Bar',
696 )
697 create_load_namespace_yaml(
698 namespace_name='ndx-test',
699 specs=[baz_spec],
700 output_dir=self.test_dir,
701 incl_types={CORE_NAMESPACE: ['Bar']},
702 type_map=self.type_map
703 )
704
705 cls = self.type_map.get_dt_container_cls('Baz', 'ndx-test')
706 self.assertEqual(cls.__name__, 'Baz')
707 self.assertTrue(issubclass(cls, Bar))
708
709 def _build_separate_namespaces(self):
710 # create an empty extension to test ClassGenerator._get_container_type resolution
711 # the Bar class has not been mapped yet to the bar spec
712 qux_spec = DatasetSpec(
713 doc='A test extension',
714 data_type_def='Qux'
715 )
716 spam_spec = DatasetSpec(
717 doc='A test extension',
718 data_type_def='Spam'
719 )
720 create_load_namespace_yaml(
721 namespace_name='ndx-qux',
722 specs=[qux_spec, spam_spec],
723 output_dir=self.test_dir,
724 incl_types={},
725 type_map=self.type_map
726 )
727 # resolve Spam first so that ndx-qux is resolved first
728 self.type_map.get_dt_container_cls('Spam', 'ndx-qux')
729
730 baz_spec = GroupSpec(
731 doc='A test extension',
732 data_type_def='Baz',
733 data_type_inc='Bar',
734 groups=[
735 GroupSpec(data_type_inc='Qux', doc='a qux', quantity='?'),
736 GroupSpec(data_type_inc='Bar', doc='a bar', quantity='?')
737 ]
738 )
739 moo_spec = DatasetSpec(
740 doc='A test dataset that is a 1D array of object references of Baz',
741 data_type_def='Moo',
742 shape=(None,),
743 dtype=RefSpec(
744 reftype='object',
745 target_type='Baz'
746 )
747 )
748 create_load_namespace_yaml(
749 namespace_name='ndx-test',
750 specs=[baz_spec, moo_spec],
751 output_dir=self.test_dir,
752 incl_types={
753 CORE_NAMESPACE: ['Bar'],
754 'ndx-qux': ['Qux']
755 },
756 type_map=self.type_map
757 )
758
759 def _check_classes(self, baz_cls, bar_cls, bar_cls2, qux_cls, qux_cls2):
760 self.assertEqual(qux_cls.__name__, 'Qux')
761 self.assertEqual(baz_cls.__name__, 'Baz')
762 self.assertEqual(bar_cls.__name__, 'Bar')
763 self.assertIs(bar_cls, bar_cls2) # same class, two different namespaces
764 self.assertIs(qux_cls, qux_cls2)
765 self.assertTrue(issubclass(qux_cls, Data))
766 self.assertTrue(issubclass(baz_cls, bar_cls))
767 self.assertTrue(issubclass(bar_cls, Container))
768
769 qux_inst = qux_cls(name='qux_name', data=[1])
770 bar_inst = bar_cls(name='bar_name', data=100, attr1='a string', attr2=10)
771 baz_inst = baz_cls(name='baz_name', qux=qux_inst, bar=bar_inst, data=100, attr1='a string', attr2=10)
772 self.assertIs(baz_inst.qux, qux_inst)
773
774 def test_get_class_include_from_separate_ns_1(self):
775 """Test that get_class correctly sets the name and includes types correctly across namespaces.
776 This is one of multiple tests carried out to ensure that order of which get_dt_container_cls is called
777 does not impact the results
778
779 first use EXTENSION namespace, then use ORIGINAL namespace
780 """
781 self._build_separate_namespaces()
782
783 baz_cls = self.type_map.get_dt_container_cls('Baz', 'ndx-test') # Qux and Bar are not yet resolved
784 bar_cls = self.type_map.get_dt_container_cls('Bar', 'ndx-test')
785 bar_cls2 = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
786 qux_cls = self.type_map.get_dt_container_cls('Qux', 'ndx-test')
787 qux_cls2 = self.type_map.get_dt_container_cls('Qux', 'ndx-qux')
788
789 self._check_classes(baz_cls, bar_cls, bar_cls2, qux_cls, qux_cls2)
790
791 def test_get_class_include_from_separate_ns_2(self):
792 """Test that get_class correctly sets the name and includes types correctly across namespaces.
793 This is one of multiple tests carried out to ensure that order of which get_dt_container_cls is called
794 does not impact the results
795
796 first use ORIGINAL namespace, then use EXTENSION namespace
797 """
798 self._build_separate_namespaces()
799
800 baz_cls = self.type_map.get_dt_container_cls('Baz', 'ndx-test') # Qux and Bar are not yet resolved
801 bar_cls2 = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
802 bar_cls = self.type_map.get_dt_container_cls('Bar', 'ndx-test')
803 qux_cls = self.type_map.get_dt_container_cls('Qux', 'ndx-test')
804 qux_cls2 = self.type_map.get_dt_container_cls('Qux', 'ndx-qux')
805
806 self._check_classes(baz_cls, bar_cls, bar_cls2, qux_cls, qux_cls2)
807
808 def test_get_class_include_from_separate_ns_3(self):
809 """Test that get_class correctly sets the name and includes types correctly across namespaces.
810 This is one of multiple tests carried out to ensure that order of which get_dt_container_cls is called
811 does not impact the results
812
813 first use EXTENSION namespace, then use EXTENSION namespace
814 """
815 self._build_separate_namespaces()
816
817 baz_cls = self.type_map.get_dt_container_cls('Baz', 'ndx-test') # Qux and Bar are not yet resolved
818 bar_cls = self.type_map.get_dt_container_cls('Bar', 'ndx-test')
819 bar_cls2 = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
820 qux_cls2 = self.type_map.get_dt_container_cls('Qux', 'ndx-qux')
821 qux_cls = self.type_map.get_dt_container_cls('Qux', 'ndx-test')
822
823 self._check_classes(baz_cls, bar_cls, bar_cls2, qux_cls, qux_cls2)
824
825 def test_get_class_include_from_separate_ns_4(self):
826 """Test that get_class correctly sets the name and includes types correctly across namespaces.
827 This is one of multiple tests carried out to ensure that order of which get_dt_container_cls is called
828 does not impact the results
829
830 first use ORIGINAL namespace, then use EXTENSION namespace
831 """
832 self._build_separate_namespaces()
833
834 baz_cls = self.type_map.get_dt_container_cls('Baz', 'ndx-test') # Qux and Bar are not yet resolved
835 bar_cls2 = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
836 bar_cls = self.type_map.get_dt_container_cls('Bar', 'ndx-test')
837 qux_cls2 = self.type_map.get_dt_container_cls('Qux', 'ndx-qux')
838 qux_cls = self.type_map.get_dt_container_cls('Qux', 'ndx-test')
839
840 self._check_classes(baz_cls, bar_cls, bar_cls2, qux_cls, qux_cls2)
841
842 class TestGetClassObjectReferences(TestCase):
843
844 def setUp(self):
845 self.test_dir = tempfile.mkdtemp()
846 if os.path.exists(self.test_dir): # start clean
847 self.tearDown()
848 os.mkdir(self.test_dir)
849 self.type_map = TypeMap()
850
851 def tearDown(self):
852 shutil.rmtree(self.test_dir)
853
854 def test_get_class_include_dataset_of_references(self):
855 """Test that get_class resolves datasets of object references."""
856 qux_spec = DatasetSpec(
857 doc='A test extension',
858 data_type_def='Qux'
859 )
860 moo_spec = DatasetSpec(
861 doc='A test dataset that is a 1D array of object references of Qux',
862 data_type_def='Moo',
863 shape=(None,),
864 dtype=RefSpec(
865 reftype='object',
866 target_type='Qux'
867 ),
868 )
869
870 create_load_namespace_yaml(
871 namespace_name='ndx-test',
872 specs=[qux_spec, moo_spec],
873 output_dir=self.test_dir,
874 incl_types={},
875 type_map=self.type_map
876 )
877 # no types should be resolved to start
878 assert self.type_map.get_container_classes('ndx-test') == []
879
880 self.type_map.get_dt_container_cls('Moo', 'ndx-test')
881 # now, Moo and Qux should be resolved
882 assert len(self.type_map.get_container_classes('ndx-test')) == 2
883 assert "Moo" in [c.__name__ for c in self.type_map.get_container_classes('ndx-test')]
884 assert "Qux" in [c.__name__ for c in self.type_map.get_container_classes('ndx-test')]
885
886 def test_get_class_include_attribute_object_reference(self):
887 """Test that get_class resolves data types with an attribute that is an object reference."""
888 qux_spec = DatasetSpec(
889 doc='A test extension',
890 data_type_def='Qux'
891 )
892 woo_spec = DatasetSpec(
893 doc='A test dataset that has a scalar object reference to a Qux',
894 data_type_def='Woo',
895 attributes=[
896 AttributeSpec(
897 name='attr1',
898 doc='a string attribute',
899 dtype=RefSpec(reftype='object', target_type='Qux')
900 ),
901 ]
902 )
903 create_load_namespace_yaml(
904 namespace_name='ndx-test',
905 specs=[qux_spec, woo_spec],
906 output_dir=self.test_dir,
907 incl_types={},
908 type_map=self.type_map
909 )
910 # no types should be resolved to start
911 assert self.type_map.get_container_classes('ndx-test') == []
912
913 self.type_map.get_dt_container_cls('Woo', 'ndx-test')
914 # now, Woo and Qux should be resolved
915 assert len(self.type_map.get_container_classes('ndx-test')) == 2
916 assert "Woo" in [c.__name__ for c in self.type_map.get_container_classes('ndx-test')]
917 assert "Qux" in [c.__name__ for c in self.type_map.get_container_classes('ndx-test')]
918
919 def test_get_class_include_nested_object_reference(self):
920 """Test that get_class resolves nested datasets that are object references."""
921 qux_spec = DatasetSpec(
922 doc='A test extension',
923 data_type_def='Qux'
924 )
925 spam_spec = DatasetSpec(
926 doc='A test extension',
927 data_type_def='Spam',
928 shape=(None,),
929 dtype=RefSpec(
930 reftype='object',
931 target_type='Qux'
932 ),
933 )
934 goo_spec = GroupSpec(
935 doc='A test dataset that has a nested dataset (Spam) that has a scalar object reference to a Qux',
936 data_type_def='Goo',
937 datasets=[
938 DatasetSpec(
939 doc='a dataset',
940 data_type_inc='Spam',
941 ),
942 ],
943 )
944
945 create_load_namespace_yaml(
946 namespace_name='ndx-test',
947 specs=[qux_spec, spam_spec, goo_spec],
948 output_dir=self.test_dir,
949 incl_types={},
950 type_map=self.type_map
951 )
952 # no types should be resolved to start
953 assert self.type_map.get_container_classes('ndx-test') == []
954
955 self.type_map.get_dt_container_cls('Goo', 'ndx-test')
956 # now, Goo, Spam, and Qux should be resolved
957 assert len(self.type_map.get_container_classes('ndx-test')) == 3
958 assert "Goo" in [c.__name__ for c in self.type_map.get_container_classes('ndx-test')]
959 assert "Spam" in [c.__name__ for c in self.type_map.get_container_classes('ndx-test')]
960 assert "Qux" in [c.__name__ for c in self.type_map.get_container_classes('ndx-test')]
961
962 def test_get_class_include_nested_attribute_object_reference(self):
963 """Test that get_class resolves nested datasets that have an attribute that is an object reference."""
964 qux_spec = DatasetSpec(
965 doc='A test extension',
966 data_type_def='Qux'
967 )
968 bam_spec = DatasetSpec(
969 doc='A test extension',
970 data_type_def='Bam',
971 attributes=[
972 AttributeSpec(
973 name='attr1',
974 doc='a string attribute',
975 dtype=RefSpec(reftype='object', target_type='Qux')
976 ),
977 ],
978 )
979 boo_spec = GroupSpec(
980 doc='A test dataset that has a nested dataset (Spam) that has a scalar object reference to a Qux',
981 data_type_def='Boo',
982 datasets=[
983 DatasetSpec(
984 doc='a dataset',
985 data_type_inc='Bam',
986 ),
987 ],
988 )
989
990 create_load_namespace_yaml(
991 namespace_name='ndx-test',
992 specs=[qux_spec, bam_spec, boo_spec],
993 output_dir=self.test_dir,
994 incl_types={},
995 type_map=self.type_map
996 )
997 # no types should be resolved to start
998 assert self.type_map.get_container_classes('ndx-test') == []
999
1000 self.type_map.get_dt_container_cls('Boo', 'ndx-test')
1001 # now, Boo, Bam, and Qux should be resolved
1002 assert len(self.type_map.get_container_classes('ndx-test')) == 3
1003 assert "Boo" in [c.__name__ for c in self.type_map.get_container_classes('ndx-test')]
1004 assert "Bam" in [c.__name__ for c in self.type_map.get_container_classes('ndx-test')]
1005 assert "Qux" in [c.__name__ for c in self.type_map.get_container_classes('ndx-test')]
1006
1007
1008 class EmptyBar(Container):
1009 pass
1010
1011
1012 class TestBaseProcessFieldSpec(TestCase):
1013
1014 def setUp(self):
1015 self.bar_spec = GroupSpec(
1016 doc='A test group specification with a data type',
1017 data_type_def='EmptyBar'
1018 )
1019 self.spec_catalog = SpecCatalog()
1020 self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
1021 self.namespace = SpecNamespace('a test namespace', CORE_NAMESPACE,
1022 [{'source': 'test.yaml'}],
1023 version='0.1.0',
1024 catalog=self.spec_catalog)
1025 self.namespace_catalog = NamespaceCatalog()
1026 self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
1027 self.type_map = TypeMap(self.namespace_catalog)
1028 self.type_map.register_container_type(CORE_NAMESPACE, 'EmptyBar', EmptyBar)
1029
1030 def test_update_docval(self):
1031 """Test update_docval_args for a variety of data types and mapping configurations."""
1032 spec = GroupSpec(
1033 doc="A test group specification with a data type",
1034 data_type_def="Baz",
1035 groups=[
1036 GroupSpec(doc="a group", data_type_inc="EmptyBar", quantity="?")
1037 ],
1038 datasets=[
1039 DatasetSpec(
1040 doc="a dataset",
1041 dtype="int",
1042 name="data",
1043 attributes=[
1044 AttributeSpec(name="attr2", doc="an integer attribute", dtype="int")
1045 ],
1046 )
1047 ],
1048 attributes=[
1049 AttributeSpec(name="attr1", doc="a string attribute", dtype="text"),
1050 AttributeSpec(name="attr3", doc="a numeric attribute", dtype="numeric"),
1051 AttributeSpec(name="attr4", doc="a float attribute", dtype="float"),
1052 ],
1053 )
1054
1055 expected = [
1056 {'name': 'data', 'type': (int, np.int32, np.int64), 'doc': 'a dataset'},
1057 {'name': 'attr1', 'type': str, 'doc': 'a string attribute'},
1058 {'name': 'attr2', 'type': (int, np.int32, np.int64), 'doc': 'an integer attribute'},
1059 {'name': 'attr3', 'doc': 'a numeric attribute',
1060 'type': (float, np.float32, np.float64, np.int8, np.int16,
1061 np.int32, np.int64, int, np.uint8, np.uint16,
1062 np.uint32, np.uint64)},
1063 {'name': 'attr4', 'doc': 'a float attribute',
1064 'type': (float, np.float32, np.float64)},
1065 {'name': 'bar', 'type': EmptyBar, 'doc': 'a group', 'default': None},
1066 ]
1067
1068 not_inherited_fields = {
1069 'data': spec.get_dataset('data'),
1070 'attr1': spec.get_attribute('attr1'),
1071 'attr2': spec.get_dataset('data').get_attribute('attr2'),
1072 'attr3': spec.get_attribute('attr3'),
1073 'attr4': spec.get_attribute('attr4'),
1074 'bar': spec.groups[0]
1075 }
1076
1077 docval_args = list()
1078 for i, attr_name in enumerate(not_inherited_fields):
1079 with self.subTest(attr_name=attr_name):
1080 CustomClassGenerator.process_field_spec(
1081 classdict={},
1082 docval_args=docval_args,
1083 parent_cls=EmptyBar, # <-- arbitrary class
1084 attr_name=attr_name,
1085 not_inherited_fields=not_inherited_fields,
1086 type_map=self.type_map,
1087 spec=spec
1088 )
1089 self.assertListEqual(docval_args, expected[:(i+1)]) # compare with the first i elements of expected
1090
1091 def test_update_docval_attr_shape(self):
1092 """Test that update_docval_args for an attribute with shape sets the type and shape keys."""
1093 spec = GroupSpec(
1094 doc='A test group specification with a data type',
1095 data_type_def='Baz',
1096 attributes=[
1097 AttributeSpec(name='attr1', doc='a string attribute', dtype='text', shape=[None])
1098 ]
1099 )
1100 not_inherited_fields = {'attr1': spec.get_attribute('attr1')}
1101
1102 docval_args = list()
1103 CustomClassGenerator.process_field_spec(
1104 classdict={},
1105 docval_args=docval_args,
1106 parent_cls=EmptyBar, # <-- arbitrary class
1107 attr_name='attr1',
1108 not_inherited_fields=not_inherited_fields,
1109 type_map=TypeMap(),
1110 spec=spec
1111 )
1112
1113 expected = [{'name': 'attr1', 'type': ('array_data', 'data'), 'doc': 'a string attribute', 'shape': [None]}]
1114 self.assertListEqual(docval_args, expected)
1115
1116 def test_update_docval_dset_shape(self):
1117 """Test that update_docval_args for a dataset with shape sets the type and shape keys."""
1118 spec = GroupSpec(
1119 doc='A test group specification with a data type',
1120 data_type_def='Baz',
1121 datasets=[
1122 DatasetSpec(name='dset1', doc='a string dataset', dtype='text', shape=[None])
1123 ]
1124 )
1125 not_inherited_fields = {'dset1': spec.get_dataset('dset1')}
1126
1127 docval_args = list()
1128 CustomClassGenerator.process_field_spec(
1129 classdict={},
1130 docval_args=docval_args,
1131 parent_cls=EmptyBar, # <-- arbitrary class
1132 attr_name='dset1',
1133 not_inherited_fields=not_inherited_fields,
1134 type_map=TypeMap(),
1135 spec=spec
1136 )
1137
1138 expected = [{'name': 'dset1', 'type': ('array_data', 'data'), 'doc': 'a string dataset', 'shape': [None]}]
1139 self.assertListEqual(docval_args, expected)
1140
1141 def test_update_docval_default_value(self):
1142 """Test that update_docval_args for an optional field with default value sets the default key."""
1143 spec = GroupSpec(
1144 doc='A test group specification with a data type',
1145 data_type_def='Baz',
1146 attributes=[
1147 AttributeSpec(name='attr1', doc='a string attribute', dtype='text', required=False,
1148 default_value='value')
1149 ]
1150 )
1151 not_inherited_fields = {'attr1': spec.get_attribute('attr1')}
1152
1153 docval_args = list()
1154 CustomClassGenerator.process_field_spec(
1155 classdict={},
1156 docval_args=docval_args,
1157 parent_cls=EmptyBar, # <-- arbitrary class
1158 attr_name='attr1',
1159 not_inherited_fields=not_inherited_fields,
1160 type_map=TypeMap(),
1161 spec=spec
1162 )
1163
1164 expected = [{'name': 'attr1', 'type': str, 'doc': 'a string attribute', 'default': 'value'}]
1165 self.assertListEqual(docval_args, expected)
1166
1167 def test_update_docval_default_value_none(self):
1168 """Test that update_docval_args for an optional field sets default: None."""
1169 spec = GroupSpec(
1170 doc='A test group specification with a data type',
1171 data_type_def='Baz',
1172 attributes=[
1173 AttributeSpec(name='attr1', doc='a string attribute', dtype='text', required=False)
1174 ]
1175 )
1176 not_inherited_fields = {'attr1': spec.get_attribute('attr1')}
1177
1178 docval_args = list()
1179 CustomClassGenerator.process_field_spec(
1180 classdict={},
1181 docval_args=docval_args,
1182 parent_cls=EmptyBar, # <-- arbitrary class
1183 attr_name='attr1',
1184 not_inherited_fields=not_inherited_fields,
1185 type_map=TypeMap(),
1186 spec=spec
1187 )
1188
1189 expected = [{'name': 'attr1', 'type': str, 'doc': 'a string attribute', 'default': None}]
1190 self.assertListEqual(docval_args, expected)
1191
1192 def test_update_docval_default_value_none_required_parent(self):
1193 """Test that update_docval_args for an optional field with a required parent sets default: None."""
1194 spec = GroupSpec(
1195 doc='A test group specification with a data type',
1196 data_type_def='Baz',
1197 groups=[
1198 GroupSpec(
1199 name='group1',
1200 doc='required untyped group',
1201 attributes=[
1202 AttributeSpec(name='attr1', doc='a string attribute', dtype='text', required=False)
1203 ]
1204 )
1205 ]
1206 )
1207 not_inherited_fields = {'attr1': spec.get_group('group1').get_attribute('attr1')}
1208
1209 docval_args = list()
1210 CustomClassGenerator.process_field_spec(
1211 classdict={},
1212 docval_args=docval_args,
1213 parent_cls=EmptyBar, # <-- arbitrary class
1214 attr_name='attr1',
1215 not_inherited_fields=not_inherited_fields,
1216 type_map=TypeMap(),
1217 spec=spec
1218 )
1219
1220 expected = [{'name': 'attr1', 'type': str, 'doc': 'a string attribute', 'default': None}]
1221 self.assertListEqual(docval_args, expected)
1222
1223 def test_update_docval_required_field_optional_parent(self):
1224 """Test that update_docval_args for a required field with an optional parent sets default: None."""
1225 spec = GroupSpec(
1226 doc='A test group specification with a data type',
1227 data_type_def='Baz',
1228 groups=[
1229 GroupSpec(
1230 name='group1',
1231 doc='required untyped group',
1232 attributes=[
1233 AttributeSpec(name='attr1', doc='a string attribute', dtype='text')
1234 ],
1235 quantity='?'
1236 )
1237 ]
1238 )
1239 not_inherited_fields = {'attr1': spec.get_group('group1').get_attribute('attr1')}
1240
1241 docval_args = list()
1242 CustomClassGenerator.process_field_spec(
1243 classdict={},
1244 docval_args=docval_args,
1245 parent_cls=EmptyBar, # <-- arbitrary class
1246 attr_name='attr1',
1247 not_inherited_fields=not_inherited_fields,
1248 type_map=TypeMap(),
1249 spec=spec
1250 )
1251
1252 expected = [{'name': 'attr1', 'type': str, 'doc': 'a string attribute', 'default': None}]
1253 self.assertListEqual(docval_args, expected)
1254
1255 def test_process_field_spec_overwrite(self):
1256 """Test that docval generation overwrites previous docval args."""
1257 spec = GroupSpec(
1258 doc='A test group specification with a data type',
1259 data_type_def='Baz',
1260 attributes=[
1261 AttributeSpec(name='attr1', doc='a string attribute', dtype='text', shape=[None])
1262 ]
1263 )
1264 not_inherited_fields = {'attr1': spec.get_attribute('attr1')}
1265
1266 docval_args = [{'name': 'attr1', 'type': ('array_data', 'data'), 'doc': 'a string attribute',
1267 'shape': [[None], [None, None]]}, # this dict will be overwritten below
1268 {'name': 'attr2', 'type': ('array_data', 'data'), 'doc': 'a string attribute',
1269 'shape': [[None], [None, None]]}]
1270 CustomClassGenerator.process_field_spec(
1271 classdict={},
1272 docval_args=docval_args,
1273 parent_cls=EmptyBar, # <-- arbitrary class
1274 attr_name='attr1',
1275 not_inherited_fields=not_inherited_fields,
1276 type_map=TypeMap(),
1277 spec=spec
1278 )
1279
1280 expected = [{'name': 'attr1', 'type': ('array_data', 'data'), 'doc': 'a string attribute',
1281 'shape': [None]},
1282 {'name': 'attr2', 'type': ('array_data', 'data'), 'doc': 'a string attribute',
1283 'shape': [[None], [None, None]]}]
1284 self.assertListEqual(docval_args, expected)
1285
1286 def test_process_field_spec_link(self):
1287 """Test that processing a link spec does not set child=True in __fields__."""
1288 classdict = {}
1289 not_inherited_fields = {'attr3': LinkSpec(name='attr3', target_type='EmptyBar', doc='a link')}
1290 CustomClassGenerator.process_field_spec(
1291 classdict=classdict,
1292 docval_args=[],
1293 parent_cls=EmptyBar, # <-- arbitrary class
1294 attr_name='attr3',
1295 not_inherited_fields=not_inherited_fields,
1296 type_map=self.type_map,
1297 spec=GroupSpec('dummy', 'doc')
1298 )
1299
1300 expected = {'__fields__': [{'name': 'attr3', 'doc': 'a link'}]}
1301 self.assertDictEqual(classdict, expected)
1302
1303 def test_post_process_fixed_name(self):
1304 """Test that docval generation for a class with a fixed name does not contain a docval arg for name."""
1305 spec = GroupSpec(
1306 doc='A test group specification with a data type',
1307 data_type_def='Baz',
1308 name='MyBaz', # <-- fixed name
1309 attributes=[
1310 AttributeSpec(
1311 name='attr1',
1312 doc='a string attribute',
1313 dtype='text',
1314 shape=[None]
1315 )
1316 ]
1317 )
1318
1319 classdict = {}
1320 bases = [Container]
1321 docval_args = [{'name': 'name', 'type': str, 'doc': 'name'},
1322 {'name': 'attr1', 'type': ('array_data', 'data'), 'doc': 'a string attribute',
1323 'shape': [None]}]
1324 CustomClassGenerator.post_process(classdict, bases, docval_args, spec)
1325
1326 expected = [{'name': 'attr1', 'type': ('array_data', 'data'), 'doc': 'a string attribute',
1327 'shape': [None]}]
1328 self.assertListEqual(docval_args, expected)
1329
1330 def test_post_process_default_name(self):
1331 """Test that docval generation for a class with a default name has the default value for name set."""
1332 spec = GroupSpec(
1333 doc='A test group specification with a data type',
1334 data_type_def='Baz',
1335 default_name='MyBaz', # <-- default name
1336 attributes=[
1337 AttributeSpec(
1338 name='attr1',
1339 doc='a string attribute',
1340 dtype='text',
1341 shape=[None]
1342 )
1343 ]
1344 )
1345
1346 classdict = {}
1347 bases = [Container]
1348 docval_args = [{'name': 'name', 'type': str, 'doc': 'name'},
1349 {'name': 'attr1', 'type': ('array_data', 'data'), 'doc': 'a string attribute',
1350 'shape': [None]}]
1351 CustomClassGenerator.post_process(classdict, bases, docval_args, spec)
1352
1353 expected = [{'name': 'name', 'type': str, 'doc': 'name', 'default': 'MyBaz'},
1354 {'name': 'attr1', 'type': ('array_data', 'data'), 'doc': 'a string attribute',
1355 'shape': [None]}]
1356 self.assertListEqual(docval_args, expected)
1357
1358
1359 class TestMCIProcessFieldSpec(TestCase):
1360
1361 def setUp(self):
1362 bar_spec = GroupSpec(
1363 doc='A test group specification with a data type',
1364 data_type_def='EmptyBar'
1365 )
1366 specs = [bar_spec]
1367 container_classes = {'EmptyBar': EmptyBar}
1368 self.type_map = create_test_type_map(specs, container_classes)
1369
1370 def test_update_docval(self):
1371 spec = GroupSpec(data_type_inc='EmptyBar', doc='test multi', quantity='*')
1372 classdict = dict()
1373 docval_args = []
1374 not_inherited_fields = {'empty_bars': spec}
1375 MCIClassGenerator.process_field_spec(
1376 classdict=classdict,
1377 docval_args=docval_args,
1378 parent_cls=Container,
1379 attr_name='empty_bars',
1380 not_inherited_fields=not_inherited_fields,
1381 type_map=self.type_map,
1382 spec=spec
1383 )
1384
1385 expected = [
1386 dict(
1387 attr='empty_bars',
1388 type=EmptyBar,
1389 add='add_empty_bars',
1390 get='get_empty_bars',
1391 create='create_empty_bars'
1392 )
1393 ]
1394 self.assertEqual(classdict['__clsconf__'], expected)
1395
1396 def test_update_init_zero_or_more(self):
1397 spec = GroupSpec(data_type_inc='EmptyBar', doc='test multi', quantity='*')
1398 classdict = dict()
1399 docval_args = []
1400 not_inherited_fields = {'empty_bars': spec}
1401 MCIClassGenerator.process_field_spec(
1402 classdict=classdict,
1403 docval_args=docval_args,
1404 parent_cls=Container,
1405 attr_name='empty_bars',
1406 not_inherited_fields=not_inherited_fields,
1407 type_map=self.type_map,
1408 spec=spec
1409 )
1410
1411 expected = [{'name': 'empty_bars', 'type': (list, tuple, dict, EmptyBar), 'doc': 'test multi', 'default': None}]
1412 self.assertListEqual(docval_args, expected)
1413
1414 def test_update_init_one_or_more(self):
1415 spec = GroupSpec(data_type_inc='EmptyBar', doc='test multi', quantity='+')
1416 classdict = dict()
1417 docval_args = []
1418 not_inherited_fields = {'empty_bars': spec}
1419 MCIClassGenerator.process_field_spec(
1420 classdict=classdict,
1421 docval_args=docval_args,
1422 parent_cls=Bar,
1423 attr_name='empty_bars',
1424 not_inherited_fields=not_inherited_fields,
1425 type_map=self.type_map,
1426 spec=spec
1427 )
1428
1429 expected = [{'name': 'empty_bars', 'type': (list, tuple, dict, EmptyBar), 'doc': 'test multi'}]
1430 self.assertListEqual(docval_args, expected)
1431
1432 def test_post_process(self):
1433 multi_spec = GroupSpec(
1434 doc='A test extension that contains a multi',
1435 data_type_def='Multi',
1436 groups=[
1437 GroupSpec(data_type_inc='EmptyBar', doc='test multi', quantity='*')
1438 ],
1439 )
1440 classdict = dict(
1441 __clsconf__=[
1442 dict(
1443 attr='empty_bars',
1444 type=EmptyBar,
1445 add='add_empty_bars',
1446 get='get_empty_bars',
1447 create='create_empty_bars'
1448 )
1449 ]
1450 )
1451 bases = [Bar]
1452 docval_args = []
1453 MCIClassGenerator.post_process(classdict, bases, docval_args, multi_spec)
1454 self.assertEqual(bases, [Bar, MultiContainerInterface])
1455
1456 def test_post_process_already_multi(self):
1457 class Multi1(MultiContainerInterface):
1458 pass
1459
1460 multi_spec = GroupSpec(
1461 doc='A test extension that contains a multi and extends a multi',
1462 data_type_def='Multi2',
1463 data_type_inc='Multi1',
1464 groups=[
1465 GroupSpec(data_type_inc='EmptyBar', doc='test multi', quantity='*')
1466 ],
1467 )
1468 classdict = dict(
1469 __clsconf__=[
1470 dict(
1471 attr='empty_bars',
1472 type=EmptyBar,
1473 add='add_empty_bars',
1474 get='get_empty_bars',
1475 create='create_empty_bars'
1476 )
1477 ]
1478 )
1479 bases = [Multi1]
1480 docval_args = []
1481 MCIClassGenerator.post_process(classdict, bases, docval_args, multi_spec)
1482 self.assertEqual(bases, [Multi1])
1483
1484 def test_post_process_container(self):
1485 class Multi1(MultiContainerInterface):
1486 pass
1487
1488 multi_spec = GroupSpec(
1489 doc='A test extension that contains a multi and extends a multi',
1490 data_type_def='Multi1',
1491 groups=[
1492 GroupSpec(data_type_inc='EmptyBar', doc='test multi', quantity='*')
1493 ],
1494 )
1495 classdict = dict(
1496 __clsconf__=[
1497 dict(
1498 attr='empty_bars',
1499 type=EmptyBar,
1500 add='add_empty_bars',
1501 get='get_empty_bars',
1502 create='create_empty_bars'
1503 )
1504 ]
1505 )
1506 bases = [Container]
1507 docval_args = []
1508 MCIClassGenerator.post_process(classdict, bases, docval_args, multi_spec)
1509 self.assertEqual(bases, [MultiContainerInterface, Container])