def to_data(instance: CdmAttributeResolutionGuidanceDefinition,
                res_opt: ResolveOptions,
                options: CopyOptions) -> Optional[AttributeResolutionGuidance]:
        if not instance:
            return None

        result = AttributeResolutionGuidance()
        result.removeAttribute = instance.remove_attribute
        result.imposedDirectives = instance.imposed_directives
        result.removedDirectives = instance.removed_directives
        result.cardinality = instance.cardinality
        result.renameFormat = instance.rename_format

        if instance.add_supporting_attribute:
            result.addSupportingAttribute = PersistenceLayer.to_data(
                instance.add_supporting_attribute, res_opt, 'CdmFolder',
                options)

        if instance.expansion:
            result.expansion = Expansion()
            result.expansion.startingOrdinal = instance.expansion.starting_ordinal
            result.expansion.maximumExpansion = instance.expansion.maximum_expansion

            if instance.expansion.count_attribute:
                result.expansion.countAttribute = PersistenceLayer.to_data(
                    instance.expansion.count_attribute, res_opt, 'CdmFolder',
                    options)

        if instance.entity_by_reference:
            result.entityByReference = EntityByReference()
            result.entityByReference.allowReference = instance.entity_by_reference.allow_reference
            result.entityByReference.alwaysIncludeForeignKey = instance.entity_by_reference.always_include_foreign_key
            result.entityByReference.referenceOnlyAfterDepth = instance.entity_by_reference.reference_only_after_depth

            if instance.entity_by_reference.foreign_key_attribute:
                result.entityByReference.foreignKeyAttribute = PersistenceLayer.to_data(
                    instance.entity_by_reference.foreign_key_attribute,
                    res_opt, 'CdmFolder', options)

        if instance.selects_sub_attribute:
            result.selectsSubAttribute = SelectsSubAttribute()
            result.selectsSubAttribute.selects = instance.selects_sub_attribute.selects
            if instance.selects_sub_attribute.selected_type_attribute:
                result.selectsSubAttribute.selectedTypeAttribute = PersistenceLayer.to_data(
                    instance.selects_sub_attribute.selected_type_attribute,
                    res_opt, 'CdmFolder', options)
                result.selectsSubAttribute.selectsSomeTakeNames = instance.selects_sub_attribute.selects_some_take_names
                result.selectsSubAttribute.selectsSomeAvoidNames = instance.selects_sub_attribute.selects_some_avoid_names

        return result
예제 #2
0
    async def test_cdm_folder_to_data_type_attribute(self):
        """
        Testing that "is.localized.describedAs" trait with a table of three entries (en, rs and cn) is fully preserved when running CdmFolder TypeAttributePersistence ToData.
        """
        corpus = CdmCorpusDefinition()
        corpus.ctx.report_at_level = CdmStatusLevel.WARNING
        corpus.storage.mount('local', LocalAdapter('C:\\Root\\Path'))
        corpus.storage.default_namespace = 'local'

        cdm_type_attribute_definition = corpus.make_object(CdmObjectType.TYPE_ATTRIBUTE_DEF, 'TestSavingTraitAttribute', False)
        english_constants_list = ['en', 'Some description in English language']
        serbian_constants_list = ['sr', 'Opis na srpskom jeziku']
        chinese_constants_list = ['cn', '一些中文描述']
        list_of_const_lists = [english_constants_list, serbian_constants_list, chinese_constants_list]

        const_ent_def = corpus.make_object(CdmObjectType.CONSTANT_ENTITY_DEF, 'localizedDescriptions', False)
        const_ent_def.constant_values = list_of_const_lists
        const_ent_def.entity_shape = corpus.make_ref(CdmObjectType.ENTITY_REF, 'localizedTable', True)
        trait_reference2 = corpus.make_object(CdmObjectType.TRAIT_REF, 'is.localized.describedAs', False)
        trait_reference2.arguments.append('localizedDisplayText', corpus.make_ref(CdmObjectType.ENTITY_REF, const_ent_def, True))
        cdm_type_attribute_definition.applied_traits.append(trait_reference2)

        result = TypeAttribute().decode(PersistenceLayer.to_data(cdm_type_attribute_definition, None, None, PersistenceLayer.CDM_FOLDER))
        self.assertIsNotNone(result.appliedTraits)

        argument = result.appliedTraits[0].arguments[0]
        constant_values = argument.value.entityReference.constantValues

        self.assertEqual('en', constant_values[0][0])
        self.assertEqual('Some description in English language', constant_values[0][1])
        self.assertEqual('sr', constant_values[1][0])
        self.assertEqual('Opis na srpskom jeziku', constant_values[1][1])
        self.assertEqual('cn', constant_values[2][0])
        self.assertEqual('一些中文描述', constant_values[2][1])
