Ejemplo n.º 1
0
class TestObjectMapper(with_metaclass(ABCMeta, unittest.TestCase)):
    def setUp(self):
        self.setUpBarSpec()
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
        self.type_map.register_map(Bar, ObjectMapper)
        self.manager = BuildManager(self.type_map)
        self.mapper = ObjectMapper(self.bar_spec)

    def setUpBarSpec(self):
        raise unittest.SkipTest('setUpBarSpec not implemented')

    def test_default_mapping(self):
        attr_map = self.mapper.get_attr_names(self.bar_spec)
        keys = set(attr_map.keys())
        for key in keys:
            with self.subTest(key=key):
                self.assertIs(attr_map[key], self.mapper.get_attr_spec(key))
                self.assertIs(attr_map[key], self.mapper.get_carg_spec(key))
Ejemplo n.º 2
0
class TestBase(unittest.TestCase):
    def setUp(self):
        self.foo_spec = GroupSpec(
            'A test group specification with a data type',
            data_type_def='Foo',
            datasets=[
                DatasetSpec('an example dataset',
                            'int',
                            name='my_data',
                            attributes=[
                                AttributeSpec('attr2',
                                              'an example integer attribute',
                                              'int')
                            ])
            ],
            attributes=[
                AttributeSpec('attr1', 'an example string attribute', 'text')
            ])

        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.foo_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo)
        self.type_map.register_map(Foo, ObjectMapper)
        self.manager = BuildManager(self.type_map)
Ejemplo n.º 3
0
def create_test_type_map(specs, container_classes, mappers=None):
    """
    Create a TypeMap with the specs registered under a test namespace, and classes and mappers registered to type names.
    :param specs: list of specs
    :param container_classes: dict of type name to container class
    :param mappers: (optional) dict of type name to mapper class
    :return: the constructed TypeMap
    """
    spec_catalog = SpecCatalog()
    schema_file = 'test.yaml'
    for s in specs:
        spec_catalog.register_spec(s, schema_file)
    namespace = SpecNamespace(doc='a test namespace',
                              name=CORE_NAMESPACE,
                              schema=[{
                                  'source': schema_file
                              }],
                              version='0.1.0',
                              catalog=spec_catalog)
    namespace_catalog = NamespaceCatalog()
    namespace_catalog.add_namespace(CORE_NAMESPACE, namespace)
    type_map = TypeMap(namespace_catalog)
    for type_name, container_cls in container_classes.items():
        type_map.register_container_type(CORE_NAMESPACE, type_name,
                                         container_cls)
    if mappers:
        for type_name, mapper_cls in mappers.items():
            container_cls = container_classes[type_name]
            type_map.register_map(container_cls, mapper_cls)
    return type_map
Ejemplo n.º 4
0
 def setUpManager(self, specs):
     spec_catalog = SpecCatalog()
     schema_file = 'test.yaml'
     for s in specs:
         spec_catalog.register_spec(s, schema_file)
     namespace = SpecNamespace(doc='a test namespace',
                               name=CORE_NAMESPACE,
                               schema=[{
                                   'source': schema_file
                               }],
                               version='0.1.0',
                               catalog=spec_catalog)
     namespace_catalog = NamespaceCatalog()
     namespace_catalog.add_namespace(CORE_NAMESPACE, namespace)
     type_map = TypeMap(namespace_catalog)
     type_map.register_container_type(CORE_NAMESPACE, 'SimpleFoo',
                                      SimpleFoo)
     type_map.register_container_type(CORE_NAMESPACE, 'NotSimpleFoo',
                                      NotSimpleFoo)
     type_map.register_container_type(CORE_NAMESPACE, 'SimpleQux',
                                      SimpleQux)
     type_map.register_container_type(CORE_NAMESPACE, 'NotSimpleQux',
                                      NotSimpleQux)
     type_map.register_container_type(CORE_NAMESPACE, 'SimpleBucket',
                                      SimpleBucket)
     type_map.register_map(SimpleBucket, self.setUpBucketMapper())
     self.manager = BuildManager(type_map)
Ejemplo n.º 5
0
class ObjectMapperMixin(metaclass=ABCMeta):
    def setUp(self):
        self.setUpBarSpec()
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
        self.manager = BuildManager(self.type_map)
        self.mapper = ObjectMapper(self.bar_spec)

    @abstractmethod
    def setUpBarSpec(self):
        raise NotImplementedError(
            'Cannot run test unless setUpBarSpec is implemented')

    def test_default_mapping(self):
        attr_map = self.mapper.get_attr_names(self.bar_spec)
        keys = set(attr_map.keys())
        for key in keys:
            with self.subTest(key=key):
                self.assertIs(attr_map[key], self.mapper.get_attr_spec(key))
                self.assertIs(attr_map[key], self.mapper.get_carg_spec(key))
Ejemplo n.º 6
0
class TestObjectMapperBadValue(TestCase):
    def test_bad_value(self):
        """Test that an error is raised if the container attribute value for a spec with a data type is not a container
        or collection of containers.
        """
        class Qux(Container):
            @docval(
                {
                    'name': 'name',
                    'type': str,
                    'doc': 'the name of this Qux'
                }, {
                    'name': 'foo',
                    'type': int,
                    'doc': 'a group'
                })
            def __init__(self, **kwargs):
                name, foo = getargs('name', 'foo', kwargs)
                super().__init__(name=name)
                self.__foo = foo
                if isinstance(foo, Foo):
                    self.__foo.parent = self

            @property
            def foo(self):
                return self.__foo

        self.qux_spec = GroupSpec(
            doc='A test group specification with data type Qux',
            data_type_def='Qux',
            groups=[GroupSpec('an example dataset', data_type_inc='Foo')])
        self.foo_spec = GroupSpec(
            'A test group specification with data type Foo',
            data_type_def='Foo')
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.qux_spec, 'test.yaml')
        self.spec_catalog.register_spec(self.foo_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Qux', Qux)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo)
        self.manager = BuildManager(self.type_map)
        self.mapper = ObjectMapper(self.qux_spec)

        container = Qux('my_qux', foo=1)
        msg = "Qux 'my_qux' attribute 'foo' has unexpected type."
        with self.assertRaisesWith(ContainerConfigurationError, msg):
            self.mapper.build(container, self.manager)
Ejemplo n.º 7
0
class TestDataIOEdgeCases(TestCase):
    def setUp(self):
        self.setUpBazSpec()
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.baz_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Baz', Baz)
        self.type_map.register_map(Baz, ObjectMapper)
        self.manager = BuildManager(self.type_map)
        self.mapper = ObjectMapper(self.baz_spec)

    def setUpBazSpec(self):
        self.baz_spec = DatasetSpec(
            doc='an Baz type',
            dtype=None,
            name='MyBaz',
            data_type_def='Baz',
            shape=[None],
            attributes=[
                AttributeSpec('baz_attr', 'an example string attribute',
                              'text')
            ])

    def test_build_dataio(self):
        """Test building of a dataset with data_type and no dtype with value DataIO."""
        container = Baz('my_baz', H5DataIO(['a', 'b', 'c', 'd'], chunks=True),
                        'value1')
        builder = self.type_map.build(container)
        self.assertIsInstance(builder.get('data'), H5DataIO)

    def test_build_datachunkiterator(self):
        """Test building of a dataset with data_type and no dtype with value DataChunkIterator."""
        container = Baz('my_baz', DataChunkIterator(['a', 'b', 'c', 'd']),
                        'value1')
        builder = self.type_map.build(container)
        self.assertIsInstance(builder.get('data'), DataChunkIterator)

    def test_build_dataio_datachunkiterator(self):  # hdmf#512
        """Test building of a dataset with no dtype and no data_type with value DataIO wrapping a DCI."""
        container = Baz(
            'my_baz',
            H5DataIO(DataChunkIterator(['a', 'b', 'c', 'd']), chunks=True),
            'value1')
        builder = self.type_map.build(container)
        self.assertIsInstance(builder.get('data'), H5DataIO)
        self.assertIsInstance(builder.get('data').data, DataChunkIterator)
Ejemplo n.º 8
0
class TestTypeMap(unittest.TestCase):
    def setUp(self):
        self.bar_spec = GroupSpec(
            'A test group specification with a data type', data_type_def='Bar')
        self.foo_spec = GroupSpec(
            'A test group specification with data type Foo',
            data_type_def='Foo')
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
        self.spec_catalog.register_spec(self.foo_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo)
        # self.build_manager = BuildManager(self.type_map)

    def test_get_map_unique_mappers(self):
        self.type_map.register_map(Bar, ObjectMapper)
        self.type_map.register_map(Foo, ObjectMapper)
        bar_inst = Bar('my_bar', list(range(10)), 'value1', 10)
        foo_inst = Foo(name='my_foo')
        bar_mapper = self.type_map.get_map(bar_inst)
        foo_mapper = self.type_map.get_map(foo_inst)
        self.assertIsNot(bar_mapper, foo_mapper)

    def test_get_map(self):
        self.type_map.register_map(Bar, ObjectMapper)
        container_inst = Bar('my_bar', list(range(10)), 'value1', 10)
        mapper = self.type_map.get_map(container_inst)
        self.assertIsInstance(mapper, ObjectMapper)
        self.assertIs(mapper.spec, self.bar_spec)
        mapper2 = self.type_map.get_map(container_inst)
        self.assertIs(mapper, mapper2)

    def test_get_map_register(self):
        class MyMap(ObjectMapper):
            pass

        self.type_map.register_map(Bar, MyMap)

        container_inst = Bar('my_bar', list(range(10)), 'value1', 10)
        mapper = self.type_map.get_map(container_inst)
        self.assertIs(mapper.spec, self.bar_spec)
        self.assertIsInstance(mapper, MyMap)
Ejemplo n.º 9
0
 def customSetUp(self, bar_spec):
     spec_catalog = SpecCatalog()
     spec_catalog.register_spec(bar_spec, 'test.yaml')
     namespace = SpecNamespace('a test namespace',
                               CORE_NAMESPACE, [{
                                   'source': 'test.yaml'
                               }],
                               version='0.1.0',
                               catalog=spec_catalog)
     namespace_catalog = NamespaceCatalog()
     namespace_catalog.add_namespace(CORE_NAMESPACE, namespace)
     type_map = TypeMap(namespace_catalog)
     type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
     return type_map
Ejemplo n.º 10
0
class TestDataMapScalar(TestCase):
    def setUp(self):
        self.setUpBazSpec()
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.baz_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'BazScalar',
                                              BazScalar)
        self.type_map.register_map(BazScalar, ObjectMapper)
        self.manager = BuildManager(self.type_map)
        self.mapper = ObjectMapper(self.baz_spec)

    def setUpBazSpec(self):
        self.baz_spec = DatasetSpec(doc='a BazScalar type',
                                    dtype='int',
                                    name='MyBaz',
                                    data_type_def='BazScalar')

    def test_construct_scalar_dataset(self):
        """Test constructing a Data object with an h5py.Dataset with shape (1, ) for scalar spec."""
        with h5py.File('test.h5', 'w') as file:
            test_ds = file.create_dataset('test_ds', data=[1])
            expected = BazScalar(
                name='MyBaz',
                data=1,
            )
            builder = DatasetBuilder(
                name='MyBaz',
                data=test_ds,
                attributes={
                    'data_type': 'BazScalar',
                    'namespace': CORE_NAMESPACE,
                    'object_id': expected.object_id
                },
            )
            container = self.mapper.construct(builder, self.manager)
            self.assertTrue(np.issubdtype(type(
                container.data), np.integer))  # as opposed to h5py.Dataset
            self.assertContainerEqual(container, expected)
        os.remove('test.h5')
Ejemplo n.º 11
0
class TestGetSubSpec(unittest.TestCase):
    def setUp(self):
        self.bar_spec = GroupSpec(
            'A test group specification with a data type', data_type_def='Bar')
        spec_catalog = SpecCatalog()
        spec_catalog.register_spec(self.bar_spec, 'test.yaml')
        namespace = SpecNamespace('a test namespace',
                                  CORE_NAMESPACE, [{
                                      'source': 'test.yaml'
                                  }],
                                  catalog=spec_catalog)
        namespace_catalog = NamespaceCatalog()
        namespace_catalog.add_namespace(CORE_NAMESPACE, namespace)
        self.type_map = TypeMap(namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)

    def test_get_subspec_data_type_noname(self):
        parent_spec = GroupSpec('Something to hold a Bar',
                                'bar_bucket',
                                groups=[self.bar_spec])
        sub_builder = GroupBuilder('my_bar',
                                   attributes={
                                       'data_type': 'Bar',
                                       'namespace': CORE_NAMESPACE
                                   })
        builder = GroupBuilder('bar_bucket',
                               groups={'my_bar': sub_builder})  # noqa: F841
        result = self.type_map.get_subspec(parent_spec, sub_builder)
        self.assertIs(result, self.bar_spec)

    def test_get_subspec_named(self):
        child_spec = GroupSpec('A test group specification with a data type',
                               'my_subgroup')
        parent_spec = GroupSpec('Something to hold a Bar',
                                'my_group',
                                groups=[child_spec])
        sub_builder = GroupBuilder('my_subgroup',
                                   attributes={
                                       'data_type': 'Bar',
                                       'namespace': CORE_NAMESPACE
                                   })
        builder = GroupBuilder('my_group', groups={'my_bar':
                                                   sub_builder})  # noqa: F841
        result = self.type_map.get_subspec(parent_spec, sub_builder)
        self.assertIs(result, child_spec)
Ejemplo n.º 12
0
class BazSpecMixin:
    def setUp(self):
        self.setUpBazSpec()
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.baz_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Baz', Baz)
        self.type_map.register_map(Baz, ObjectMapper)
        self.manager = BuildManager(self.type_map)
        self.mapper = ObjectMapper(self.baz_spec)

    def setUpBazSpec(self):
        raise NotImplementedError('Test must implement this method.')
Ejemplo n.º 13
0
 def setUp(self):
     self.set_up_specs()
     spec_catalog = SpecCatalog()
     spec_catalog.register_spec(self.bar_data_spec, 'test.yaml')
     spec_catalog.register_spec(self.bar_data_holder_spec, 'test.yaml')
     namespace = SpecNamespace(doc='a test namespace',
                               name=CORE_NAMESPACE,
                               schema=[{
                                   'source': 'test.yaml'
                               }],
                               version='0.1.0',
                               catalog=spec_catalog)
     namespace_catalog = NamespaceCatalog()
     namespace_catalog.add_namespace(CORE_NAMESPACE, namespace)
     type_map = TypeMap(namespace_catalog)
     type_map.register_container_type(CORE_NAMESPACE, 'BarData', BarData)
     type_map.register_container_type(CORE_NAMESPACE, 'BarDataHolder',
                                      BarDataHolder)
     type_map.register_map(BarData, ExtBarDataMapper)
     type_map.register_map(BarDataHolder, ObjectMapper)
     self.manager = BuildManager(type_map)