예제 #3
0
    def to_data(instance: CdmAttributeContext, res_opt: ResolveOptions,
                options: CopyOptions) -> AttributeContext:
        result = AttributeContext()

        exhibits_traits = [
            trait for trait in instance.exhibits_traits
            if not trait.is_from_property
        ]

        result.explanation = instance.explanation
        result.name = instance.name
        result.type = map_enum_to_type_name[instance.type]
        result.parent = AttributeContextReferencePersistence.to_data(
            instance.parent, res_opt,
            options) if instance.parent is not None else None
        result.definition = PersistenceLayer.to_data(
            instance.definition, res_opt, options, PersistenceLayer.CDM_FOLDER
        ) if instance.definition is not None else None
        # I know the trait collection names look wrong. but I wanted to use the def baseclass
        result.appliedTraits = copy_data_utils._array_copy_data(
            res_opt, exhibits_traits, options)
        result.contents = copy_data_utils._array_copy_data(
            res_opt, instance.contents, options)

        return result
예제 #4
0
    def to_data(instance: CdmObjectReference, res_opt: ResolveOptions, options: CopyOptions) -> CdmJsonType:
        # We don't know what object we are creating to initialize to any
        copy = None
        replace = None

        if instance.named_reference:
            identifier = utils.copy_identifier_ref(instance, res_opt, options)
            if instance.simple_named_reference:
                return identifier

            replace = CdmObjectRefPersistence._copy_ref_data(instance, res_opt, copy, identifier, options)

            if replace:
                copy = replace

        elif instance.explicit_reference:
            er_copy = PersistenceLayer.to_data(instance.explicit_reference, res_opt, options, PersistenceLayer.CDM_FOLDER)
            replace = CdmObjectRefPersistence._copy_ref_data(instance, res_opt, copy, er_copy, options)

            if replace:
                copy = replace

        if instance.optional is not None:
            copy.optional = instance.optional

        if instance.applied_traits:
            # We don't know if the object we are copying has applied traits or not and hence use any
            copy.appliedTraits = copy_data_utils._array_copy_data(res_opt, instance.applied_traits, options)

        return copy
예제 #5
0
    async def test_from_and_to_data_with_elevated_traits(self):
        corpus = TestHelper.get_local_corpus(
            self.tests_subpath, 'test_from_and_to_data_with_elevated_traits')
        # need to set schema docs to the cdm namespace instead of using resources
        corpus.storage.mount("cdm",
                             LocalAdapter(TestHelper.get_schema_docs_root()))

        def callback(level, message):
            self.assertTrue('unable to resolve an entity' not in message)

        corpus.set_event_callback(callback, CdmStatusLevel.WARNING)

        entity = await corpus.fetch_object_async(
            'local:/Account.cdm.json/Account')  # type: CdmEntityDefinition
        res_entity = await entity.create_resolved_entity_async(
            '{}_'.format(entity.entity_name))  # type: CdmEntityDefinition
        PersistenceLayer.to_data(
            res_entity, ResolveOptions(wrt_doc=res_entity.in_document),
            CopyOptions(string_refs=True), PersistenceLayer.CDM_FOLDER)
예제 #6
0
    def fetch_value_string(self, res_opt: 'ResolveOptions') -> str:
        from cdm.objectmodel import CdmObject
        if self.value is None:
            return ''

        if isinstance(self.value, str):
            return self.value
        elif isinstance(self.value, CdmObject):
            # If this is a constant table, then expand into an HTML table.
            object_def = self.value.fetch_object_definition(
                res_opt)  # type: CdmConstantEntityDefinition
            if self.value.object_type == CdmObjectType.ENTITY_REF and object_def is not None and object_def.object_type == CdmObjectType.CONSTANT_ENTITY_DEF:
                ent_shape = object_def.entity_shape
                ent_values = object_def.constant_values
                if not ent_values:
                    return ''

                rows = []
                shape_atts = ent_shape._fetch_resolved_attributes(res_opt)

                if shape_atts is not None and shape_atts._set is not None:
                    for row_data in ent_values:
                        if not row_data:
                            continue

                        row = OrderedDict()
                        for (c, tvalue) in enumerate(row_data):
                            col_att = shape_atts._set[c]
                            if col_att is not None and tvalue is not None:
                                row[col_att.resolved_name] = tvalue

                        rows.append(row)

                rows_string = [self._spew_dict(row) for row in rows]

                return '[' + ','.join(rows_string) + ']'

            # Should be a reference to an object.

            from cdm.persistence import PersistenceLayer
            from cdm.utilities import CopyOptions
            data = PersistenceLayer.to_data(self.value, res_opt,
                                            CopyOptions(string_refs=False),
                                            PersistenceLayer.CDM_FOLDER)
            if isinstance(data, str):
                return data

            # TODO: the line bellow won't work, the result is going to be the address of the object.
            return str(data)
        else:
            return str(self.value)

        return ''