Ejemplo n.º 14
0
class BuildDatasetOfReferencesMixin:
    def setUp(self):
        self.setUpBazSpec()
        self.foo_spec = GroupSpec(
            doc='A test group specification with a data type',
            data_type_def='Foo',
            datasets=[
                DatasetSpec(name='my_data',
                            doc='an example dataset',
                            dtype='int')
            ],
            attributes=[
                AttributeSpec(name='attr1',
                              doc='an example string attribute',
                              dtype='text'),
                AttributeSpec(name='attr2',
                              doc='an example int attribute',
                              dtype='int'),
                AttributeSpec(name='attr3',
                              doc='an example float attribute',
                              dtype='float')
            ])
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.baz_spec, 'test.yaml')
        self.spec_catalog.register_spec(self.foo_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Baz', Baz)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo)
        self.type_map.register_map(Baz, ObjectMapper)
        self.type_map.register_map(Foo, ObjectMapper)
        self.manager = BuildManager(self.type_map)
Ejemplo n.º 15
0
class TestDataMap(unittest.TestCase):
    def setUp(self):
        self.setUpBazSpec()
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.baz_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Baz', Baz)
        self.type_map.register_map(Baz, ObjectMapper)
        self.manager = BuildManager(self.type_map)
        self.mapper = ObjectMapper(self.baz_spec)

    def setUpBazSpec(self):
        self.baz_spec = DatasetSpec(
            'an Baz type',
            'int',
            name='MyBaz',
            data_type_def='Baz',
            attributes=[
                AttributeSpec('baz_attr', 'an example string attribute',
                              'text')
            ])

    def test_build(self):
        ''' Test default mapping functionality when no attributes are nested '''
        container = Baz('my_baz', list(range(10)),
                        'abcdefghijklmnopqrstuvwxyz')
        builder = self.mapper.build(container, self.manager)
        expected = DatasetBuilder(
            'my_baz',
            list(range(10)),
            attributes={'baz_attr': 'abcdefghijklmnopqrstuvwxyz'})
        self.assertDictEqual(builder, expected)
Ejemplo n.º 16
0
class TestDataMap(BazSpecMixin, TestCase):
    def setUp(self):
        self.setUpBazSpec()
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.baz_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Baz', Baz)
        self.type_map.register_map(Baz, ObjectMapper)
        self.manager = BuildManager(self.type_map)
        self.mapper = ObjectMapper(self.baz_spec)

    def setUpBazSpec(self):
        self.baz_spec = DatasetSpec(
            doc='an Baz type',
            dtype='int',
            name='MyBaz',
            data_type_def='Baz',
            shape=[None],
            attributes=[
                AttributeSpec('baz_attr', 'an example string attribute',
                              'text')
            ])

    def test_build(self):
        ''' Test default mapping functionality when no attributes are nested '''
        container = Baz('MyBaz', list(range(10)), 'abcdefghijklmnopqrstuvwxyz')
        builder = self.mapper.build(container, self.manager)
        expected = DatasetBuilder(
            'MyBaz',
            list(range(10)),
            attributes={'baz_attr': 'abcdefghijklmnopqrstuvwxyz'})
        self.assertBuilderEqual(builder, expected)

    def test_build_empty_data(self):
        """Test building of a Data object with empty data."""
        baz_inc_spec = DatasetSpec(doc='doc',
                                   data_type_inc='Baz',
                                   quantity=ZERO_OR_MANY)
        baz_holder_spec = GroupSpec(doc='doc',
                                    data_type_def='BazHolder',
                                    datasets=[baz_inc_spec])
        self.spec_catalog.register_spec(baz_holder_spec, 'test.yaml')
        self.type_map.register_container_type(CORE_NAMESPACE, 'BazHolder',
                                              BazHolder)
        self.holder_mapper = ObjectMapper(baz_holder_spec)

        baz = Baz('MyBaz', [], 'abcdefghijklmnopqrstuvwxyz')
        holder = BazHolder('holder', [baz])

        builder = self.holder_mapper.build(holder, self.manager)
        expected = GroupBuilder(
            name='holder',
            datasets=[
                DatasetBuilder(name='MyBaz',
                               data=[],
                               attributes={
                                   'baz_attr': 'abcdefghijklmnopqrstuvwxyz',
                                   'data_type': 'Baz',
                                   'namespace': 'test_core',
                                   'object_id': baz.object_id
                               })
            ])
        self.assertBuilderEqual(builder, expected)

    def test_append(self):
        with h5py.File('test.h5', 'w') as file:
            test_ds = file.create_dataset('test_ds',
                                          data=[1, 2, 3],
                                          chunks=True,
                                          maxshape=(None, ))
            container = Baz('MyBaz', test_ds, 'abcdefghijklmnopqrstuvwxyz')
            container.append(4)
            np.testing.assert_array_equal(container[:], [1, 2, 3, 4])
        os.remove('test.h5')

    def test_extend(self):
        with h5py.File('test.h5', 'w') as file:
            test_ds = file.create_dataset('test_ds',
                                          data=[1, 2, 3],
                                          chunks=True,
                                          maxshape=(None, ))
            container = Baz('MyBaz', test_ds, 'abcdefghijklmnopqrstuvwxyz')
            container.extend([4, 5])
            np.testing.assert_array_equal(container[:], [1, 2, 3, 4, 5])
        os.remove('test.h5')
Ejemplo n.º 17
0
class TestDataMapScalarCompound(TestCase):
    def setUp(self):
        self.setUpBazSpec()
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.baz_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE,
                                              'BazScalarCompound',
                                              BazScalarCompound)
        self.type_map.register_map(BazScalarCompound, ObjectMapper)
        self.manager = BuildManager(self.type_map)
        self.mapper = ObjectMapper(self.baz_spec)

    def setUpBazSpec(self):
        self.baz_spec = DatasetSpec(
            doc='a BazScalarCompound type',
            dtype=[
                DtypeSpec(name='id',
                          dtype='uint64',
                          doc='The unique identifier in this table.'),
                DtypeSpec(name='attr1', dtype='text', doc='A text attribute.'),
            ],
            name='MyBaz',
            data_type_def='BazScalarCompound',
        )

    def test_construct_scalar_compound_dataset(self):
        """Test construct on a compound h5py.Dataset with shape (1, ) for scalar spec does not resolve the data."""
        with h5py.File('test.h5', 'w') as file:
            comp_type = np.dtype([('id', np.uint64),
                                  ('attr1', h5py.special_dtype(vlen=str))])
            test_ds = file.create_dataset(name='test_ds',
                                          data=np.array((1, 'text'),
                                                        dtype=comp_type),
                                          shape=(1, ),
                                          dtype=comp_type)
            expected = BazScalarCompound(
                name='MyBaz',
                data=(1, 'text'),
            )
            builder = DatasetBuilder(
                name='MyBaz',
                data=test_ds,
                attributes={
                    'data_type': 'BazScalarCompound',
                    'namespace': CORE_NAMESPACE,
                    'object_id': expected.object_id
                },
            )
            container = self.mapper.construct(builder, self.manager)
            self.assertEqual(type(container.data), h5py.Dataset)
            self.assertContainerEqual(container, expected)
        os.remove('test.h5')
Ejemplo n.º 18
0
class TestDataMap(TestCase):
    def setUp(self):
        self.setUpBazSpec()
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.baz_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Baz', Baz)
        self.type_map.register_map(Baz, ObjectMapper)
        self.manager = BuildManager(self.type_map)
        self.mapper = ObjectMapper(self.baz_spec)

    def setUpBazSpec(self):
        self.baz_spec = DatasetSpec(
            'an Baz type',
            'int',
            name='MyBaz',
            data_type_def='Baz',
            shape=[None],
            attributes=[
                AttributeSpec('baz_attr', 'an example string attribute',
                              'text')
            ])

    def test_build(self):
        ''' Test default mapping functionality when no attributes are nested '''
        container = Baz('my_baz', list(range(10)),
                        'abcdefghijklmnopqrstuvwxyz')
        builder = self.mapper.build(container, self.manager)
        expected = DatasetBuilder(
            'my_baz',
            list(range(10)),
            attributes={'baz_attr': 'abcdefghijklmnopqrstuvwxyz'})
        self.assertDictEqual(builder, expected)

    def test_append(self):
        with h5py.File('test.h5', 'w') as file:
            test_ds = file.create_dataset('test_ds',
                                          data=[1, 2, 3],
                                          chunks=True,
                                          maxshape=(None, ))
            container = Baz('my_baz', test_ds, 'abcdefghijklmnopqrstuvwxyz')
            container.append(4)
            np.testing.assert_array_equal(container[:], [1, 2, 3, 4])
        os.remove('test.h5')

    def test_extend(self):
        with h5py.File('test.h5', 'w') as file:
            test_ds = file.create_dataset('test_ds',
                                          data=[1, 2, 3],
                                          chunks=True,
                                          maxshape=(None, ))
            container = Baz('my_baz', test_ds, 'abcdefghijklmnopqrstuvwxyz')
            container.extend([4, 5])
            np.testing.assert_array_equal(container[:], [1, 2, 3, 4, 5])
        os.remove('test.h5')
Ejemplo n.º 19
0
class TestReference(TestCase):
    def setUp(self):
        self.foo_spec = GroupSpec(
            'A test group specification with data type Foo',
            data_type_def='Foo')
        self.bar_spec = GroupSpec(
            'A test group specification with a data type Bar',
            data_type_def='Bar',
            datasets=[DatasetSpec('an example dataset', 'int', name='data')],
            attributes=[
                AttributeSpec('attr1', 'an example string attribute', 'text'),
                AttributeSpec('attr2', 'an example integer attribute', 'int'),
                AttributeSpec('foo',
                              'a referenced foo',
                              RefSpec('Foo', 'object'),
                              required=False)
            ])

        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.foo_spec, 'test.yaml')
        self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
        self.manager = BuildManager(self.type_map)
        self.foo_mapper = ObjectMapper(self.foo_spec)
        self.bar_mapper = ObjectMapper(self.bar_spec)

    def test_build_attr_ref(self):
        ''' Test default mapping functionality when one container contains an attribute reference to another container.
        '''
        foo_inst = Foo('my_foo')
        bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10, foo=foo_inst)
        bar_inst2 = Bar('my_bar2', list(range(10)), 'value1', 10)

        foo_builder = self.manager.build(foo_inst, root=True)
        bar1_builder = self.manager.build(bar_inst1, root=True)  # adds refs
        bar2_builder = self.manager.build(bar_inst2, root=True)

        foo_expected = GroupBuilder('my_foo',
                                    attributes={
                                        'data_type': 'Foo',
                                        'namespace': CORE_NAMESPACE,
                                        'object_id': foo_inst.object_id
                                    })
        bar1_expected = GroupBuilder(
            'n/a',  # name doesn't matter
            datasets={'data': DatasetBuilder('data', list(range(10)))},
            attributes={
                'attr1': 'value1',
                'attr2': 10,
                'foo': ReferenceBuilder(foo_expected),
                'data_type': 'Bar',
                'namespace': CORE_NAMESPACE,
                'object_id': bar_inst1.object_id
            })
        bar2_expected = GroupBuilder(
            'n/a',  # name doesn't matter
            datasets={'data': DatasetBuilder('data', list(range(10)))},
            attributes={
                'attr1': 'value1',
                'attr2': 10,
                'data_type': 'Bar',
                'namespace': CORE_NAMESPACE,
                'object_id': bar_inst2.object_id
            })
        self.assertDictEqual(foo_builder, foo_expected)
        self.assertDictEqual(bar1_builder, bar1_expected)
        self.assertDictEqual(bar2_builder, bar2_expected)

    def test_build_attr_ref_invalid(self):
        ''' Test default mapping functionality when one container contains an attribute reference to another container.
        '''
        bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10)
        bar_inst1._Bar__foo = object()  # make foo object a non-container type

        msg = "invalid type for reference 'foo' (<class 'object'>) - must be AbstractContainer"
        with self.assertRaisesWith(ValueError, msg):
            self.bar_mapper.build(bar_inst1, self.manager)
Ejemplo n.º 20
0
class TestLinkedContainer(TestCase):
    def setUp(self):
        self.foo_spec = GroupSpec(
            'A test group specification with data type Foo',
            data_type_def='Foo')
        self.bar_spec = GroupSpec(
            'A test group specification with a data type Bar',
            data_type_def='Bar',
            groups=[self.foo_spec],
            datasets=[DatasetSpec('an example dataset', 'int', name='data')],
            attributes=[
                AttributeSpec('attr1', 'an example string attribute', 'text'),
                AttributeSpec('attr2', 'an example integer attribute', 'int')
            ])

        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.foo_spec, 'test.yaml')
        self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
        self.manager = BuildManager(self.type_map)
        self.foo_mapper = ObjectMapper(self.foo_spec)
        self.bar_mapper = ObjectMapper(self.bar_spec)

    def test_build_child_link(self):
        ''' Test default mapping functionality when one container contains a child link to another container '''
        foo_inst = Foo('my_foo')
        bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10, foo=foo_inst)
        # bar_inst2.foo should link to bar_inst1.foo
        bar_inst2 = Bar('my_bar2', list(range(10)), 'value1', 10, foo=foo_inst)

        foo_builder = self.foo_mapper.build(foo_inst, self.manager)
        bar1_builder = self.bar_mapper.build(bar_inst1, self.manager)
        bar2_builder = self.bar_mapper.build(bar_inst2, self.manager)

        foo_expected = GroupBuilder('my_foo')

        inner_foo_builder = GroupBuilder('my_foo',
                                         attributes={
                                             'data_type': 'Foo',
                                             'namespace': CORE_NAMESPACE,
                                             'object_id': foo_inst.object_id
                                         })
        bar1_expected = GroupBuilder(
            'my_bar1',
            datasets={'data': DatasetBuilder('data', list(range(10)))},
            groups={'foo': inner_foo_builder},
            attributes={
                'attr1': 'value1',
                'attr2': 10
            })
        link_foo_builder = LinkBuilder(builder=inner_foo_builder)
        bar2_expected = GroupBuilder(
            'my_bar2',
            datasets={'data': DatasetBuilder('data', list(range(10)))},
            links={'foo': link_foo_builder},
            attributes={
                'attr1': 'value1',
                'attr2': 10
            })
        self.assertBuilderEqual(foo_builder, foo_expected)
        self.assertBuilderEqual(bar1_builder, bar1_expected)
        self.assertBuilderEqual(bar2_builder, bar2_expected)

    @unittest.expectedFailure
    def test_build_broken_link_parent(self):
        ''' Test that building a container with a broken link that has a parent raises an error. '''
        foo_inst = Foo('my_foo')
        Bar('my_bar1', list(range(10)), 'value1', 10,
            foo=foo_inst)  # foo_inst.parent is this bar
        # bar_inst2.foo should link to bar_inst1.foo
        bar_inst2 = Bar('my_bar2', list(range(10)), 'value1', 10, foo=foo_inst)

        # TODO bar_inst.foo.parent exists but is never built - this is a tricky edge case that should raise an error
        with self.assertRaises(OrphanContainerBuildError):
            self.bar_mapper.build(bar_inst2, self.manager)

    def test_build_broken_link_no_parent(self):
        ''' Test that building a container with a broken link that has no parent raises an error. '''
        foo_inst = Foo('my_foo')
        bar_inst1 = Bar('my_bar1', list(range(10)), 'value1', 10,
                        foo=foo_inst)  # foo_inst.parent is this bar
        # bar_inst2.foo should link to bar_inst1.foo
        bar_inst2 = Bar('my_bar2', list(range(10)), 'value1', 10, foo=foo_inst)
        bar_inst1.remove_foo()

        msg = (
            "my_bar2 (my_bar2): Linked Foo 'my_foo' has no parent. Remove the link or ensure the linked container "
            "is added properly.")
        with self.assertRaisesWith(OrphanContainerBuildError, msg):
            self.bar_mapper.build(bar_inst2, self.manager)