예제 #7
0
    def test_non_null_default_value_attribute(self):
        the_list = [{
            'languageTag': 'en',
            'displayText': 'Preferred Customer',
            'attributeValue': '1',
            'displayOrder': '0'
        },
        {
            'languageTag': 'en',
            'displayText': 'Standard',
            'attributeValue': '2',
            'displayOrder': '1'
        }]

        input = {'defaultValue': the_list}

        cdmTypeAttributeDefinition = PersistenceLayer.from_data(CdmCorpusContext(CdmCorpusDefinition(), None), JObject(input), CdmObjectType.TYPE_ATTRIBUTE_DEF, PersistenceLayer.CDM_FOLDER)

        result = PersistenceLayer.to_data(cdmTypeAttributeDefinition, None, None, PersistenceLayer.CDM_FOLDER)

        self.assertTrue(result)
        self.assertEqual(result.get('defaultValue'), input.get('defaultValue'))
예제 #8
0
    def to_data(instance: CdmParameterDefinition, res_opt: ResolveOptions,
                options: CopyOptions) -> Parameter:
        def_val = None

        if instance.default_value:
            if isinstance(instance.default_value, CdmObject):
                def_val = PersistenceLayer.to_data(instance.default_value,
                                                   res_opt, options,
                                                   PersistenceLayer.CDM_FOLDER)
            elif isinstance(instance.default_value, str):
                def_val = instance.default_value

        result = Parameter()
        result.name = instance.name
        result.dataType = PersistenceLayer.to_data(
            instance.data_type_ref, res_opt, options,
            PersistenceLayer.CDM_FOLDER) if instance.data_type_ref else None
        result.explanation = instance.explanation
        result.defaultValue = def_val
        result.required = instance.required

        return result
예제 #9
0
def array_copy_data(res_opt: ResolveOptions, source: Union['CdmCollection', List['CdmObject']], options: CopyOptions) -> Optional[List]:
    """Creates a list object that is a copy of the input IEnumerable object"""
    if not source:
        return None

    casted = []

    for elem in source:
        if elem:
            data = PersistenceLayer.to_data(elem, res_opt, 'CdmFolder', options)
            casted.append(data)

    return casted
예제 #10
0
def _array_copy_data(res_opt: 'ResolveOptions',
                     source: Union['CdmCollection', List['CdmObject']],
                     options: 'CopyOptions') -> Optional[List]:
    """Creates a list object that is a copy of the input IEnumerable object"""
    if not source:
        return None

    casted = []

    for elem in source:
        if elem:
            from cdm.persistence import PersistenceLayer
            data = PersistenceLayer.to_data(elem, res_opt, options,
                                            PersistenceLayer.CDM_FOLDER)
            casted.append(data)

    return casted
예제 #11
0
    def to_data(instance: 'CdmArgumentDefinition', res_opt: 'ResolveOptions',
                options: 'CopyOptions') -> CdmJsonType:
        from cdm.objectmodel import CdmObject

        value = None

        if instance.value is not None:
            if isinstance(instance.value, CdmObject):
                value = PersistenceLayer.to_data(instance.value, res_opt,
                                                 options,
                                                 PersistenceLayer.CDM_FOLDER)
            else:
                value = instance.value

        # Skip the argument if just a value
        if not instance.name:
            return value

        arg = Argument()
        arg.explanation = instance.explanation
        arg.name = instance.name
        arg.value = value
        return arg
예제 #12
0
    async def test_save_projection(self):
        """Basic test to save persisted Projections based entities"""
        corpus = TestHelper.get_local_corpus(self.tests_subpath, 'test_save_projection')  # type CdmCorpusDefinition

        manifest = await corpus.fetch_object_async('local:/default.manifest.cdm.json')  # type CdmManifestDefinition

        entity_sales = await corpus.fetch_object_async('local:/Sales.cdm.json/Sales', manifest)  # type CdmEntityDefinition
        self.assertIsNotNone(entity_sales)

        actual_root = corpus.storage.fetch_root_folder("output")  # type CdmFolderDefinition
        self.assertIsNotNone(actual_root)

        actual_root._documents.append(entity_sales.in_document, 'Persisted_Sales.cdm.json')
        await actual_root._documents.__getitem__(0).save_as_async('output:/Persisted_Sales.cdm.json')

        entity_actual = await corpus.fetch_object_async('output:/Persisted_Sales.cdm.json/Sales', manifest)  # type CdmEntityDefinition
        self.assertIsNotNone(entity_actual)

        entity_content_actual = PersistenceLayer.to_data(entity_actual, None, None, 'CdmFolder')  # type Entity
        self.assertIsNotNone(entity_content_actual)
        self.assertIsNotNone(entity_content_actual.hasAttributes)
        self.assertTrue(len(entity_content_actual.hasAttributes) == 1)
        self.assertFalse('"entityReference"' in str(entity_content_actual.hasAttributes[0]))