Ejemplo n.º 21
0
class TestBaseProcessFieldSpec(TestCase):
    def setUp(self):
        self.bar_spec = GroupSpec(
            doc='A test group specification with a data type',
            data_type_def='EmptyBar')
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       version='0.1.0',
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'EmptyBar',
                                              EmptyBar)

    def test_update_docval(self):
        """Test update_docval_args for a variety of data types and mapping configurations."""
        spec = GroupSpec(
            doc="A test group specification with a data type",
            data_type_def="Baz",
            groups=[
                GroupSpec(doc="a group",
                          data_type_inc="EmptyBar",
                          quantity="?")
            ],
            datasets=[
                DatasetSpec(
                    doc="a dataset",
                    dtype="int",
                    name="data",
                    attributes=[
                        AttributeSpec(name="attr2",
                                      doc="an integer attribute",
                                      dtype="int")
                    ],
                )
            ],
            attributes=[
                AttributeSpec(name="attr1",
                              doc="a string attribute",
                              dtype="text"),
                AttributeSpec(name="attr3",
                              doc="a numeric attribute",
                              dtype="numeric"),
                AttributeSpec(name="attr4",
                              doc="a float attribute",
                              dtype="float"),
            ],
        )

        expected = [
            {
                'name': 'data',
                'type': (int, np.int32, np.int64),
                'doc': 'a dataset'
            },
            {
                'name': 'attr1',
                'type': str,
                'doc': 'a string attribute'
            },
            {
                'name': 'attr2',
                'type': (int, np.int32, np.int64),
                'doc': 'an integer attribute'
            },
            {
                'name':
                'attr3',
                'doc':
                'a numeric attribute',
                'type':
                (float, np.float32, np.float64, np.int8, np.int16, np.int32,
                 np.int64, int, np.uint8, np.uint16, np.uint32, np.uint64)
            },
            {
                'name': 'attr4',
                'doc': 'a float attribute',
                'type': (float, np.float32, np.float64)
            },
            {
                'name': 'bar',
                'type': EmptyBar,
                'doc': 'a group',
                'default': None
            },
        ]

        not_inherited_fields = {
            'data': spec.get_dataset('data'),
            'attr1': spec.get_attribute('attr1'),
            'attr2': spec.get_dataset('data').get_attribute('attr2'),
            'attr3': spec.get_attribute('attr3'),
            'attr4': spec.get_attribute('attr4'),
            'bar': spec.groups[0]
        }

        docval_args = list()
        for i, attr_name in enumerate(not_inherited_fields):
            with self.subTest(attr_name=attr_name):
                CustomClassGenerator.process_field_spec(
                    classdict={},
                    docval_args=docval_args,
                    parent_cls=EmptyBar,  # <-- arbitrary class
                    attr_name=attr_name,
                    not_inherited_fields=not_inherited_fields,
                    type_map=self.type_map,
                    spec=spec)
                self.assertListEqual(docval_args, expected[:(
                    i + 1)])  # compare with the first i elements of expected

    def test_update_docval_attr_shape(self):
        """Test that update_docval_args for an attribute with shape sets the type and shape keys."""
        spec = GroupSpec(doc='A test group specification with a data type',
                         data_type_def='Baz',
                         attributes=[
                             AttributeSpec(name='attr1',
                                           doc='a string attribute',
                                           dtype='text',
                                           shape=[None])
                         ])
        not_inherited_fields = {'attr1': spec.get_attribute('attr1')}

        docval_args = list()
        CustomClassGenerator.process_field_spec(
            classdict={},
            docval_args=docval_args,
            parent_cls=EmptyBar,  # <-- arbitrary class
            attr_name='attr1',
            not_inherited_fields=not_inherited_fields,
            type_map=TypeMap(),
            spec=spec)

        expected = [{
            'name': 'attr1',
            'type': ('array_data', 'data'),
            'doc': 'a string attribute',
            'shape': [None]
        }]
        self.assertListEqual(docval_args, expected)

    def test_update_docval_dset_shape(self):
        """Test that update_docval_args for a dataset with shape sets the type and shape keys."""
        spec = GroupSpec(doc='A test group specification with a data type',
                         data_type_def='Baz',
                         datasets=[
                             DatasetSpec(name='dset1',
                                         doc='a string dataset',
                                         dtype='text',
                                         shape=[None])
                         ])
        not_inherited_fields = {'dset1': spec.get_dataset('dset1')}

        docval_args = list()
        CustomClassGenerator.process_field_spec(
            classdict={},
            docval_args=docval_args,
            parent_cls=EmptyBar,  # <-- arbitrary class
            attr_name='dset1',
            not_inherited_fields=not_inherited_fields,
            type_map=TypeMap(),
            spec=spec)

        expected = [{
            'name': 'dset1',
            'type': ('array_data', 'data'),
            'doc': 'a string dataset',
            'shape': [None]
        }]
        self.assertListEqual(docval_args, expected)

    def test_update_docval_default_value(self):
        """Test that update_docval_args for an optional field with default value sets the default key."""
        spec = GroupSpec(doc='A test group specification with a data type',
                         data_type_def='Baz',
                         attributes=[
                             AttributeSpec(name='attr1',
                                           doc='a string attribute',
                                           dtype='text',
                                           required=False,
                                           default_value='value')
                         ])
        not_inherited_fields = {'attr1': spec.get_attribute('attr1')}

        docval_args = list()
        CustomClassGenerator.process_field_spec(
            classdict={},
            docval_args=docval_args,
            parent_cls=EmptyBar,  # <-- arbitrary class
            attr_name='attr1',
            not_inherited_fields=not_inherited_fields,
            type_map=TypeMap(),
            spec=spec)

        expected = [{
            'name': 'attr1',
            'type': str,
            'doc': 'a string attribute',
            'default': 'value'
        }]
        self.assertListEqual(docval_args, expected)

    def test_update_docval_default_value_none(self):
        """Test that update_docval_args for an optional field sets default: None."""
        spec = GroupSpec(doc='A test group specification with a data type',
                         data_type_def='Baz',
                         attributes=[
                             AttributeSpec(name='attr1',
                                           doc='a string attribute',
                                           dtype='text',
                                           required=False)
                         ])
        not_inherited_fields = {'attr1': spec.get_attribute('attr1')}

        docval_args = list()
        CustomClassGenerator.process_field_spec(
            classdict={},
            docval_args=docval_args,
            parent_cls=EmptyBar,  # <-- arbitrary class
            attr_name='attr1',
            not_inherited_fields=not_inherited_fields,
            type_map=TypeMap(),
            spec=spec)

        expected = [{
            'name': 'attr1',
            'type': str,
            'doc': 'a string attribute',
            'default': None
        }]
        self.assertListEqual(docval_args, expected)

    def test_update_docval_default_value_none_required_parent(self):
        """Test that update_docval_args for an optional field with a required parent sets default: None."""
        spec = GroupSpec(doc='A test group specification with a data type',
                         data_type_def='Baz',
                         groups=[
                             GroupSpec(name='group1',
                                       doc='required untyped group',
                                       attributes=[
                                           AttributeSpec(
                                               name='attr1',
                                               doc='a string attribute',
                                               dtype='text',
                                               required=False)
                                       ])
                         ])
        not_inherited_fields = {
            'attr1': spec.get_group('group1').get_attribute('attr1')
        }

        docval_args = list()
        CustomClassGenerator.process_field_spec(
            classdict={},
            docval_args=docval_args,
            parent_cls=EmptyBar,  # <-- arbitrary class
            attr_name='attr1',
            not_inherited_fields=not_inherited_fields,
            type_map=TypeMap(),
            spec=spec)

        expected = [{
            'name': 'attr1',
            'type': str,
            'doc': 'a string attribute',
            'default': None
        }]
        self.assertListEqual(docval_args, expected)

    def test_update_docval_required_field_optional_parent(self):
        """Test that update_docval_args for a required field with an optional parent sets default: None."""
        spec = GroupSpec(doc='A test group specification with a data type',
                         data_type_def='Baz',
                         groups=[
                             GroupSpec(name='group1',
                                       doc='required untyped group',
                                       attributes=[
                                           AttributeSpec(
                                               name='attr1',
                                               doc='a string attribute',
                                               dtype='text')
                                       ],
                                       quantity='?')
                         ])
        not_inherited_fields = {
            'attr1': spec.get_group('group1').get_attribute('attr1')
        }

        docval_args = list()
        CustomClassGenerator.process_field_spec(
            classdict={},
            docval_args=docval_args,
            parent_cls=EmptyBar,  # <-- arbitrary class
            attr_name='attr1',
            not_inherited_fields=not_inherited_fields,
            type_map=TypeMap(),
            spec=spec)

        expected = [{
            'name': 'attr1',
            'type': str,
            'doc': 'a string attribute',
            'default': None
        }]
        self.assertListEqual(docval_args, expected)

    def test_process_field_spec_overwrite(self):
        """Test that docval generation overwrites previous docval args."""
        spec = GroupSpec(doc='A test group specification with a data type',
                         data_type_def='Baz',
                         attributes=[
                             AttributeSpec(name='attr1',
                                           doc='a string attribute',
                                           dtype='text',
                                           shape=[None])
                         ])
        not_inherited_fields = {'attr1': spec.get_attribute('attr1')}

        docval_args = [
            {
                'name': 'attr1',
                'type': ('array_data', 'data'),
                'doc': 'a string attribute',
                'shape': [[None], [None, None]]
            },  # this dict will be overwritten below
            {
                'name': 'attr2',
                'type': ('array_data', 'data'),
                'doc': 'a string attribute',
                'shape': [[None], [None, None]]
            }
        ]
        CustomClassGenerator.process_field_spec(
            classdict={},
            docval_args=docval_args,
            parent_cls=EmptyBar,  # <-- arbitrary class
            attr_name='attr1',
            not_inherited_fields=not_inherited_fields,
            type_map=TypeMap(),
            spec=spec)

        expected = [{
            'name': 'attr1',
            'type': ('array_data', 'data'),
            'doc': 'a string attribute',
            'shape': [None]
        }, {
            'name': 'attr2',
            'type': ('array_data', 'data'),
            'doc': 'a string attribute',
            'shape': [[None], [None, None]]
        }]
        self.assertListEqual(docval_args, expected)

    def test_process_field_spec_link(self):
        """Test that processing a link spec does not set child=True in __fields__."""
        classdict = {}
        not_inherited_fields = {
            'attr3': LinkSpec(name='attr3',
                              target_type='EmptyBar',
                              doc='a link')
        }
        CustomClassGenerator.process_field_spec(
            classdict=classdict,
            docval_args=[],
            parent_cls=EmptyBar,  # <-- arbitrary class
            attr_name='attr3',
            not_inherited_fields=not_inherited_fields,
            type_map=self.type_map,
            spec=GroupSpec('dummy', 'doc'))

        expected = {'__fields__': [{'name': 'attr3', 'doc': 'a link'}]}
        self.assertDictEqual(classdict, expected)

    def test_post_process_fixed_name(self):
        """Test that docval generation for a class with a fixed name does not contain a docval arg for name."""
        spec = GroupSpec(
            doc='A test group specification with a data type',
            data_type_def='Baz',
            name='MyBaz',  # <-- fixed name
            attributes=[
                AttributeSpec(name='attr1',
                              doc='a string attribute',
                              dtype='text',
                              shape=[None])
            ])

        classdict = {}
        bases = [Container]
        docval_args = [{
            'name': 'name',
            'type': str,
            'doc': 'name'
        }, {
            'name': 'attr1',
            'type': ('array_data', 'data'),
            'doc': 'a string attribute',
            'shape': [None]
        }]
        CustomClassGenerator.post_process(classdict, bases, docval_args, spec)

        expected = [{
            'name': 'attr1',
            'type': ('array_data', 'data'),
            'doc': 'a string attribute',
            'shape': [None]
        }]
        self.assertListEqual(docval_args, expected)

    def test_post_process_default_name(self):
        """Test that docval generation for a class with a default name has the default value for name set."""
        spec = GroupSpec(
            doc='A test group specification with a data type',
            data_type_def='Baz',
            default_name='MyBaz',  # <-- default name
            attributes=[
                AttributeSpec(name='attr1',
                              doc='a string attribute',
                              dtype='text',
                              shape=[None])
            ])

        classdict = {}
        bases = [Container]
        docval_args = [{
            'name': 'name',
            'type': str,
            'doc': 'name'
        }, {
            'name': 'attr1',
            'type': ('array_data', 'data'),
            'doc': 'a string attribute',
            'shape': [None]
        }]
        CustomClassGenerator.post_process(classdict, bases, docval_args, spec)

        expected = [{
            'name': 'name',
            'type': str,
            'doc': 'name',
            'default': 'MyBaz'
        }, {
            'name': 'attr1',
            'type': ('array_data', 'data'),
            'doc': 'a string attribute',
            'shape': [None]
        }]
        self.assertListEqual(docval_args, expected)
Ejemplo n.º 22
0
class TestDynamicContainer(unittest.TestCase):
    def setUp(self):
        self.bar_spec = GroupSpec(
            'A test group specification with a data type',
            data_type_def='Bar',
            datasets=[
                DatasetSpec('an example dataset',
                            'int',
                            name='data',
                            attributes=[
                                AttributeSpec('attr2',
                                              'an example integer attribute',
                                              'int')
                            ])
            ],
            attributes=[
                AttributeSpec('attr1', 'an example string attribute', 'text')
            ])
        self.spec_catalog = SpecCatalog()
        self.spec_catalog.register_spec(self.bar_spec, 'test.yaml')
        self.namespace = SpecNamespace('a test namespace',
                                       CORE_NAMESPACE, [{
                                           'source': 'test.yaml'
                                       }],
                                       catalog=self.spec_catalog)
        self.namespace_catalog = NamespaceCatalog()
        self.namespace_catalog.add_namespace(CORE_NAMESPACE, self.namespace)
        self.type_map = TypeMap(self.namespace_catalog)
        self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
        self.type_map.register_map(Bar, ObjectMapper)
        self.manager = BuildManager(self.type_map)
        self.mapper = ObjectMapper(self.bar_spec)

    def test_dynamic_container_creation(self):
        baz_spec = GroupSpec(
            'A test extension with no Container class',
            data_type_def='Baz',
            data_type_inc=self.bar_spec,
            attributes=[
                AttributeSpec('attr3', 'an example float attribute', 'float'),
                AttributeSpec('attr4', 'another example float attribute',
                              'float')
            ])
        self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
        cls = self.type_map.get_container_cls(CORE_NAMESPACE, 'Baz')
        expected_args = {'name', 'data', 'attr1', 'attr2', 'attr3', 'attr4'}
        received_args = set()
        for x in get_docval(cls.__init__):
            received_args.add(x['name'])
            with self.subTest(name=x['name']):
                self.assertNotIn('default', x)
        self.assertSetEqual(expected_args, received_args)
        self.assertEqual(cls.__name__, 'Baz')
        self.assertTrue(issubclass(cls, Bar))

    def test_dynamic_container_creation_defaults(self):
        baz_spec = GroupSpec(
            'A test extension with no Container class',
            data_type_def='Baz',
            data_type_inc=self.bar_spec,
            attributes=[
                AttributeSpec('attr3', 'an example float attribute', 'float'),
                AttributeSpec('attr4', 'another example float attribute',
                              'float')
            ])
        self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
        cls = self.type_map.get_container_cls(CORE_NAMESPACE, 'Baz')
        expected_args = {'name', 'data', 'attr1', 'attr2', 'attr3', 'attr4'}
        received_args = set(map(lambda x: x['name'], get_docval(cls.__init__)))
        self.assertSetEqual(expected_args, received_args)
        self.assertEqual(cls.__name__, 'Baz')
        self.assertTrue(issubclass(cls, Bar))

    def test_dynamic_container_constructor(self):
        baz_spec = GroupSpec(
            'A test extension with no Container class',
            data_type_def='Baz',
            data_type_inc=self.bar_spec,
            attributes=[
                AttributeSpec('attr3', 'an example float attribute', 'float'),
                AttributeSpec('attr4', 'another example float attribute',
                              'float')
            ])
        self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
        cls = self.type_map.get_container_cls(CORE_NAMESPACE, 'Baz')
        # TODO: test that constructor works!
        inst = cls('My Baz', [1, 2, 3, 4],
                   'string attribute',
                   1000,
                   attr3=98.6,
                   attr4=1.0)
        self.assertEqual(inst.name, 'My Baz')
        self.assertEqual(inst.data, [1, 2, 3, 4])
        self.assertEqual(inst.attr1, 'string attribute')
        self.assertEqual(inst.attr2, 1000)
        self.assertEqual(inst.attr3, 98.6)
        self.assertEqual(inst.attr4, 1.0)

    def test_dynamic_container_constructor_name(self):
        # name is specified in spec and cannot be changed
        baz_spec = GroupSpec(
            'A test extension with no Container class',
            data_type_def='Baz',
            data_type_inc=self.bar_spec,
            name='A fixed name',
            attributes=[
                AttributeSpec('attr3', 'an example float attribute', 'float'),
                AttributeSpec('attr4', 'another example float attribute',
                              'float')
            ])
        self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
        cls = self.type_map.get_container_cls(CORE_NAMESPACE, 'Baz')

        with self.assertRaises(TypeError):
            inst = cls('My Baz', [1, 2, 3, 4],
                       'string attribute',
                       1000,
                       attr3=98.6,
                       attr4=1.0)

        inst = cls([1, 2, 3, 4],
                   'string attribute',
                   1000,
                   attr3=98.6,
                   attr4=1.0)
        self.assertEqual(inst.name, 'A fixed name')
        self.assertEqual(inst.data, [1, 2, 3, 4])
        self.assertEqual(inst.attr1, 'string attribute')
        self.assertEqual(inst.attr2, 1000)
        self.assertEqual(inst.attr3, 98.6)
        self.assertEqual(inst.attr4, 1.0)

    def test_dynamic_container_constructor_name_default_name(self):
        # if both name and default_name are specified, name should be used
        with self.assertWarns(Warning):
            baz_spec = GroupSpec(
                'A test extension with no Container class',
                data_type_def='Baz',
                data_type_inc=self.bar_spec,
                name='A fixed name',
                default_name='A default name',
                attributes=[
                    AttributeSpec('attr3', 'an example float attribute',
                                  'float'),
                    AttributeSpec('attr4', 'another example float attribute',
                                  'float')
                ])
            self.spec_catalog.register_spec(baz_spec, 'extension.yaml')
            cls = self.type_map.get_container_cls(CORE_NAMESPACE, 'Baz')

            inst = cls([1, 2, 3, 4],
                       'string attribute',
                       1000,
                       attr3=98.6,
                       attr4=1.0)
            self.assertEqual(inst.name, 'A fixed name')
Ejemplo n.º 23
0
def _get_manager():

    foo_spec = GroupSpec('A test group specification with a data type',
                         data_type_def='Foo',
                         datasets=[DatasetSpec('an example dataset',
                                               'int',
                                               name='my_data',
                                               attributes=[AttributeSpec('attr2',
                                                                         'an example integer attribute',
                                                                         'int')])],
                         attributes=[AttributeSpec('attr1', 'an example string attribute', 'text')])

    tmp_spec = GroupSpec('A subgroup for Foos',
                         name='foo_holder',
                         groups=[GroupSpec('the Foos in this bucket', data_type_inc='Foo', quantity=ZERO_OR_MANY)])

    bucket_spec = GroupSpec('A test group specification for a data type containing data type',
                            data_type_def='FooBucket',
                            groups=[tmp_spec])

    class BucketMapper(ObjectMapper):
        def __init__(self, spec):
            super(BucketMapper, self).__init__(spec)
            foo_spec = spec.get_group('foo_holder').get_data_type('Foo')
            self.map_spec('foos', foo_spec)

    file_spec = GroupSpec("A file of Foos contained in FooBuckets",
                          name='root',
                          data_type_def='FooFile',
                          groups=[GroupSpec('Holds the FooBuckets',
                                            name='buckets',
                                            groups=[GroupSpec("One ore more FooBuckets",
                                                              data_type_inc='FooBucket',
                                                              quantity=ONE_OR_MANY)])])

    class FileMapper(ObjectMapper):
        def __init__(self, spec):
            super(FileMapper, self).__init__(spec)
            bucket_spec = spec.get_group('buckets').get_data_type('FooBucket')
            self.map_spec('buckets', bucket_spec)

    spec_catalog = SpecCatalog()
    spec_catalog.register_spec(foo_spec, 'test.yaml')
    spec_catalog.register_spec(bucket_spec, 'test.yaml')
    spec_catalog.register_spec(file_spec, 'test.yaml')
    namespace = SpecNamespace(
        'a test namespace',
        CORE_NAMESPACE,
        [{'source': 'test.yaml'}],
        catalog=spec_catalog)
    namespace_catalog = NamespaceCatalog()
    namespace_catalog.add_namespace(CORE_NAMESPACE, namespace)
    type_map = TypeMap(namespace_catalog)

    type_map.register_container_type(CORE_NAMESPACE, 'Foo', Foo)
    type_map.register_container_type(CORE_NAMESPACE, 'FooBucket', FooBucket)
    type_map.register_container_type(CORE_NAMESPACE, 'FooFile', FooFile)

    type_map.register_map(FooBucket, BucketMapper)
    type_map.register_map(FooFile, FileMapper)

    manager = BuildManager(type_map)
    return manager
Ejemplo n.º 24
0
class TestGetClassSeparateNamespace(TestCase):
    def setUp(self):
        self.test_dir = tempfile.mkdtemp()
        if os.path.exists(self.test_dir):  # start clean
            self.tearDown()
        os.mkdir(self.test_dir)

        self.bar_spec = GroupSpec(
            doc='A test group specification with a data type',
            data_type_def='Bar',
            datasets=[DatasetSpec(name='data', doc='a dataset', dtype='int')],
            attributes=[
                AttributeSpec(name='attr1',
                              doc='a string attribute',
                              dtype='text'),
                AttributeSpec(name='attr2',
                              doc='an integer attribute',
                              dtype='int')
            ])
        self.type_map = TypeMap()
        create_load_namespace_yaml(namespace_name=CORE_NAMESPACE,
                                   specs=[self.bar_spec],
                                   output_dir=self.test_dir,
                                   incl_types=dict(),
                                   type_map=self.type_map)

    def tearDown(self):
        shutil.rmtree(self.test_dir)

    def test_get_class_separate_ns(self):
        """Test that get_class correctly sets the name and type hierarchy across namespaces."""
        self.type_map.register_container_type(CORE_NAMESPACE, 'Bar', Bar)
        baz_spec = GroupSpec(
            doc='A test extension',
            data_type_def='Baz',
            data_type_inc='Bar',
        )
        create_load_namespace_yaml(namespace_name='ndx-test',
                                   specs=[baz_spec],
                                   output_dir=self.test_dir,
                                   incl_types={CORE_NAMESPACE: ['Bar']},
                                   type_map=self.type_map)

        cls = self.type_map.get_dt_container_cls('Baz', 'ndx-test')
        self.assertEqual(cls.__name__, 'Baz')
        self.assertTrue(issubclass(cls, Bar))

    def _build_separate_namespaces(self):
        # create an empty extension to test ClassGenerator._get_container_type resolution
        # the Bar class has not been mapped yet to the bar spec
        qux_spec = DatasetSpec(doc='A test extension', data_type_def='Qux')
        spam_spec = DatasetSpec(doc='A test extension', data_type_def='Spam')
        create_load_namespace_yaml(namespace_name='ndx-qux',
                                   specs=[qux_spec, spam_spec],
                                   output_dir=self.test_dir,
                                   incl_types={},
                                   type_map=self.type_map)
        # resolve Spam first so that ndx-qux is resolved first
        self.type_map.get_dt_container_cls('Spam', 'ndx-qux')

        baz_spec = GroupSpec(doc='A test extension',
                             data_type_def='Baz',
                             data_type_inc='Bar',
                             groups=[
                                 GroupSpec(data_type_inc='Qux',
                                           doc='a qux',
                                           quantity='?'),
                                 GroupSpec(data_type_inc='Bar',
                                           doc='a bar',
                                           quantity='?')
                             ])
        create_load_namespace_yaml(namespace_name='ndx-test',
                                   specs=[baz_spec],
                                   output_dir=self.test_dir,
                                   incl_types={
                                       CORE_NAMESPACE: ['Bar'],
                                       'ndx-qux': ['Qux']
                                   },
                                   type_map=self.type_map)

    def _check_classes(self, baz_cls, bar_cls, bar_cls2, qux_cls, qux_cls2):
        self.assertEqual(qux_cls.__name__, 'Qux')
        self.assertEqual(baz_cls.__name__, 'Baz')
        self.assertEqual(bar_cls.__name__, 'Bar')
        self.assertIs(bar_cls,
                      bar_cls2)  # same class, two different namespaces
        self.assertIs(qux_cls, qux_cls2)
        self.assertTrue(issubclass(qux_cls, Data))
        self.assertTrue(issubclass(baz_cls, bar_cls))
        self.assertTrue(issubclass(bar_cls, Container))

        qux_inst = qux_cls(name='qux_name', data=[1])
        bar_inst = bar_cls(name='bar_name',
                           data=100,
                           attr1='a string',
                           attr2=10)
        baz_inst = baz_cls(name='baz_name',
                           qux=qux_inst,
                           bar=bar_inst,
                           data=100,
                           attr1='a string',
                           attr2=10)
        self.assertIs(baz_inst.qux, qux_inst)

    def test_get_class_include_from_separate_ns_1(self):
        """Test that get_class correctly sets the name and includes types correctly across namespaces.
        This is one of multiple tests carried out to ensure that order of which get_dt_container_cls is called
        does not impact the results

        first use EXTENSION namespace, then use ORIGINAL namespace
        """
        self._build_separate_namespaces()

        baz_cls = self.type_map.get_dt_container_cls(
            'Baz', 'ndx-test')  # Qux and Bar are not yet resolved
        bar_cls = self.type_map.get_dt_container_cls('Bar', 'ndx-test')
        bar_cls2 = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
        qux_cls = self.type_map.get_dt_container_cls('Qux', 'ndx-test')
        qux_cls2 = self.type_map.get_dt_container_cls('Qux', 'ndx-qux')

        self._check_classes(baz_cls, bar_cls, bar_cls2, qux_cls, qux_cls2)

    def test_get_class_include_from_separate_ns_2(self):
        """Test that get_class correctly sets the name and includes types correctly across namespaces.
        This is one of multiple tests carried out to ensure that order of which get_dt_container_cls is called
        does not impact the results

        first use ORIGINAL namespace, then use EXTENSION namespace
        """
        self._build_separate_namespaces()

        baz_cls = self.type_map.get_dt_container_cls(
            'Baz', 'ndx-test')  # Qux and Bar are not yet resolved
        bar_cls2 = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
        bar_cls = self.type_map.get_dt_container_cls('Bar', 'ndx-test')
        qux_cls = self.type_map.get_dt_container_cls('Qux', 'ndx-test')
        qux_cls2 = self.type_map.get_dt_container_cls('Qux', 'ndx-qux')

        self._check_classes(baz_cls, bar_cls, bar_cls2, qux_cls, qux_cls2)

    def test_get_class_include_from_separate_ns_3(self):
        """Test that get_class correctly sets the name and includes types correctly across namespaces.
        This is one of multiple tests carried out to ensure that order of which get_dt_container_cls is called
        does not impact the results

        first use EXTENSION namespace, then use EXTENSION namespace
        """
        self._build_separate_namespaces()

        baz_cls = self.type_map.get_dt_container_cls(
            'Baz', 'ndx-test')  # Qux and Bar are not yet resolved
        bar_cls = self.type_map.get_dt_container_cls('Bar', 'ndx-test')
        bar_cls2 = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
        qux_cls2 = self.type_map.get_dt_container_cls('Qux', 'ndx-qux')
        qux_cls = self.type_map.get_dt_container_cls('Qux', 'ndx-test')

        self._check_classes(baz_cls, bar_cls, bar_cls2, qux_cls, qux_cls2)

    def test_get_class_include_from_separate_ns_4(self):
        """Test that get_class correctly sets the name and includes types correctly across namespaces.
        This is one of multiple tests carried out to ensure that order of which get_dt_container_cls is called
        does not impact the results

        first use ORIGINAL namespace, then use EXTENSION namespace
        """
        self._build_separate_namespaces()

        baz_cls = self.type_map.get_dt_container_cls(
            'Baz', 'ndx-test')  # Qux and Bar are not yet resolved
        bar_cls2 = self.type_map.get_dt_container_cls('Bar', CORE_NAMESPACE)
        bar_cls = self.type_map.get_dt_container_cls('Bar', 'ndx-test')
        qux_cls2 = self.type_map.get_dt_container_cls('Qux', 'ndx-qux')
        qux_cls = self.type_map.get_dt_container_cls('Qux', 'ndx-test')

        self._check_classes(baz_cls, bar_cls, bar_cls2, qux_cls, qux_cls2)